feat: Enhance session management in authentication
- Added email and name to the token during the sign-in process for improved user context. - Updated session callback to ensure session.user is populated with token data, including id, email, name, and role, while maintaining existing session data. - Added a warning for non-production environments when the token is missing or invalid.
This commit is contained in:
parent
888ffef8e3
commit
c0a1ed146f
16
lib/auth.ts
16
lib/auth.ts
@ -58,13 +58,23 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
|||||||
if (user) {
|
if (user) {
|
||||||
token.id = user.id
|
token.id = user.id
|
||||||
token.role = (user as { role: string }).role
|
token.role = (user as { role: string }).role
|
||||||
|
token.email = user.email
|
||||||
|
token.name = user.name
|
||||||
}
|
}
|
||||||
return token
|
return token
|
||||||
},
|
},
|
||||||
async session({ session, token }) {
|
async session({ session, token }) {
|
||||||
if (session.user) {
|
// Always ensure session.user exists when token exists
|
||||||
session.user.id = token.id as string
|
if (token && (token.id || token.email)) {
|
||||||
session.user.role = token.role as string
|
session.user = {
|
||||||
|
...session.user,
|
||||||
|
id: token.id as string,
|
||||||
|
email: (token.email as string) || session.user?.email || "",
|
||||||
|
name: (token.name as string) || session.user?.name || "",
|
||||||
|
role: token.role as string,
|
||||||
|
}
|
||||||
|
} else if (process.env.NODE_ENV !== "production") {
|
||||||
|
console.warn("Session callback: token missing or invalid", { token, session })
|
||||||
}
|
}
|
||||||
return session
|
return session
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user