-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
81 lines (67 loc) · 2.21 KB
/
Copy pathauth.ts
File metadata and controls
81 lines (67 loc) · 2.21 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
import NextAuth from "next-auth"
import {PrismaAdapter} from "@auth/prisma-adapter"
import {prisma} from "@/lib/prisma"
import Credentials from "next-auth/providers/credentials"
import {SignInSchema} from "@/lib/zod"
import {compareSync} from "bcrypt-ts"
export const {handlers, signIn, signOut, auth} = NextAuth({
adapter: PrismaAdapter(prisma),
session: {
strategy: "jwt"
},
pages: {
signIn: '/login'
},
providers: [Credentials({
credentials: {
email: {},
password: {}
},
authorize: async (credentials) => {
const validatedFields = SignInSchema.safeParse(credentials);
if (!validatedFields.success) {
return null;
}
const {email, password} = validatedFields.data;
const user = await prisma
.user
.findUnique({where: {
email
}})
if (!user || !user.password) {
throw new Error("no user found")
}
const passwordMatch = compareSync(password, user.password);
if (!passwordMatch)
return null;
return user;
}
})],
// callback
callbacks: {
authorized({auth, request: {
nextUrl
}}) {
const isLoggedIn = !!auth
?.user;
const ProtectedRoutes = ["/dashboard", "/"];
if (!isLoggedIn && ProtectedRoutes.includes(nextUrl.pathname)) {
return Response.redirect(new URL("/login", nextUrl))
}
if (isLoggedIn && nextUrl.pathname.startsWith("/login")) {
return Response.redirect(new URL("/dashboard", nextUrl))
}
return true;
},
jwt({token, user}) {
if (user)
token.role = user.role;
return token;
},
session({session, token}) {
session.user.id = token.sub;
session.user.role = token.role
return session;
}
}
})