-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
115 lines (96 loc) · 3.96 KB
/
auth.ts
File metadata and controls
115 lines (96 loc) · 3.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import NextAuth from 'next-auth';
import {PrismaAdapter} from '@auth/prisma-adapter';
import { db } from './lib/db';
import authConfig from './auth.config';
import { getAccountByUserId, getUserById } from './features/auth/actions';
export const {auth, handlers, signIn, signOut} = NextAuth({
callbacks:{
async signIn({user, account, profile}){
if(!user || !account) return false;
const existingUser = await db.user.findUnique({
where:{email:user.email!},
});
if(!existingUser){
// Create a new user if they don't exist
const newUser = await db.user.create({
data:{
email: user.email!,
name: user.name,
image: user.image,
accounts: {
// @ts-ignore
create: {
type: account.type,
provider: account.provider,
providerAccountId: account.providerAccountId,
refreshToken: account.refresh_token,
accessToken: account.access_token,
expiresAt: account.expires_at,
tokenType: account.token_type,
scope: account.scope,
idToken: account.id_token,
sessionState: account.session_state,
},
},
},
});
if(!newUser) {
return false; // User creation failed
}
}
else{
const existingAccount = await db.account.findUnique({
where: {
provider_providerAccountId: {
provider: account.provider,
providerAccountId: account.providerAccountId,
},
},
})
if(!existingAccount){
// Create a new account if it doesn't exist
await db.account.create({
data: {
userId: existingUser.id,
type: account.type,
provider: account.provider,
providerAccountId: account.providerAccountId,
accessToken: account.access_token,
refreshToken: account.refresh_token,
expiresAt: account.expires_at,
tokenType: account.token_type,
scope: account.scope,
idToken: account.id_token,
// @ts-ignore
sessionState: account.session_state,
},
});
}
}
return true; // Sign in successful
},
async jwt({token, user, account}){
if(!token.sub) return token;
const existingUser = await getUserById(token.sub);
if(!existingUser) return token;
const existingAccount = await getAccountByUserId(existingUser.id);
token.name = existingUser.name;
token.email = existingUser.email;
token.role = existingUser.role;
return token;
},
async session({session, token}){
if(token.sub && session.user){
session.user.id= token.sub;
}
if(token.sub && session.user){
session.user.role = token.role
}
return session;
}
},
secret: process.env.AUTH_SECRET,
adapter: PrismaAdapter(db),
session: {strategy: 'jwt'},
...authConfig
});