-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
86 lines (84 loc) · 2.29 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
import NextAuth, { Account, User } from 'next-auth';
import authConfig from './auth.config';
import { db } from './db';
export const {
handlers: { GET, POST },
auth,
signIn,
signOut,
} = NextAuth({
...authConfig,
callbacks: {
async signIn({ user, account }: { user: any; account: Account | null }) {
if (account?.provider === 'google') {
try {
const { name, email, image } = await user;
const userExists = await db.user.findUnique({
where: { email },
select: {
id: true,
},
});
if (!userExists) {
const res = await fetch(
`${process.env.NEXT_PUBLIC_APP_DOMAIN}/api/user`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name,
email,
image,
username: name.split(' ').join('').toLowerCase(),
}),
}
);
if (!res.ok) {
throw new Error('Failed to create user');
}
}
console.log('userExists', userExists);
return true;
} catch (err) {
console.error(err);
return false;
}
}
if (account?.provider === 'github') {
try {
console.log('user from github', user);
const { name, email, image } = await user;
const userExists = await db.user.findUnique({
where: { email },
});
if (!userExists) {
const res = await fetch(
`${process.env.NEXT_PUBLIC_APP_DOMAIN}/api/user`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name,
email,
image,
}),
}
);
if (!res.ok) {
throw new Error('Failed to create user');
}
}
return true;
} catch (err) {
console.error(err);
return false;
}
}
return user;
},
},
});