-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathauth.ts
106 lines (99 loc) · 2.65 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
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
import NextAuth, {
AuthError,
CredentialsSignin,
NextAuthConfig,
} from "next-auth";
import Credentials from "next-auth/providers/credentials";
import connectDB from "./utils/db";
import Users from "./models/users";
import { compare } from "bcrypt";
import Google from "next-auth/providers/google";
class InvalidLoginError extends CredentialsSignin {
message = "Invalid Credentials";
code = "401";
}
const config: NextAuthConfig = {
providers: [
Google,
Credentials({
credentials: {
email: {
label: "email",
type: "text",
},
password: {
label: "password",
type: "password",
},
},
async authorize(credentials) {
await connectDB();
const email = credentials.email as string | undefined;
const password = credentials.password as string | undefined;
if (!email || !password) {
throw new InvalidLoginError();
}
const user = await Users.findOne({ email }).select("+password");
if (!user || !user.password) {
throw new InvalidLoginError();
}
const isPasswordCorrect = await compare(password, user.password);
if (!isPasswordCorrect) {
throw new InvalidLoginError();
}
return user;
},
}),
],
pages: {
signIn: "/login",
},
callbacks: {
signIn: async ({ user, account }) => {
if (account?.provider === "google") {
try {
const { email, name, image } = user;
await connectDB();
const userInfo = await Users.findOne({ email });
if (!userInfo) {
await Users.create({
name,
email,
image,
});
} else if (!userInfo.image) {
await Users.findOneAndUpdate({ email }, { $set: { image } });
}
return true;
} catch (error) {
throw new AuthError("An error occurred while creating your account.");
}
}
if (account?.provider === "credentials") return true;
return false;
},
session: async ({ session, token }) => {
if (token.sub) {
session.user.id = token.sub;
}
return session;
},
jwt: async ({ token }) => {
if (token.email) {
await connectDB();
const dbUser = (await Users.findOne(
{ email: token.email },
{ _id: 1 }
).lean()) as { _id: string } | null;
if (dbUser) {
token.sub = dbUser._id;
}
}
return token;
},
},
session: {
strategy: "jwt",
},
};
export const { handlers, signIn, signOut, auth } = NextAuth(config);