This repository has been archived by the owner on Jul 17, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathindex.ts
351 lines (330 loc) · 10.4 KB
/
index.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
import type * as Prisma from "@prisma/client"
import { createHash, randomBytes } from "crypto"
import type { Adapter } from "next-auth/adapters"
import {
CreateSessionError,
CreateUserError,
CreateVerificationRequestError,
DeleteSessionError,
DeleteUserError,
DeleteVerificationRequestError,
GetSessionError,
GetUserByEmailError,
GetUserByIdError,
GetUserByProviderAccountIdError,
GetVerificationRequestError,
LinkAccountError,
UnlinkAccountError,
UpdateSessionError,
UpdateUserError,
} from "next-auth/errors"
function verificationRequestToken({
token,
secret,
}: {
token: string
secret: string
}) {
// TODO: Use bcrypt or a more secure method
return createHash("sha256").update(`${token}${secret}`).digest("hex")
}
const PrismaAdapter: Adapter<
{ prisma: Prisma.PrismaClient },
unknown,
Prisma.User,
Prisma.User,
Prisma.Session
> = ({ prisma }) => {
return {
async getAdapter({ logger, session, ...appOptions }) {
function debug(debugCode: string, ...args: unknown[]) {
logger.debug(`PRISMA_${debugCode}`, ...args)
}
if (!session.maxAge) {
debug(
"GET_ADAPTER",
"Session expiry not configured (defaulting to 30 days)"
)
}
if (!session.updateAge) {
debug(
"GET_ADAPTER",
"Session update age not configured (defaulting to 1 day)"
)
}
const {
maxAge = 30 * 24 * 60 * 60, // 30 days
updateAge = 24 * 60 * 60, // 1 day
} = session
const sessionMaxAgeMs = maxAge * 1000
const sessionUpdateAgeMs = updateAge * 1000
return {
async createUser(profile) {
debug("CREATE_USER", profile)
try {
return await prisma.user.create({
data: {
name: profile.name,
email: profile.email,
image: profile.image,
emailVerified: profile.emailVerified?.toISOString() ?? null,
},
})
} catch (error) {
logger.error("CREATE_USER_ERROR", error)
throw new CreateUserError(error)
}
},
async getUser(id) {
debug("GET_USER_BY_ID", id)
try {
return await prisma.user.findUnique({
where: { id },
})
} catch (error) {
logger.error("GET_USER_BY_ID_ERROR", error)
throw new GetUserByIdError(error)
}
},
async getUserByEmail(email) {
debug("GET_USER_BY_EMAIL", email)
try {
if (!email) return null
return await prisma.user.findUnique({ where: { email } })
} catch (error) {
logger.error("GET_USER_BY_EMAIL_ERROR", error)
throw new GetUserByEmailError(error)
}
},
async getUserByProviderAccountId(providerId, providerAccountId) {
debug(
"GET_USER_BY_PROVIDER_ACCOUNT_ID",
providerId,
providerAccountId
)
try {
const account = await prisma.account.findUnique({
where: {
providerId_providerAccountId: { providerId, providerAccountId },
},
select: { user: true },
})
return account ? account.user : null
} catch (error) {
logger.error("GET_USER_BY_PROVIDER_ACCOUNT_ID_ERROR", error)
throw new GetUserByProviderAccountIdError(error)
}
},
async updateUser(user) {
debug("UPDATE_USER", user)
try {
return await prisma.user.update({
where: { id: user.id },
data: {
name: user.name,
email: user.email,
image: user.image,
emailVerified: user.emailVerified?.toISOString() ?? null,
},
})
} catch (error) {
logger.error("UPDATE_USER_ERROR", error)
throw new UpdateUserError(error)
}
},
async deleteUser(userId) {
debug("DELETE_USER", userId)
try {
await prisma.user.delete({
where: { id: userId },
})
return
} catch (error) {
logger.error("DELETE_USER_ERROR", error)
throw new DeleteUserError(error)
}
},
async linkAccount(
userId,
providerId,
providerType,
providerAccountId,
refreshToken,
accessToken,
accessTokenExpires
) {
debug(
"LINK_ACCOUNT",
userId,
providerId,
providerType,
providerAccountId,
refreshToken,
accessToken,
accessTokenExpires
)
try {
await prisma.account.create({
data: {
userId,
providerId,
providerType,
providerAccountId,
refreshToken,
accessToken,
accessTokenExpires:
accessTokenExpires != null
? new Date(accessTokenExpires)
: null,
},
})
} catch (error) {
logger.error("LINK_ACCOUNT_ERROR", error)
throw new LinkAccountError(error)
}
},
async unlinkAccount(userId, providerId, providerAccountId) {
debug("UNLINK_ACCOUNT", userId, providerId, providerAccountId)
try {
await prisma.account.delete({
where: {
providerId_providerAccountId: { providerId, providerAccountId },
},
})
} catch (error) {
logger.error("UNLINK_ACCOUNT_ERROR", error)
throw new UnlinkAccountError(error)
}
},
async createSession(user) {
debug("CREATE_SESSION", user)
try {
return await prisma.session.create({
data: {
userId: user.id,
expires: new Date(Date.now() + sessionMaxAgeMs),
sessionToken: randomBytes(32).toString("hex"),
accessToken: randomBytes(32).toString("hex"),
},
})
} catch (error) {
logger.error("CREATE_SESSION_ERROR", error)
throw new CreateSessionError(error)
}
},
async getSession(sessionToken) {
debug("GET_SESSION", sessionToken)
try {
const session = await prisma.session.findUnique({
where: { sessionToken },
})
if (session && session.expires < new Date()) {
await prisma.session.delete({ where: { sessionToken } })
return null
}
return session
} catch (error) {
logger.error("GET_SESSION_ERROR", error)
throw new GetSessionError(error)
}
},
async updateSession(session, force) {
debug("UPDATE_SESSION", session)
try {
if (
!force &&
Number(session.expires) - sessionMaxAgeMs + sessionUpdateAgeMs >
Date.now()
) {
return null
}
return await prisma.session.update({
where: { id: session.id },
data: {
expires: new Date(Date.now() + sessionMaxAgeMs),
},
})
} catch (error) {
logger.error("UPDATE_SESSION_ERROR", error)
throw new UpdateSessionError(error)
}
},
async deleteSession(sessionToken) {
debug("DELETE_SESSION", sessionToken)
try {
await prisma.session.delete({ where: { sessionToken } })
} catch (error) {
logger.error("DELETE_SESSION_ERROR", error)
throw new DeleteSessionError(error)
}
},
async createVerificationRequest(
identifier,
url,
token,
secret,
provider
) {
debug("CREATE_VERIFICATION_REQUEST", identifier)
try {
const hashedToken = verificationRequestToken({ token, secret })
await prisma.verificationRequest.create({
data: {
identifier,
token: hashedToken,
expires: new Date(Date.now() + provider.maxAge * 1000),
},
})
await provider.sendVerificationRequest({
identifier,
url,
token,
baseUrl: appOptions.baseUrl,
provider,
})
} catch (error) {
logger.error("CREATE_VERIFICATION_REQUEST_ERROR", error)
throw new CreateVerificationRequestError(error)
}
},
async getVerificationRequest(identifier, token, secret) {
debug("GET_VERIFICATION_REQUEST", identifier, token)
try {
const hashedToken = verificationRequestToken({ token, secret })
const verificationRequest = await prisma.verificationRequest.findUnique(
{
where: { identifier_token: { identifier, token: hashedToken } },
}
)
if (
verificationRequest &&
verificationRequest.expires < new Date()
) {
await prisma.verificationRequest.delete({
where: { identifier_token: { identifier, token: hashedToken } },
})
return null
}
return verificationRequest
} catch (error) {
logger.error("GET_VERIFICATION_REQUEST_ERROR", error)
throw new GetVerificationRequestError(error)
}
},
async deleteVerificationRequest(identifier, token, secret) {
debug("DELETE_VERIFICATION_REQUEST", identifier, token)
try {
const hashedToken = verificationRequestToken({ token, secret })
await prisma.verificationRequest.delete({
where: { identifier_token: { identifier, token: hashedToken } },
})
} catch (error) {
logger.error("DELETE_VERIFICATION_REQUEST_ERROR", error)
throw new DeleteVerificationRequestError(error)
}
},
}
},
}
}
export default PrismaAdapter