-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
120 lines (114 loc) · 3.07 KB
/
auth.ts
File metadata and controls
120 lines (114 loc) · 3.07 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
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
import NextAuth, { CredentialsSignin } from 'next-auth';
import Google from 'next-auth/providers/google';
import GitHub from 'next-auth/providers/github';
import Credentials from 'next-auth/providers/credentials';
// import bcrypt from 'bcrypt';
import bcrypt from 'bcryptjs';
import { db } from '@/lib/db';
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
Google,
GitHub,
Credentials({
name: 'Credentials',
credentials: {
email: {
label: 'Email',
type: 'email',
placeholder: 'Enter your email',
},
password: {
label: 'Password',
type: 'password',
placeholder: 'Enter your password',
},
},
authorize: async (credentials) => {
const email = credentials.email as string | undefined;
const password = credentials.password as string | undefined;
console.log(email, password);
if (!email || !password) {
throw new CredentialsSignin(
'please provide all required credentials'
);
}
const user = await db.user.findUnique({
where: {
email,
},
});
if (!user) {
throw new CredentialsSignin('user not found');
}
const ismatch = await bcrypt.compare(password, user.password as string);
if (!ismatch) {
throw new CredentialsSignin('password not match');
}
console.log(user, 'user from credentials');
return {
id: user.id,
name: user.username,
email: user.email,
image: user.image,
};
},
}),
],
callbacks: {
async session({ session, token }) {
if (token?.sub && token?.email) {
session.user.id = token.sub;
session.user.email = token.email;
}
return session;
},
async jwt({ token, user }) {
if (user) {
token.sub = user.id;
token.email = user.email;
}
return token;
},
signIn: async ({ user, account }) => {
if (account?.provider === 'google') {
console.log(account, 'account');
console.log(user, 'user');
try {
const { email, image } = user;
// console.log(email, image);
const alreadyUser = await db.user.findUnique({
where: {
email: email || '',
},
});
if (alreadyUser) {
// console.log(alreadyUser, 'alreadyUser');
await db.user.update({
where: {
email: email || '',
},
data: {
image,
},
});
}
if (!alreadyUser) {
return false;
} else {
return true;
}
} catch (error) {
throw new Error('Failed to login');
}
}
if (account?.provider === 'credentials') {
return true;
}
return false;
},
},
pages: {
signIn: '/login',
},
secret: process.env.NEXT_PUBLIC_SECRET,
});