forked from nextauthjs/adapters
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic-tests.ts
383 lines (339 loc) · 11.7 KB
/
basic-tests.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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import { Adapter, AdapterInstance } from "next-auth/adapters"
import { AppOptions } from "next-auth/internals"
import Providers, { EmailConfig } from "next-auth/providers"
import { createHash, randomBytes } from "crypto"
/**
* A wrapper to run the most basic tests.
* Run this at the top of your test file.
* You can add additional tests below, if you wish.
*/
export function runBasicTests(options: {
adapter: ReturnType<Adapter>
/** Utility functions to talk directly with the db */
db: {
/** Optional, after all tests have been run, this will make sure the database is disconnected */
disconnect?: () => any
/** Optional, establishes a db connection before all tests, if your db doesn't do this manually */
connect?: () => any
/** A simple query function that returns a session directly from the db. */
session: (token: string) => any
/**
* Forcefully sets the expiry date to a value
* in the past on the given session. This helps to
* test if an invalidated session is properly cleaned up.
*/
expireSession: (sessionToken: string, expires: Date) => any
/** A simple query function that returns a user directly from the db. */
user: (id: string) => any
/** A simple query function that returns an account directly from the db. */
account: (providerId: string, providerAccountId: string) => any
/**
* A simple query function that returns an verification token directly from the db,
* based on the user identifier and the verification token (hashed).
*/
verificationRequest: (identifier: string, hashedToken: string) => any
}
/** Optionally overrides the default mock data values */
mock?: {
/** The options that `getAdapter()` receives from `next-auth` */
appOptions?: AppOptions
/** The user object passed to the adapter from `next-auth` */
user?: any
/** The params */
verificationParams?: string[]
}
}) {
// Mock data
const appOptions: AppOptions = {
action: "signin",
basePath: "",
baseUrl: "http://example.com",
callbacks: {},
cookies: {},
debug: false,
events: {},
jwt: {},
theme: "auto",
logger: {
debug: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
} as const,
pages: {},
providers: [],
secret: "VERY SECRET",
session: {
jwt: false,
maxAge: 60 * 60 * 24 * 30,
updateAge: 60 * 60 * 24,
},
adapter: null as unknown as ReturnType<Adapter>, // TODO: Make it optional on AppOptions
...options.mock?.appOptions,
}
const defaultUser = {
email: "fill@murray.com",
image: "https://www.fillmurray.com/460/300",
name: "Fill Murray",
...options.mock?.user,
}
// Init
let adapter: AdapterInstance<any, any, any>
beforeAll(async () => {
await options.db.connect?.()
adapter = await options.adapter.getAdapter(appOptions)
})
afterAll(async () => {
await options.db.disconnect?.()
})
// Tests
describe("Meta", () => {
test("Has displayName for debug purposes", async () => {
expect(adapter.displayName).not.toBe(undefined)
})
})
describe("User", () => {
let user: any
test("createUser", async () => {
user = await adapter.createUser(defaultUser)
expect(user).toEqual(expect.objectContaining(defaultUser))
})
test("getUser", async () => {
const userById = await adapter.getUser(user.id)
expect(userById).toMatchObject(user)
})
test("getUserByEmail", async () => {
expect(await adapter.getUserByEmail(null)).toBeNull()
const userByEmail = await adapter.getUserByEmail(user.email)
expect(userByEmail).toMatchObject(user)
})
test("updatedUser", async () => {
user.email = "jane@example.com"
const updatedUser = await adapter.updateUser(user)
expect(updatedUser.email).toBe(user.email)
})
// (Currently unimplemented in core, so we don't require it yet)
test.skip("deleteUser", async () => {
if (adapter.deleteUser) {
await adapter.deleteUser(user.id)
const expectedUser = await options.db.user(user.id)
expect(expectedUser).toBeNull()
}
})
})
describe("Session", () => {
const now = Date.now()
let user: any
beforeAll(async () => {
user = await adapter.createUser(defaultUser)
})
test("createSession", async () => {
const session = await adapter.createSession(user)
expect(session.accessToken).toHaveLength(64)
expect(session.sessionToken).toHaveLength(64)
expect(session.userId).toBe(user.id)
expect(session.expires.valueOf()).toBeGreaterThanOrEqual(
now + appOptions.session.maxAge
)
})
test("getSession", async () => {
const session = await adapter.createSession(user)
const sessionByToken = await adapter.getSession(session.sessionToken)
expect(sessionByToken).toMatchObject(session)
// Invalidate expired session
await options.db.expireSession(session.sessionToken, new Date(1970, 1, 1))
// Expired session should return null
expect(await adapter.getSession(session.sessionToken)).toBeNull()
// Expired session should be removed from the database
expect(await options.db.session(session.sessionToken)).toBeNull()
})
test("updateSession", async () => {
const session = await adapter.createSession(user)
// Don't update session if not forced
expect(await adapter.updateSession(session)).toBeNull()
expect(await adapter.updateSession(session, false)).toBeNull()
// Update session if forced
const updated = await adapter.updateSession(session, true)
expect(updated.accessToken).toBe(session.accessToken)
expect(updated.sessionToken).toBe(session.sessionToken)
expect(updated.userId).toBe(session.userId)
// TODO: expect(updated.expires.valueOf()).toBe(????)
// Update session if expired
const expired = await adapter.updateSession(session, true)
expect(expired.accessToken).toBe(session.accessToken)
expect(expired.sessionToken).toBe(session.sessionToken)
expect(expired.userId).toBe(session.userId)
// TODO: expect(expired.expires.valueOf()).toBe(????)
})
test("deleteSession", async () => {
const session = await adapter.createSession(user)
await adapter.deleteSession(session.sessionToken)
expect(await options.db.session(session.sessionToken)).toBeNull()
})
})
describe("Account", () => {
let user: any
beforeAll(async () => {
user = await adapter.createUser({
...defaultUser,
email: "account@test.com",
})
})
test("linkAccount (OAuth provider)", async () => {
// Basic OAuth provider config
const provider = Providers.Auth0({})
// Roughly what is returned from a succesful OAuth login flow
const providerProfile = {
id: randomBytes(32).toString("hex"),
refreshToken: randomBytes(32).toString("hex"),
accessToken: randomBytes(32).toString("hex"),
accessTokenExpires: null,
}
const account = {
userId: user.id,
providerId: provider.id,
providerType: provider.type,
providerAccountId: providerProfile.id,
refreshToken: providerProfile.refreshToken,
accessToken: providerProfile.accessToken,
accessTokenExpires: providerProfile.accessTokenExpires,
}
// @ts-expect-error
await adapter.linkAccount(...Object.values(account))
const dbAccount = await options.db.account(
provider.id,
providerProfile.id
)
expect(dbAccount).toEqual(expect.objectContaining(account))
})
test("getUserByProviderAccountId", async () => {
// Basic OAuth provider config
const provider = Providers.GitHub({})
// Roughly what is returned from a succesful OAuth login flow
const providerProfile = {
id: randomBytes(32).toString("hex"),
refreshToken: randomBytes(32).toString("hex"),
accessToken: randomBytes(32).toString("hex"),
accessTokenExpires: null,
}
const account = {
userId: user.id,
providerId: provider.id,
providerType: provider.type,
providerAccountId: providerProfile.id,
refreshToken: providerProfile.refreshToken,
accessToken: providerProfile.accessToken,
accessTokenExpires: providerProfile.accessTokenExpires,
}
// @ts-expect-error
await adapter.linkAccount(...Object.values(account))
const adapterUser = await adapter.getUserByProviderAccountId(
provider.id,
providerProfile.id
)
const dbUser = await options.db.user(user.id)
expect(dbUser).toEqual(expect.objectContaining(adapterUser))
})
// (Currently unimplemented in core, so we don't require it yet)
test.skip("unlinkAccount", async () => {
await adapter.unlinkAccount?.("", "", "")
})
})
describe("Verification Request", () => {
const email = "jane@example.com"
const url = appOptions.baseUrl
const token = "000000000000"
const hashToken = (token: string) =>
createHash("sha256").update(`${token}${appOptions.secret}`).digest("hex")
// @ts-expect-error
const provider: EmailConfig & {
maxAge: number
from: string
} = Providers.Email({
sendVerificationRequest: jest.fn(),
server: "",
maxAge: 60,
from: "noreply@example.com",
})
test("createVerificationRequest", async () => {
if (!adapter.createVerificationRequest) {
return console.warn("This adapter does not support Email providers")
}
await adapter.createVerificationRequest(
email,
appOptions.baseUrl,
token,
appOptions.secret,
provider
)
expect(provider.sendVerificationRequest).toBeCalledTimes(1)
expect(provider.sendVerificationRequest).toBeCalledWith({
baseUrl: appOptions.baseUrl,
identifier: email,
provider,
token,
url,
})
const dbVerificationRequest = await options.db.verificationRequest(
email,
hashToken(token)
)
expect(dbVerificationRequest.identifier).toBe(email)
expect(dbVerificationRequest.expires.valueOf()).toBeLessThanOrEqual(
Date.now() + provider.maxAge * 1000
)
expect(dbVerificationRequest.token).toBe(hashToken(token))
})
test("getVerificationRequest", async () => {
if (!adapter.getVerificationRequest) {
return console.warn("This adapter does not support Email providers")
}
expect(
await adapter.getVerificationRequest(
email,
token,
appOptions.secret,
provider
)
).toEqual(
expect.objectContaining({
identifier: email,
expires: expect.any(Date),
token: hashToken(token),
})
)
// TODO: getVerificationRequest should delete the token from the database immediatelly
// expect(
// await options.db.verificationRequest(email, hashToken(token))
// ).toBeNull()
})
test("deleteVerificationRequest", async () => {
// TODO: Deprecate in favour of getVerificationRequest doing this.
if (
!adapter.deleteVerificationRequest ||
!adapter.createVerificationRequest
) {
return console.warn("This adapter does not support Email providers")
}
const token = "1111111111111111"
await adapter.createVerificationRequest(
email,
appOptions.baseUrl,
token,
appOptions.secret,
provider
)
await adapter.deleteVerificationRequest(
email,
token,
appOptions.secret,
provider
)
expect(
await options.db.verificationRequest(email, hashToken(token))
).toBeNull()
})
})
return {
appOptions,
}
}