Skip to content
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

Open
Soneji opened this issue Nov 8, 2021 · 2 comments · May be fixed by #36
Open

Is there any easy way to protect a api route with this plugin? #25

Soneji opened this issue Nov 8, 2021 · 2 comments · May be fixed by #36

Comments

@Soneji
Copy link

Soneji commented Nov 8, 2021

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!
:)

@BJvdA
Copy link
Member

BJvdA commented Nov 9, 2021

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

@Soneji
Copy link
Author

Soneji commented Nov 9, 2021

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

@BJvdA BJvdA linked a pull request Dec 9, 2021 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants