-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.ts
322 lines (292 loc) · 8.79 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
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import NextAuth from "next-auth";
import GitHub from "next-auth/providers/github";
import Google from "next-auth/providers/google";
import { DrizzleAdapter } from "@auth/drizzle-adapter";
import { db } from "./db";
import { type AdapterUser, Adapter } from "@auth/core/adapters";
import {
users,
accounts,
verificationTokens,
sessions,
SelectUser,
socials,
} from "@/db/schema";
import { eq, and } from "drizzle-orm";
import { revalidatePath, revalidateTag } from "next/cache";
import { setUsername } from "@/db/actions";
declare module "next-auth" {
interface Profile extends Partial<SelectUser> {}
interface User extends Partial<SelectUser> {}
}
function customAdapter(): Adapter {
const adapter = DrizzleAdapter(db);
// Overwrite createUser method on adapter
adapter.createUser = async (data): Promise<AdapterUser> => {
// TODO: create a non allowed usernames - ninja
// Google returns this format
// {
// id: 'redacted-redacted',
// name: 'Adrian Galilea Delgado',
// email: '[email protected]',
// image: 'https://lh3.googleusercontent.com/a/ACg8ocKYnnkCAxRw6qspAIG425xBn9AiGvXW_El-vSVDv15tAic=s96-c',
// emailVerified: null
// }
// Github returns
// gh_id gh_username gh_image
const { username, ...dataWithoutUsername } = data;
console.log(dataWithoutUsername);
const userCreated = await db
.insert(users)
.values({
...dataWithoutUsername,
id: crypto.randomUUID(),
})
.returning()
.then((res) => res[0] ?? null);
if (!userCreated) {
throw new Error("User Creation Failed");
}
// @ts-expect-error ts-migrate(2532) FIXME: Object is possibly 'undefined'.
if (dataWithoutUsername.gh_id) {
try {
await db.insert(socials).values({
id: crypto.randomUUID(),
user_id: userCreated.id,
platform: "github",
// @ts-expect-error ts-migrate(2532) FIXME: Object is possibly 'undefined'.
value: dataWithoutUsername.gh_username,
// @ts-expect-error ts-migrate(2532) FIXME: Object is possibly 'undefined'.
image: dataWithoutUsername.gh_image,
custom_data: {
// @ts-expect-error ts-migrate(2532) FIXME: Object is possibly 'undefined'.
platform_user_id: dataWithoutUsername.gh_id,
},
});
// create his email social
await db
.insert(socials)
.values({
id: crypto.randomUUID(),
user_id: userCreated.id,
platform: "email",
value: dataWithoutUsername.email,
})
.returning()
.then((res) => res[0] ?? null);
// we try to set his image
await db
.update(users)
// @ts-expect-error ts-migrate(2532) FIXME: Object is possibly 'undefined'.
.set({ image: dataWithoutUsername.gh_image })
.where(eq(users.id, userCreated.id));
// last we try to claim his username given his gh_username
// this may fail if username is not unique hence we do it last and isolated
await setUsername(userCreated, username!);
} catch (error) {
console.error("Error updating user:", error);
}
} else if (dataWithoutUsername.name) {
// we assume this is google
// we propose an username given it's email
const username = dataWithoutUsername.email.split("@")[0];
try {
await db
.insert(socials)
.values({
id: crypto.randomUUID(),
user_id: userCreated.id,
platform: "email",
value: dataWithoutUsername.email,
image: dataWithoutUsername.image,
custom_data: { platform_user_id: dataWithoutUsername.id },
})
.returning()
.then((res) => res[0] ?? null);
// set his image
await db
.update(users)
.set({ image: dataWithoutUsername.image })
.where(eq(users.id, userCreated.id));
// last we try to claim his username given his gh_username
// this may fail if username is not unique hence we do it last and isolated
await setUsername(userCreated, username!);
} catch (error) {
console.error("Error updating user:", error);
}
}
revalidatePath("/");
revalidateTag("users");
return userCreated;
};
adapter.linkAccount = async (rawAccount): Promise<any> => {
console.log(rawAccount);
const updatedAccount = await db
.insert(accounts)
.values(rawAccount)
.returning()
.get();
const account: any = {
...updatedAccount,
type: updatedAccount.type,
access_token: updatedAccount.access_token ?? undefined,
token_type: updatedAccount.token_type ?? undefined,
id_token: updatedAccount.id_token ?? undefined,
refresh_token: updatedAccount.refresh_token ?? undefined,
scope: updatedAccount.scope ?? undefined,
expires_at: updatedAccount.expires_at ?? undefined,
session_state: updatedAccount.session_state ?? undefined,
};
return account;
};
// the rest of the methods need to be copy-pasted, else the custom session data will not appear
adapter.getUser = async (data) => {
const result = await db
.select()
.from(users)
.where(eq(users.id, data))
.get();
return result ?? null;
};
adapter.getUserByEmail = async (data) => {
const result = await db
.select()
.from(users)
.where(eq(users.email, data))
.get();
return result ?? null;
};
adapter.createSession = (data) => {
return db.insert(sessions).values(data).returning().get();
};
adapter.getSessionAndUser = async (data) => {
const result = await db
.select({ session: sessions, user: users })
.from(sessions)
.where(eq(sessions.sessionToken, data))
.innerJoin(users, eq(users.id, sessions.userId))
.get();
return result ?? null;
};
adapter.updateUser = async (data) => {
console.log(data);
if (!data.id) {
throw new Error("No user id.");
}
const result = await db
.update(users)
.set(data)
.where(eq(users.id, data.id))
.returning()
.get();
return result ?? null;
};
adapter.updateSession = async (data) => {
const result = await db
.update(sessions)
.set(data)
.where(eq(sessions.sessionToken, data.sessionToken))
.returning()
.get();
return result ?? null;
};
adapter.getUserByAccount = async (account) => {
const results = await db
.select()
.from(accounts)
.leftJoin(users, eq(users.id, accounts.userId))
.where(
and(
eq(accounts.provider, account.provider),
eq(accounts.providerAccountId, account.providerAccountId),
),
)
.get();
if (!results) {
return null;
}
return Promise.resolve(results).then((results) => results.user);
};
adapter.deleteSession = async (sessionToken) => {
const result = await db
.delete(sessions)
.where(eq(sessions.sessionToken, sessionToken))
.returning()
.get();
return result ?? null;
};
adapter.createVerificationToken = async (token) => {
const result = await db
.insert(verificationTokens)
.values(token)
.returning()
.get();
return result ?? null;
};
adapter.useVerificationToken = async (token) => {
try {
const result = await db
.delete(verificationTokens)
.where(
and(
eq(verificationTokens.identifier, token.identifier),
eq(verificationTokens.token, token.token),
),
)
.returning()
.get();
return result ?? null;
} catch (err) {
throw new Error("No verification token found.");
}
};
adapter.deleteUser = async (id) => {
const result = await db
.delete(users)
.where(eq(users.id, id))
.returning()
.get();
return result ?? null;
};
adapter.unlinkAccount = async (account) => {
await db
.delete(accounts)
.where(
and(
eq(accounts.providerAccountId, account.providerAccountId),
eq(accounts.provider, account.provider),
),
)
.run();
};
return {
...adapter,
};
}
export const {
handlers: { GET, POST },
auth,
signIn,
signOut,
} = NextAuth({
basePath: "/auth",
adapter: customAdapter(),
providers: [
Google({
allowDangerousEmailAccountLinking: true,
}),
GitHub({
allowDangerousEmailAccountLinking: true,
profile(profile) {
return {
id: profile.id.toString(),
gh_id: profile.id.toString(),
name: profile.name ?? profile.login,
email: profile.email,
gh_image: profile.avatar_url,
gh_username: profile.login,
};
},
}),
],
});