-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
72 lines (68 loc) · 1.81 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
import NextAuth from "next-auth";
import Github from "next-auth/providers/github";
import { PrismaAdapter } from "@auth/prisma-adapter";
import Credentials from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
import { db } from "./db";
import { saltAndHashPassword } from "@/utils/helper";
interface AuthUser {
email: string | null;
hashedPassword: string | null;
}
export const {
handlers: { GET, POST },
signIn,
signOut,
auth,
} = NextAuth({
adapter: PrismaAdapter(db),
session: { strategy: "jwt" },
providers: [
Github({
clientId: process.env.AUTH_GITHUB_ID,
clientSecret: process.env.AUTH_GITHUB_SECRET,
}),
Credentials({
name: "Credentials",
credentials: {
email: {
label: "Email",
type: "email",
placeholder: "[email protected]",
},
password: { label: "Password", type: "password" },
},
authorize: async (credentials) => {
if (!credentials?.email || !credentials.password) {
return null;
}
const email = credentials.email as string;
const hash = saltAndHashPassword(credentials.password as string);
let user = (await db.user.findUnique({
where: { email },
select: {
email: true,
hashedPassword: true,
},
})) as AuthUser | null;
if (!user) {
user = await db.user.create({
data: {
email,
hashedPassword: hash,
},
});
} else {
const isMatch = bcrypt.compareSync(
credentials.password as string,
user.hashedPassword!,
);
if (!isMatch) {
throw new Error("Incorrect password.");
}
}
return user;
},
}),
],
});