Next.js Discord

Discord Forum

How can I get the rank from my session in my api?

Unanswered
Mike posted this in #help-forum
Open in Discord
How can I get the rank from my session in my api? the user object there only has email, name and image.

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
import { dbConnect, dbDisconnect } from "@/utils/database";
import User from "@/models/User";

const auth = NextAuth({
  session: {
    strategy: "jwt",
  },
  providers: [
    CredentialsProvider({
      async authorize(credentials, req) {
        await dbConnect();
        const { email, password } = credentials;
        const user = await User.findOne({ email });
        if (!user) {
          return null;
        }
        const isPasswordMatched = await bcrypt.compare(password, user.password);
        if (!isPasswordMatched) {
          return null;
        }
        return user;
      },
    }),
  ],
  callbacks: {
    jwt: async ({ token, user }) => {
      if(user)  {
        token.rank = user.rank
        token._id = user._id
      }
      return token
    },
    session: async ({ session, token }) => {
      session.user.rank = token.rank;
      session.user._id = token._id;
      return session;
    },
  },
  pages: {
    signIn: "/",
  },
  secret: process.env.NEXTAUTH_SECRET,
});

export { auth as POST, auth as GET, auth as nextAuthOptions };



  const session = await getServerSession(nextAuthOptions);
if (!session?.user.rank !== "admin" || !session?.user.rank !== "owner" || !session?.user.rank !== "leitung") {
    return Response.json(
      {
        message: "You dont have the Permissions to do that",
      },
      {
        status: 401,
      }
    );
  }

0 Replies