-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
79 lines (68 loc) · 1.97 KB
/
auth.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
72
73
74
75
76
77
78
79
import NextAuth from "next-auth";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "@/../lib/prisma";
import Credentials from "next-auth/providers/credentials";
import { LoginSchema } from "@/../lib/zod";
import { compareSync } from "bcrypt-ts";
import Google from "next-auth/providers/google";
import GitHub from "next-auth/providers/github";
export const { handlers, signIn, signOut, auth } = NextAuth({
adapter: PrismaAdapter(prisma),
session: {
strategy: "jwt",
},
pages: {
signIn: "/login",
},
providers: [
Google,
GitHub,
Credentials({
credentials: {
email: {},
password: {},
},
authorize: async (credentials) => {
const validateFields = LoginSchema.safeParse(credentials);
if (!validateFields.success) {
return null;
}
const { email, password } = validateFields.data;
const user = await prisma.user.findUnique({
where: {
email,
},
});
if (!user || !user.password) {
throw new Error("Invalid credentials");
}
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", "/user", "/product"];
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;
}
},
});