-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
102 lines (95 loc) · 3.18 KB
/
auth.ts
File metadata and controls
102 lines (95 loc) · 3.18 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
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 || !profile) return false;
//if user already exist
const existingUser = await db.user.findUnique({
where: { email: user.email! },
});
// If user does not exist, create a new one
if (!existingUser) {
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; // if user creation fails
} else {
// link the account if user exists
const existingAccount = await db.account.findUnique({
where: {
provider_providerAccountId: {
provider: account.provider,
providerAccountId: account.providerAccountId,
},
},
});
if (!existingAccount) {
await db.account.create({
data: {
userId: existingUser.id,
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,
// @ts-ignore
sessionState: account.session_state,
},
});
}
}
return true;
},
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 }) {
// attach user id from token to session
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,
});