forked from bluuweb/example-next-auth-v5
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.config.ts
More file actions
80 lines (66 loc) · 2.24 KB
/
auth.config.ts
File metadata and controls
80 lines (66 loc) · 2.24 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
import { db } from "@/lib/db";
import { loginSchema } from "@/lib/zod";
import bcrypt from "bcryptjs";
import { nanoid } from "nanoid";
import type { NextAuthConfig } from "next-auth";
import Credentials from "next-auth/providers/credentials";
import { sendEmailVerification } from "./lib/mail";
import GitHub from "next-auth/providers/github";
import Google from "next-auth/providers/google";
// Notice this is only an object, not a full Auth.js instance
export default {
providers: [
Google,
GitHub,
Credentials({
authorize: async (credentials) => {
const { data, success } = loginSchema.safeParse(credentials);
if (!success) {
throw new Error("Invalid credentials");
}
// verificar si existe el usuario en la base de datos
const user = await db.user.findUnique({
where: {
email: data.email,
},
});
if (!user || !user.password) {
throw new Error("No user found");
}
// verificar si la contraseña es correcta
const isValid = await bcrypt.compare(data.password, user.password);
if (!isValid) {
throw new Error("Incorrect password");
}
// verificación de email
if (!user.emailVerified) {
const verifyTokenExits = await db.verificationToken.findFirst({
where: {
identifier: user.email,
},
});
// si existe un token, lo eliminamos
if (verifyTokenExits?.identifier) {
await db.verificationToken.delete({
where: {
identifier: user.email,
},
});
}
const token = nanoid();
await db.verificationToken.create({
data: {
identifier: user.email,
token,
expires: new Date(Date.now() + 1000 * 60 * 60 * 24),
},
});
// enviar email de verificación
await sendEmailVerification(user.email, token);
throw new Error("Please check Email send verification");
}
return user;
},
}),
],
} satisfies NextAuthConfig;