authentication - How can I pass the other data from AuthJs and pass it to Middleware? - Stack Overflow

Is it possible to access other data coming from my Auth and pass it to middleware, I'm trying to p

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?

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742309082a4419527.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信