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
版权声明:本文标题:authentication - How can I pass the other data from AuthJs and pass it to Middleware? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742309082a2450504.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论