-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.config.ts
71 lines (61 loc) · 1.43 KB
/
auth.config.ts
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
import { NextAuthConfig, User } from 'next-auth'
import Google from 'next-auth/providers/google'
import { Provider } from 'next-auth/providers'
import { UserLevel } from './src/types/global'
import { ADMINS } from './src/config'
import { prisma } from './src/prisma'
const getUserRoleByEmail = (email = ''): UserLevel =>
ADMINS.test(email) ? 'admin' : 'user'
const getProfile = (profile: any) =>
{
const object: User =
{
id: profile.sub,
email: profile.email,
name: profile.name,
image: profile.picture,
role: getUserRoleByEmail(profile.email)
}
return (object)
}
const providers: Provider[] =
[
Google({ profile: getProfile })
]
const callbacks: NextAuthConfig['callbacks'] =
{
async signIn({ user })
{
if (user && user.email)
{
const dbUser = await prisma.user
.findUnique({ where: { email: user.email } })
if (dbUser)
{
await prisma.user
.update({ where: { email: user.email }, data: { role: getUserRoleByEmail(user.email) } })
}
}
return true
},
async session({ session, token })
{
session.user.role = token.role as UserLevel
return session
},
async jwt({ token, user })
{
if(user)
token.role = user.role
return token
},
async redirect({ url, baseUrl })
{
return url.startsWith(baseUrl) ? url : baseUrl
}
}
export const authConfig: NextAuthConfig =
{
providers: providers,
callbacks: callbacks
}