-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathauth.config.ts
More file actions
108 lines (95 loc) · 2.82 KB
/
auth.config.ts
File metadata and controls
108 lines (95 loc) · 2.82 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
import Credentials from "next-auth/providers/credentials";
import { signInSchema } from "./lib/zod";
import prisma from "./lib/prisma";
import bcryptjs from "bcryptjs";
import { NextAuthConfig } from "next-auth";
const authRoutes = ["/auth/signin", "/auth/signup"];
const adminRoutes = ["/admin"];
export default {
providers: [
Credentials({
credentials: {
email: { label: "Email", type: "email", placeholder: "Email" },
password: {
label: "Password",
type: "password",
placeholder: "Password",
},
},
async authorize(credentials) {
let user = null;
// validate credentials
const parsedCredentials = signInSchema.safeParse(credentials);
if (!parsedCredentials.success) {
console.error("Invalid credentials:", parsedCredentials.error.errors);
return null;
}
// get user
user = await prisma.user.findUnique({
where: {
email: credentials.email as string,
},
});
if (!user) {
console.log("Invalid credentials");
return null;
}
if (!user.password) {
console.log(
"User has no password. They probably signed up with an oauth provider.",
);
return null;
}
const isPasswordValid = await bcryptjs.compare(
credentials.password as string,
user.password,
);
if (!isPasswordValid) {
console.log("Invalid password");
return null;
}
const { password, ...userWithoutPassword } = user;
return userWithoutPassword;
},
}),
],
callbacks: {
authorized({ request: { nextUrl }, auth }) {
const isLoggedIn = !!auth?.user;
const role = auth?.user?.role;
const { pathname } = nextUrl;
const isAuthRoute = authRoutes.some((route) =>
pathname.startsWith(route),
);
const isAdminRoute = adminRoutes.some((route) =>
pathname.startsWith(route),
);
if (isLoggedIn) {
if (isAuthRoute) return Response.redirect(new URL("/", nextUrl));
if (isAdminRoute && role !== "admin")
return Response.redirect(new URL("/", nextUrl));
}
// here the user is not logged in
if (isAuthRoute) return true;
return isLoggedIn;
},
jwt({ token, user, trigger, session }) {
if (user) {
token.id = user.id as string;
token.role = user.role as string;
}
if (trigger === "update" && session) {
token = { ...token, ...session };
}
return token;
},
session({ session, token }) {
session.user.id = token.id;
session.user.role = token.role;
return session;
},
},
pages: {
signIn: "/auth/signin",
},
} satisfies NextAuthConfig;