-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauth.ts
58 lines (52 loc) · 1.55 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
import CredentialsProvider from "next-auth/providers/credentials";
import { type NextAuthOptions } from "next-auth";
import prisma from "@/lib/prisma";
import bcrypt from "bcryptjs";
export const authOptions = {
providers: [
CredentialsProvider({
name: "credentials",
credentials: {
email: { label: "Email", type: "email" },
name: { label: "Name", type: "name" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) {
throw new Error("Invalid credentials");
}
const user = await prisma.user.findUnique({
where: { email: credentials.email },
});
if (!user) {
return await prisma.user.create({
data: {
name: credentials.name ?? credentials.email,
email: credentials.email,
password: await bcrypt.hash(credentials.password, 10),
},
});
}
const isCorrectPassword = await bcrypt.compare(
credentials.password,
user.password
);
if (!isCorrectPassword) {
throw new Error("Invalid credentials");
}
return user;
},
}),
],
pages: {
signIn: "/login",
},
callbacks: {
async jwt({ token, user }) {
return { ...token, id: token.id ?? user?.id };
},
async session({ session, token }) {
return { ...session, user: { ...session.user, id: token.id } };
},
},
} satisfies NextAuthOptions;