-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
122 lines (99 loc) · 2.9 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import NextAuth, { CredentialsSignin } from "next-auth";
import Credentials from "next-auth/providers/credentials";
import Github from "next-auth/providers/github";
import Google from "next-auth/providers/google";
import connectDB from "./lib/db";
import { User } from "./models/User";
import {compare} from "bcryptjs"
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
Github({
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
}),
Google({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
authorization:{
params:{
prompt:"consent",
access_type:"offline",
response_type:"code",
}
}
}),
Credentials({
name: "Credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
authorize: async (credentials) => {
const email = credentials.email as string | undefined;
const password = credentials.password as string | undefined;
if (!email || !password) {
throw new CredentialsSignin("Please provide both email & password");
}
await connectDB();
const user = await User.findOne({ email }).select("+password +role");
if (!user) {
throw new Error("Invalid email or password");
}
if (!user.password) {
throw new Error("Invalid email or password");
}
const isMatched = await compare(password, user.password);
if (!isMatched) {
throw new Error("Password did not matched");
}
const userData = {
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
role: user.role,
id: user._id,
};
return userData;
},
}),
],
pages: {
signIn: "/login",
},
callbacks: {
async session({ session, token }) {
if (token?.sub && token?.role) {
session.user.id = token.sub;
session.user.role = token.role;
}
return session;
},
async jwt({ token, user }) {
if (user) {
token.role = user.role;
}
return token;
},
signIn: async ({ user, account }) => {
if (account?.provider === "google") {
try {
const { email, name, image, id } = user;
await connectDB();
const alreadyUser = await User.findOne({ email });
if (!alreadyUser) {
await User.create({ email, name, image, authProviderId: id });
} else {
return true;
}
} catch (error) {
throw new Error("Error while creating user");
}
}
if (account?.provider === "credentials") {
return true;
} else {
return false;
}
},
},
});