next-password-protect
next-password-protect copied to clipboard
Is there any easy way to protect a api route with this plugin?
Hi
I love this next plugin thing! It's so handy!
I was wondering if there exists any simple way to protect an API route with this plugin? I imagine it would be as simple as validating the cookie, but unsure how exactly to do so...
It could also be handy to do in a nextjs middleware too, now that those exist 😁
Thanks! :)
Glad you found this library helpful!
So if I understand correctly, you want someone to be able to access an API route after logging in? You could implement the same logic that is done in this file, to see if a user is "authenticated".
Let me know if that helps.
Also yes, I'm looking how this library could use nextjs middleware, so hopefully there will be an update soon
yup I managed to do that with this, if anybody wants to know for future reference:
import cookie from "cookie";
import jwt from "jsonwebtoken";
const csv = require("csvtojson");
const axios = require("axios");
const URL = process.env.SHEETS_URL;
export default async function handler(req, res) {
res.setHeader("Content-Type", "application/json");
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
res.setHeader("Pragma", "no-cache"); // HTTP 1.0.
res.setHeader("Expires", "0"); // Proxies.
const check = await passwordCheck(process.env.PASSWORD);
const checkRes = await check(req, res);
if (!checkRes) {
res.statusCode = 401;
res.end(JSON.stringify({ error: "Unauthorized" }));
return;
}
const { data } = await axios.get(URL);
const data_without_first_line = data.substring(data.indexOf("\n") + 1);
const json = await csv().fromString(data_without_first_line);
res.status(200).json(json);
}
export const passwordCheck = (password, options) => async (req) => {
try {
if (req.method !== "GET") {
throw new Error("Invalid method.");
}
if (req?.headers?.cookie) {
const cookies = cookie.parse(req.headers.cookie);
const cookieName = options?.cookieName || "next-password-protect";
jwt.verify(cookies?.[cookieName], password);
return true;
}
} catch (err) {
console.error(err);
}
return false;
};
https://github.com/kcsocwarwick/warwick-retreat-paylist/blob/master/pages/api/data.js
I was thinking though, it might be handy for the package to have a function that users can use to just validate before any api requests. What do you think?
Excited for the middleware update 😄
I think the best thing about this plugin is how easy it is to use and implement