admin管理员组

文章数量:1332873

Is it possible to access other data coming from my Auth and pass it to middleware, I'm trying to prevent the other user to access other page if they have different affiliation. So for example, the user's affiliation === school, then if they tried to access /main they will redirected to /myaccount.

auth.ts

export const { handlers, signIn, signOut, auth } = NextAuth({
  pages: {
    signIn: '/auth/signin',
    error: '/auth/error',
  },
  callbacks: {
    async session({ session, token }) {
      if (session.user) {
        session.user.id = token.sub!;
        session.user.role = token.role as string;
        session.user.affiliation = token.affiliation as string;
    
      }
      return session;
    },
    async jwt({ token, user }) {
      if (user) {
        token.sub = user.id;
        token.role = user.role;
        //@ts-ignore
        token.affiliation = user.affiliation;

        
      } else if (token.sub) {
        const existingUser = await db.user.findUnique({
          where: { id: token.sub },
          select: {
            role: true,
            affiliation: true
          }
        });

        if (existingUser) {
          token.role = existingUser.role;
          //@ts-ignore
          token.affiliation = existingUser.affiliation;
        }
      }
      return token;
    },
  },
  adapter: PrismaAdapter(db) as any, // Type assertion to bypass the type error temporarily
  session: { strategy: "jwt" },
  ...authConfig,
});

middleware.ts

export const DEFAULT_LOGIN_AS_USERS = "/myaccount"
export const DEFAULT_LOGIN_REDIRECT = "/main"

//@ts-ignore
export default auth((req) => {
  //cHECK IF loggin or not
  const { nextUrl, auth: user } = req
  const isLoggedIn = !!req.auth

  

  if (isAuthRoutes) {
    if (isLoggedIn) {
      return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl))
    }
    return null
  }

  

  if (!isLoggedIn ) {
    return Response.redirect(new URL('/login', nextUrl))
  }

  return null;
})

schema.prisma

 id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  password      String?
  emailVerified DateTime?
  image         String?

本文标签: authenticationHow can I pass the other data from AuthJs and pass it to MiddlewareStack Overflow