-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathauth.ts
More file actions
170 lines (156 loc) · 4.99 KB
/
auth.ts
File metadata and controls
170 lines (156 loc) · 4.99 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { prisma } from '@/lib/db';
import bcrypt from 'bcryptjs';
import Google from 'next-auth/providers/google';
import Github from 'next-auth/providers/github';
export const handler = NextAuth({
providers: [
CredentialsProvider({
name: 'Credentials',
credentials: {
email: { label: 'Email', type: 'email' },
name: { label: 'Name', type: 'text' },
password: { label: 'Password', type: 'password' },
action: { label: 'Action', type: 'text' },
},
async authorize(
credentials: Record<'email' | 'password' | 'name' | 'action', string> | undefined,
) {
if (!credentials?.email || !credentials?.password) {
throw new Error('Missing fields');
}
if (credentials.action === 'signup') {
const existingUser = await prisma.user.findUnique({
where: { email: credentials.email },
});
if (existingUser) {
throw new Error('Email already exists');
}
const hashedPassword = await bcrypt.hash(credentials.password, 10);
const user = await prisma.user.create({
data: {
email: credentials.email,
name: credentials.name || '',
password: hashedPassword,
},
});
return {
id: user.id.toString(),
email: user.email,
name: user.name,
};
}
const user = await prisma.user.findUnique({
where: { email: credentials.email },
});
if (!user || !user.password) {
throw new Error('No user found');
}
const isPasswordValid = await bcrypt.compare(credentials.password, user.password);
if (!isPasswordValid) {
throw new Error('Invalid password');
}
return {
id: user.id.toString(),
email: user.email,
name: user.name,
};
},
}),
Google({
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
}),
Github({
clientId: process.env.GITHUB_CLIENT_ID as string,
clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
}),
],
callbacks: {
async signIn({ user, account }) {
if (account?.provider === 'google' || account?.provider === 'github') {
try {
const existingUser = await prisma.user.findUnique({
where: { email: user.email! },
include: {
accounts: true,
},
});
if (!existingUser) {
// Create new user and account
await prisma.user.create({
data: {
email: user.email!,
name: user.name || '',
accounts: {
create: {
type: account.type,
provider: account.provider,
providerAccountId: account.providerAccountId,
access_token: account.access_token,
expires_at: account.expires_at,
token_type: account.token_type,
scope: account.scope,
id_token: account.id_token,
},
},
},
});
} else {
// If user exists but doesn't have this OAuth account
const existingAccount = existingUser.accounts.find(
(acc: any) => acc.provider === account.provider,
);
if (!existingAccount) {
await prisma.account.create({
data: {
userId: existingUser.id,
type: account.type,
provider: account.provider,
providerAccountId: account.providerAccountId,
access_token: account.access_token,
expires_at: account.expires_at,
token_type: account.token_type,
scope: account.scope,
id_token: account.id_token,
},
});
}
}
} catch (error) {
console.error('Error in signIn callback:', error);
return false;
}
}
return true;
},
async jwt({ token, user, account }) {
if (user) {
// Find the user in database to get the correct ID
const dbUser = await prisma.user.findUnique({
where: { email: user.email! },
});
if (dbUser) {
token.id = dbUser.id;
token.email = dbUser.email;
}
}
return token;
},
async session({ session, token }) {
if (session.user) {
// Make sure to use the correct ID from the token
session.user.id = token.id as number;
}
return session;
},
},
pages: {
signIn: '/auth/signin',
error: '/auth/error',
},
session: {
strategy: 'jwt',
},
});