#how to secure my api's?

5 messages · Page 1 of 1 (latest)

river wraith
#

In a video I have been watching a little bit, this was his setup (almost)

  const session = await getServerSession(req, res, authOptions);
  if (!process.env.EMAILS?.includes(session?.user?.email)) {
    throw "Not Admin";
  }```

and I basically have a lot of different sort of routes that looks like this, both get, put, post etc
```javascript
export const PUT = async (req: NextRequest, res: Response) => {
  const body: kropp = await req.json();

  const {
    namn,
    fulltNamn,
    beskrivning,
    his

**More Code...**

but is there a go to method of doing this? because as you can see i am using next auth and I have therefore access to the session, how can i easily restrict these api ,or what every they are called, so that no other than the logged in user can do the request...

I appreciate all help 🙂

cloud wharfBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

      🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in <id:customize>

      ✅ You can mark a message as the answer for your post with `Right click -> Apps -> Mark Solution`
      (if you don't see the option, try refreshing Discord with Ctrl + R)
river wraith
#

I also tried

  const { data: session, status } = useSession();

  if (status === "unauthenticated") {
    throw "Not Admin";
  }

but I got: Error: React Context is unavailable in Server Components

#

I also tried :

 const token = await getToken({ req });

  if (token) {
    // Signed in
    console.log("JSON Web Token", JSON.stringify(token, null, 2));
  } else {
    // Not Signed in
    throw "Not Admin";
  }

but then I just got "not Admin" all the time even when signed in

river wraith
#

I now tried this:

  const session = await getServerSession(authOptions);

  if (!session) {
    throw "Not Admin";
  }

It seems to be working