-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
index.ts
448 lines (421 loc) · 12.1 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
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
/**
* <div style={{display: "flex", justifyContent: "space-between", alignItems: "center", padding: 16}}>
* <p style={{fontWeight: "normal"}}>Official <a href="https://pouchdb.com/api.html">PouchDB</a> adapter for Auth.js / NextAuth.js.</p>
* <a href="https://pouchdb.com">
* <img style={{display: "block"}} src="https://authjs.dev/img/adapters/pouchdb.svg" width="38" />
* </a>
* </div>
*
* ## Installation
*
* ```bash npm2yarn
* npm install pouchdb pouchdb-find @auth/pouchdb-adapter
* ```
*
* @module @auth/pouchdb-adapter
*/
import type {
Adapter,
AdapterAccount,
AdapterSession,
AdapterUser,
VerificationToken,
} from "@auth/core/adapters"
type PrefixConfig = Record<
"user" | "account" | "session" | "verificationToken",
string
>
type IndexConfig = Record<
| "userByEmail"
| "accountByProviderId"
| "sessionByToken"
| "verificationTokenByToken",
string
>
/**
* Configure the adapter
*/
export interface PouchDBAdapterOptions {
/**
* Your PouchDB instance, with the `pouchdb-find` plugin installed.
* @example
* ```javascript
* import PouchDB from "pouchdb"
*
* PouchDB
* .plugin(require("pouchdb-adapter-leveldb")) // Or any other adapter
* .plugin(require("pouchdb-find")) // Don't forget the `pouchdb-find` plugin
*
* const pouchdb = new PouchDB("auth_db", { adapter: "leveldb" })
*/
pouchdb: PouchDB.Database
/**
* Override the default prefix names.
*
* @default
* ```js
* {
* user: "USER",
* account: "ACCOUNT",
* session: "SESSION",
* verificationToken: "VERIFICATION-TOKEN"
* }
* ```
*/
prefixes?: PrefixConfig
/**
* Override the default index names.
*
* @default
* ```js
* {
* userByEmail: "nextAuthUserByEmail",
* accountByProviderId: "nextAuthAccountByProviderId",
* sessionByToken: "nextAuthSessionByToken",
* verificationTokenByToken: "nextAuthVerificationRequestByToken"
* }
* ```
*/
indexes?: IndexConfig
}
/**
* :::info
* Depending on your architecture you can use PouchDB's http adapter to reach any database compliant with the CouchDB protocol (CouchDB, Cloudant, ...) or use any other PouchDB compatible adapter (leveldb, in-memory, ...)
* :::
*
* ## Setup
*
* :::note
* Your PouchDB instance MUST provide the `pouchdb-find` plugin since it is used internally by the adapter to build and manage indexes
* :::
*
* Add this adapter to your `pages/api/auth/[...nextauth].js` next-auth configuration object:
*
* ```javascript title="pages/api/auth/[...nextauth].js"
* import NextAuth from "next-auth"
* import GoogleProvider from "next-auth/providers/google"
* import { PouchDBAdapter } from "@auth/pouchdb-adapter"
* import PouchDB from "pouchdb"
*
* // Setup your PouchDB instance and database
* PouchDB
* .plugin(require("pouchdb-adapter-leveldb")) // Or any other adapter
* .plugin(require("pouchdb-find")) // Don't forget the `pouchdb-find` plugin
*
* const pouchdb = new PouchDB("auth_db", { adapter: "leveldb" })
*
* // For more information on each option (and a full list of options) go to
* // https://authjs.dev/reference/configuration/auth-options
* export default NextAuth({
* // https://authjs.dev/reference/providers/
* providers: [
* GoogleProvider({
* clientId: process.env.GOOGLE_ID,
* clientSecret: process.env.GOOGLE_SECRET,
* }),
* ],
* adapter: PouchDBAdapter(pouchdb),
* // ...
* })
* ```
*
* ## Advanced usage
*
* ### Memory-First Caching Strategy
*
* If you need to boost your authentication layer performance, you may use PouchDB's powerful sync features and various adapters, to build a memory-first caching strategy.
*
* Use an in-memory PouchDB as your main authentication database, and synchronize it with any other persisted PouchDB. You may do a one way, one-off replication at startup from the persisted PouchDB into the in-memory PouchDB, then two-way, continuous sync.
*
* This will most likely not increase performance much in a serverless environment due to various reasons such as concurrency, function startup time increases, etc.
*
* For more details, please see https://pouchdb.com/api.html#sync
*
*/
export function PouchDBAdapter(options: PouchDBAdapterOptions): Adapter {
const { pouchdb } = options
const {
userByEmail = "nextAuthUserByEmail",
accountByProviderId = "nextAuthAccountByProviderId",
sessionByToken = "nextAuthSessionByToken",
verificationTokenByToken = "nextAuthVerificationRequestByToken",
} = options?.indexes ?? {}
const {
user: userPrefix = "USER",
account: accountPrefix = "ACCOUNT",
session: sessionPrefix = "SESSION",
verificationToken: verificationTokenPrefix = "VERIFICATION-TOKEN",
} = options?.prefixes ?? {}
return {
async createUser(user) {
const doc = { ...user, _id: [userPrefix, crypto.randomUUID()].join("_") }
await pouchdb.put(doc)
return { ...user, id: doc._id }
},
async getUser(id) {
try {
const res = await pouchdb.get<AdapterUser>(id)
return toAdapterUser(res)
} catch {
return null
}
},
async getUserByEmail(email) {
const res = await (
pouchdb as unknown as PouchDB.Database<AdapterUser>
).find({
use_index: userByEmail,
selector: { email: { $eq: email } },
limit: 1,
})
const userDoc = res.docs[0]
if (userDoc) {
return toAdapterUser(userDoc)
}
return null
},
async getUserByAccount({ provider, providerAccountId }) {
const res = await (
pouchdb as unknown as PouchDB.Database<AdapterAccount>
).find({
use_index: accountByProviderId,
selector: {
provider: { $eq: provider },
providerAccountId: { $eq: providerAccountId },
},
limit: 1,
})
const account = res.docs[0]
if (account) {
const user = await (
pouchdb as unknown as PouchDB.Database<AdapterUser>
).get(account.userId)
return toAdapterUser(user) ?? null
}
return null
},
async updateUser(user) {
const doc = await (
pouchdb as unknown as PouchDB.Database<AdapterUser>
).get(user.id!)
const newUser = {
...doc,
...user,
}
await pouchdb.put(newUser)
return toAdapterUser(newUser)
},
/** @todo Implement */
async deleteUser(id) {},
async linkAccount(account) {
const doc = {
...account,
_id: [accountPrefix, crypto.randomUUID()].join("_"),
}
await (pouchdb as unknown as PouchDB.Database<AdapterAccount>).put(doc)
return { ...account, id: doc._id }
},
async unlinkAccount({ provider, providerAccountId }) {
const _account = await (
pouchdb as unknown as PouchDB.Database<AdapterAccount>
).find({
use_index: accountByProviderId,
selector: {
provider: { $eq: provider },
providerAccountId: { $eq: providerAccountId },
},
limit: 1,
})
await pouchdb.put({
..._account.docs[0],
_deleted: true,
})
},
async createSession(data) {
const doc = {
_id: [sessionPrefix, crypto.randomUUID()].join("_"),
...data,
}
await (pouchdb as unknown as PouchDB.Database<AdapterSession>).put(doc)
return { ...data, id: doc._id }
},
async getSessionAndUser(sessionToken) {
const session = (
await (
pouchdb as unknown as PouchDB.Database<
AdapterSession & { user: AdapterUser }
>
).find({
use_index: sessionByToken,
selector: {
sessionToken: { $eq: sessionToken },
},
limit: 1,
})
).docs[0]
if (session) {
const user = await (
pouchdb as unknown as PouchDB.Database<AdapterUser>
).get(session.userId)
return {
session: toAdapterSession(session),
user: toAdapterUser(user),
}
}
return null
},
async updateSession(data) {
const res = await (
pouchdb as unknown as PouchDB.Database<AdapterSession>
).find({
use_index: sessionByToken,
selector: {
sessionToken: { $eq: data.sessionToken },
},
limit: 1,
})
const previousSessionDoc = res.docs[0]
if (previousSessionDoc) {
const currentSessionDoc = {
...previousSessionDoc,
...data,
}
await pouchdb.put(currentSessionDoc)
return toAdapterSession(currentSessionDoc)
}
return null
},
async deleteSession(sessionToken) {
const res = await (
pouchdb as unknown as PouchDB.Database<AdapterSession>
).find({
use_index: sessionByToken,
selector: {
sessionToken: { $eq: sessionToken },
},
limit: 1,
})
const sessionDoc = res.docs[0]
await pouchdb.put({
...sessionDoc,
_deleted: true,
})
},
async createVerificationToken(data) {
await (pouchdb as unknown as PouchDB.Database<VerificationToken>).put({
_id: [verificationTokenPrefix, crypto.randomUUID()].join("_"),
...data,
})
return data
},
async useVerificationToken({ identifier, token }) {
const res = await (
pouchdb as unknown as PouchDB.Database<VerificationToken>
).find({
use_index: verificationTokenByToken,
selector: {
identifier: { $eq: identifier },
token: { $eq: token },
},
limit: 1,
})
const verificationRequestDoc = res.docs[0]
if (verificationRequestDoc) {
await pouchdb.put({
...verificationRequestDoc,
_deleted: true,
})
return toVerificationToken(verificationRequestDoc)
}
return null
},
}
}
export async function createIndexes(
pouchdb: PouchDB.Database,
indexes?: IndexConfig
) {
const {
userByEmail = "nextAuthUserByEmail",
accountByProviderId = "nextAuthAccountByProviderId",
sessionByToken = "nextAuthSessionByToken",
verificationTokenByToken = "nextAuthVerificationRequestByToken",
} = indexes ?? {}
await Promise.allSettled([
await pouchdb.createIndex({
index: {
name: userByEmail,
ddoc: userByEmail,
fields: ["email"],
},
}),
await pouchdb.createIndex({
index: {
name: accountByProviderId,
ddoc: accountByProviderId,
fields: ["provider", "providerAccountId"],
},
}),
await pouchdb.createIndex({
index: {
name: sessionByToken,
ddoc: sessionByToken,
fields: ["sessionToken"],
},
}),
await pouchdb.createIndex({
index: {
name: verificationTokenByToken,
ddoc: verificationTokenByToken,
fields: ["identifier", "token"],
},
}),
])
}
/** @internal */
function toAdapter<T>(
dbObject: T & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta
) {
const {
_id,
_rev,
_conflicts,
_attachments,
_revisions,
_revs_info,
...rest
} = dbObject
return { ...rest }
}
/** @internal */
export function toAdapterUser(
user: AdapterUser & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta
) {
if (typeof user?.emailVerified === "string")
user.emailVerified = new Date(user.emailVerified)
return { ...toAdapter(user), id: user._id }
}
/** @internal */
export function toAdapterSession(
session: AdapterSession & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta
) {
if (typeof session?.expires === "string")
session.expires = new Date(session.expires)
return { ...toAdapter(session), id: session._id }
}
/** @internal */
export function toAdapterAccount(
account: AdapterAccount & PouchDB.Core.IdMeta & PouchDB.Core.GetMeta
) {
return { ...toAdapter(account), id: account._id }
}
/** @internal */
export function toVerificationToken(
verificationToken: VerificationToken &
PouchDB.Core.IdMeta &
PouchDB.Core.GetMeta
) {
if (typeof verificationToken?.expires === "string")
verificationToken.expires = new Date(verificationToken.expires)
return { ...toAdapter(verificationToken) }
}