session.user extended with id prop

This commit is contained in:
2024-01-08 15:50:03 +01:00
parent cd9060c97e
commit adae452399
3 changed files with 36 additions and 5 deletions

View File

@@ -1,15 +1,34 @@
import NextAuth, { NextAuthConfig } from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import { Session } from 'next-auth';
const authConfig: NextAuthConfig = {
callbacks: {
// This method verifies if the user is logged in or not
// It is called by Next-Auth when the midleware calls
// the `auth` method (exported below)
// method verifies if the user is logged in or not
// -> is called by Next-Auth when the midleware calls the `auth` method (exported below)
authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = !!auth?.user;
return (isLoggedIn);
},
// method is called when the user is not logged in
// this is a hack which takes user ID and assigns it temporaty to the token, which is then used to extend Session.user
// see: https://stackoverflow.com/questions/70409219/get-user-id-from-session-in-next-auth-client
jwt({ token, account, user }) {
if (account) {
token.accessToken = account.access_token
token.id = user?.id
}
return token
},
// method is called after the JWT token is created
// this is a hack which takes user ID temporaty assigned to the token and assigns it to the Session.user
// see: https://stackoverflow.com/questions/70409219/get-user-id-from-session-in-next-auth-client
async session({ session, token }:{ session:Session, token:any }) {
if(session.user && token) {
session.user.id = token.id;
}
return session;
},
},
providers: [
GoogleProvider({