-
Notifications
You must be signed in to change notification settings - Fork 22
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Is there any easy way to protect a api route with this plugin? #25
Comments
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 |
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!
:)
The text was updated successfully, but these errors were encountered: