@auth/edgedb-adapter 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,615 @@
1
+ /**
2
+ * <div style={{display: "flex", justifyContent: "space-between", alignItems: "center", padding: 16}}>
3
+ * <p style={{fontWeight: "normal"}}>Official <a href="https://www.edgedb.com/">Edge DB</a> adapter for Auth.js / NextAuth.js.</p>
4
+ * <a href="https://www.edgedb.com/">
5
+ * <img style={{display: "block"}} src="/img/adapters/edgedb.svg" width="38" />
6
+ * </a>
7
+ * </div>
8
+ *
9
+ * ## Installation
10
+ *
11
+ * ```bash npm2yarn2pnpm
12
+ * npm install edgedb @auth/edgedb-adapter
13
+ * npm install @edgedb/generate --save-dev
14
+ * ```
15
+ *
16
+ * @module @auth/edgedb-adapter
17
+ */
18
+
19
+ import type {
20
+ Adapter,
21
+ AdapterSession,
22
+ AdapterUser,
23
+ VerificationToken,
24
+ } from "@auth/core/adapters"
25
+ import type { Client } from "edgedb"
26
+
27
+ /**
28
+ *
29
+ * To use this Adapter, you need to install `edgedb`, `@edgedb/generate`, and the separate `@auth/edgedb-adapter` package:
30
+ *
31
+ * ```bash npm2yarn2pnpm
32
+ * npm install edgedb @auth/edgedb-adapter
33
+ * npm install @edgedb/generate --save-dev
34
+ * ```
35
+ *
36
+ * ## Installation
37
+ *
38
+ * First, ensure you have the EdgeDB CLI installed.
39
+ *
40
+ * Follow the instructions below, or read the [EdgeDB quickstart](https://www.edgedb.com/docs/intro/quickstart) to install the EdgeDB CLI and initialize a project
41
+ *
42
+ * ### Linux or macOS
43
+ * ```bash
44
+ * curl --proto '=https' --tlsv1.2 -sSf https://sh.edgedb.com | sh
45
+ * ```
46
+ *
47
+ * ### Windows
48
+ * ```powershell
49
+ * iwr https://ps1.edgedb.com -useb | iex
50
+ * ```
51
+ *
52
+ * Check that the CLI is available with the `edgedb --version` command. If you get a `Command not found` error, you may need to open a new terminal window before the `edgedb` command is available.
53
+ *
54
+ * Once the CLI is installed, initialize a project from the application’s root directory. You’ll be presented with a series of prompts.
55
+ *
56
+ * ```bash
57
+ * edgedb project init
58
+ * ```
59
+ *
60
+ * This process will spin up an EdgeDB instance and [“link”](https://www.edgedb.com/docs/cli/edgedb_instance/edgedb_instance_link#edgedb-instance-link) it with your current directory. As long as you’re inside that directory, CLI commands and client libraries will be able to connect to the linked instance automatically, without additional configuration.
61
+ *
62
+ * ## Setup
63
+ *
64
+ * ### NextAuth.js configuration
65
+ *
66
+ * Configure your NextAuth.js to use the EdgeDB Adapter:
67
+ *
68
+ * ```javascript title="pages/api/auth/[...nextauth].js"
69
+ * import NextAuth from "next-auth"
70
+ * import GoogleProvider from "next-auth/providers/google"
71
+ * import { EdgeDBAdapter } from "@auth/edgedb-adapter"
72
+ * import { createClient } from "edgedb"
73
+ *
74
+ * const client = createClient()
75
+ *
76
+ * export default NextAuth({
77
+ * adapter: EdgeDBAdapter(client),
78
+ * providers: [
79
+ * GoogleProvider({
80
+ * clientId: process.env.GOOGLE_CLIENT_ID,
81
+ * clientSecret: process.env.GOOGLE_CLIENT_SECRET,
82
+ * }),
83
+ * ],
84
+ * })
85
+ * ```
86
+ *
87
+ * ### Create the EdgeDB schema
88
+ *
89
+ * Replace the contents of the auto-generated file in `dbschema/default.esdl` with the following:
90
+ *
91
+ * > This schema is adapted for use in EdgeDB and based upon our main [schema](/adapters/models)
92
+ *
93
+ * ```json title="default.esdl"
94
+ * module default {
95
+ * type User {
96
+ * property name -> str;
97
+ * required property email -> str {
98
+ * constraint exclusive;
99
+ * }
100
+ * property emailVerified -> datetime;
101
+ * property image -> str;
102
+ * multi link accounts := .<user[is Account];
103
+ * multi link sessions := .<user[is Session];
104
+ * property createdAt -> datetime {
105
+ * default := datetime_current();
106
+ * };
107
+ * }
108
+ *
109
+ * type Account {
110
+ * required property userId := .user.id;
111
+ * required property type -> str;
112
+ * required property provider -> str;
113
+ * required property providerAccountId -> str {
114
+ * constraint exclusive;
115
+ * };
116
+ * property refresh_token -> str;
117
+ * property access_token -> str;
118
+ * property expires_at -> int64;
119
+ * property token_type -> str;
120
+ * property scope -> str;
121
+ * property id_token -> str;
122
+ * property session_state -> str;
123
+ * required link user -> User {
124
+ * on target delete delete source;
125
+ * };
126
+ * property createdAt -> datetime {
127
+ * default := datetime_current();
128
+ * };
129
+ *
130
+ * constraint exclusive on ((.provider, .providerAccountId))
131
+ * }
132
+ *
133
+ * type Session {
134
+ * required property sessionToken -> str {
135
+ * constraint exclusive;
136
+ * }
137
+ * required property userId := .user.id;
138
+ * required property expires -> datetime;
139
+ * required link user -> User {
140
+ * on target delete delete source;
141
+ * };
142
+ * property createdAt -> datetime {
143
+ * default := datetime_current();
144
+ * };
145
+ * }
146
+ *
147
+ * type VerificationToken {
148
+ * required property identifier -> str;
149
+ * required property token -> str {
150
+ * constraint exclusive;
151
+ * }
152
+ * required property expires -> datetime;
153
+ * property createdAt -> datetime {
154
+ * default := datetime_current();
155
+ * };
156
+ *
157
+ * constraint exclusive on ((.identifier, .token))
158
+ * }
159
+ * }
160
+ *
161
+ * # Disable the application of access policies within access policies
162
+ * # themselves. This behavior will become the default in EdgeDB 3.0.
163
+ * # See: https://www.edgedb.com/docs/reference/ddl/access_policies#nonrecursive
164
+ * using future nonrecursive_access_policies;
165
+ * ```
166
+ *
167
+ * ### Migrate the database schema
168
+ *
169
+ * Create a migration
170
+ *
171
+ * ```
172
+ * edgedb migration create
173
+ * ```
174
+ *
175
+ * Apply the migration
176
+ *
177
+ * ```
178
+ * edgedb migrate
179
+ * ```
180
+ *
181
+ * To learn more about [EdgeDB migrations](https://www.edgedb.com/docs/intro/migrations#generate-a-migration), check out the [Migrations docs](https://www.edgedb.com/docs/intro/migrations).
182
+ *
183
+ * ### Generate the query builder
184
+ *
185
+ * ```npm2yarn2pnpm
186
+ * npx @edgedb/generate edgeql-js
187
+ * ```
188
+ *
189
+ * This will generate the [query builder](https://www.edgedb.com/docs/clients/js/querybuilder) so that you can write fully typed EdgeQL queries with TypeScript in a code-first way.
190
+ *
191
+ * For example
192
+ *
193
+ * ```ts
194
+ * const query = e.select(e.User, () => ({
195
+ * id: true,
196
+ * email: true,
197
+ * emailVerified: true,
198
+ * name: true,
199
+ * image: true,
200
+ * filter_single: { email: 'johndoe@example.com' },
201
+ * }));
202
+ *
203
+ * return await query.run(client);
204
+ *
205
+ * // Return type:
206
+ * // {
207
+ * // id: string;
208
+ * // email: string;
209
+ * // emailVerified: Date | null;
210
+ * // image: string | null;
211
+ * // name: string | null;
212
+ * // } | null
213
+ *
214
+ * ```
215
+ *
216
+ *
217
+ * ## Deploying
218
+ *
219
+ * ### Deploy EdgeDB
220
+ *
221
+ * First deploy an EdgeDB instance on your preferred cloud provider:
222
+ *
223
+ * [AWS](https://www.edgedb.com/docs/guides/deployment/aws_aurora_ecs)
224
+ *
225
+ * [Google Cloud](https://www.edgedb.com/docs/guides/deployment/gcp)
226
+ *
227
+ * [Azure](https://www.edgedb.com/docs/guides/deployment/azure_flexibleserver)
228
+ *
229
+ * [DigitalOcean](https://www.edgedb.com/docs/guides/deployment/digitalocean)
230
+ *
231
+ * [Fly.io](https://www.edgedb.com/docs/guides/deployment/fly_io)
232
+ *
233
+ * [Docker](https://www.edgedb.com/docs/guides/deployment/docker) (cloud-agnostic)
234
+ *
235
+ * ### Find your instance’s DSN
236
+ *
237
+ * The DSN is also known as a connection string. It will have the format `edgedb://username:password@hostname:port`. The exact instructions for this depend on which cloud you are deploying to.
238
+ *
239
+ * ### Set an environment variable
240
+ *
241
+ * ```env title=".env"
242
+ * EDGEDB_DSN=edgedb://johndoe:supersecure@myhost.com:420
243
+ * ```
244
+ *
245
+ * ### Update the client
246
+ *
247
+ * ```diff title="pages/api/auth/[...nextauth].js"
248
+ * import NextAuth from "next-auth"
249
+ * import GoogleProvider from "next-auth/providers/google"
250
+ * import { EdgeDBAdapter } from "@auth/edgedb-adapter"
251
+ * import { createClient } from "edgedb"
252
+ *
253
+ * - const client = createClient()
254
+ * + const client = createClient({ dsn: process.env.EDGEDB_DSN })
255
+ *
256
+ * export default NextAuth({
257
+ * adapter: EdgeDBAdapter(client),
258
+ * providers: [
259
+ * GoogleProvider({
260
+ * clientId: process.env.GOOGLE_CLIENT_ID,
261
+ * clientSecret: process.env.GOOGLE_CLIENT_SECRET,
262
+ * }),
263
+ * ],
264
+ * })
265
+ * ```
266
+ *
267
+ *
268
+ *
269
+ * ### Apply migrations
270
+ *
271
+ * Use the DSN to apply migrations against your remote instance.
272
+ *
273
+ * ```bash
274
+ * edgedb migrate --dsn <your-instance-dsn>
275
+ * ```
276
+ *
277
+ * ### Set up a `prebuild` script
278
+ *
279
+ * Add the following `prebuild` script to your `package.json`. When your hosting provider initializes the build, it will trigger this script which will generate the query builder. The `npx @edgedb/generate edgeql-js` command will read the value of the `EDGEDB_DSN` environment variable, connect to the database, and generate the query builder before your hosting provider starts building the project.
280
+ *
281
+ * ```diff title="package.json"
282
+ * "scripts": {
283
+ * "dev": "next dev",
284
+ * "build": "next build",
285
+ * "start": "next start",
286
+ * "lint": "next lint",
287
+ * + "prebuild": "npx @edgedb/generate edgeql-js"
288
+ * },
289
+ * ```
290
+ *
291
+ */
292
+ export function EdgeDBAdapter(client: Client): Adapter {
293
+ return {
294
+ async createUser({ email, emailVerified, name, image }) {
295
+ return await client.queryRequiredSingle(
296
+ `
297
+ with
298
+ image := <optional str>$image,
299
+ name := <optional str>$name,
300
+ emailVerified := <optional str>$emailVerified
301
+
302
+ select (
303
+ insert User {
304
+ email:= <str>$email,
305
+ emailVerified:= <datetime>emailVerified,
306
+ name:= name,
307
+ image:= image,
308
+ }
309
+ ) {
310
+ id,
311
+ email,
312
+ emailVerified,
313
+ name,
314
+ image
315
+ }
316
+ `,
317
+ {
318
+ email,
319
+ emailVerified: emailVerified && new Date(emailVerified).toISOString(),
320
+ name,
321
+ image,
322
+ }
323
+ )
324
+ },
325
+ async getUser(id) {
326
+ return await client.querySingle<AdapterUser>(
327
+ `
328
+ select User {
329
+ id,
330
+ email,
331
+ emailVerified,
332
+ name,
333
+ image
334
+ } filter .id = <uuid>$id;
335
+ `,
336
+ { id }
337
+ )
338
+ },
339
+ async getUserByEmail(email) {
340
+ return await client.querySingle<AdapterUser>(
341
+ `
342
+ select User {
343
+ id,
344
+ email,
345
+ emailVerified,
346
+ name,
347
+ image
348
+ } filter .email = <str>$email;
349
+ `,
350
+ { email }
351
+ )
352
+ },
353
+ async getUserByAccount({ providerAccountId, provider }) {
354
+ return await client.querySingle<AdapterUser>(
355
+ `
356
+ with account := (
357
+ select Account
358
+ filter .providerAccountId = <str>$providerAccountId
359
+ and .provider = <str>$provider
360
+ )
361
+ select account.user {
362
+ id,
363
+ email,
364
+ image,
365
+ name,
366
+ emailVerified
367
+ }
368
+ `,
369
+ { providerAccountId, provider }
370
+ )
371
+ },
372
+ async updateUser({ email, emailVerified, id, image, name }) {
373
+ return await client.queryRequiredSingle<AdapterUser>(
374
+ `
375
+ with
376
+ email := <optional str>$email,
377
+ emailVerified := <optional str>$emailVerified,
378
+ image := <optional str>$image,
379
+ name := <optional str>$name
380
+
381
+ select (
382
+ update User
383
+ filter .id = <uuid>$id
384
+ set {
385
+ email := email ?? .email,
386
+ emailVerified := <datetime>emailVerified ?? .emailVerified,
387
+ image := image ?? .image,
388
+ name := name ?? .name,
389
+ }
390
+ ) {
391
+ id,
392
+ email,
393
+ emailVerified,
394
+ image,
395
+ name
396
+ }
397
+ `,
398
+ {
399
+ email,
400
+ emailVerified: emailVerified && new Date(emailVerified).toISOString(),
401
+ id,
402
+ image,
403
+ name,
404
+ }
405
+ )
406
+ },
407
+ async deleteUser(id) {
408
+ await client.execute(`delete User filter .id = <uuid>$id;`, { id })
409
+ },
410
+ async linkAccount({
411
+ userId,
412
+ type,
413
+ provider,
414
+ providerAccountId,
415
+ refresh_token,
416
+ access_token,
417
+ expires_at,
418
+ token_type,
419
+ scope,
420
+ id_token,
421
+ session_state,
422
+ }) {
423
+ await client.execute(
424
+ `
425
+ with
426
+ userId := <optional str>$userId,
427
+ refresh_token := <optional str>$refresh_token,
428
+ access_token := <optional str>$access_token,
429
+ expires_at := <optional str>$expires_at,
430
+ token_type := <optional str>$token_type,
431
+ scope := <optional str>$scope,
432
+ id_token := <optional str>$id_token,
433
+ session_state := <optional str>$session_state
434
+
435
+ insert Account {
436
+ type := <str>$type,
437
+ provider := <str>$provider,
438
+ providerAccountId := <str>$providerAccountId,
439
+ refresh_token := refresh_token,
440
+ access_token := access_token,
441
+ expires_at := <int64>expires_at,
442
+ token_type := token_type,
443
+ scope := scope,
444
+ id_token := id_token,
445
+ session_state := session_state,
446
+ user := (
447
+ select User filter .id = <uuid>userId
448
+ )
449
+ }
450
+ `,
451
+ {
452
+ userId,
453
+ type,
454
+ provider,
455
+ providerAccountId,
456
+ refresh_token,
457
+ access_token,
458
+ expires_at: expires_at && String(expires_at),
459
+ token_type,
460
+ scope,
461
+ id_token,
462
+ session_state,
463
+ }
464
+ )
465
+ },
466
+ async unlinkAccount({ providerAccountId, provider }) {
467
+ await client.execute(
468
+ `
469
+ delete Account filter
470
+ .providerAccountId = <str>$providerAccountId
471
+ and
472
+ .provider = <str>$provider
473
+ `,
474
+ { providerAccountId, provider }
475
+ )
476
+ },
477
+ async createSession({ expires, sessionToken, userId }) {
478
+ return await client.queryRequiredSingle<AdapterSession>(
479
+ `
480
+ select (
481
+ insert Session {
482
+ expires := <datetime>$expires,
483
+ sessionToken := <str>$sessionToken,
484
+ user := (
485
+ select User filter .id = <uuid>$userId
486
+ )
487
+ }
488
+ ) {
489
+ expires,
490
+ sessionToken,
491
+ userId
492
+ };
493
+ `,
494
+ { expires, sessionToken, userId }
495
+ )
496
+ },
497
+ async getSessionAndUser(sessionToken) {
498
+ const sessionAndUser = await client.querySingle<
499
+ AdapterSession & { user: AdapterUser }
500
+ >(
501
+ `
502
+ select Session {
503
+ userId,
504
+ id,
505
+ expires,
506
+ sessionToken,
507
+ user: {
508
+ id,
509
+ email,
510
+ emailVerified,
511
+ image,
512
+ name
513
+ }
514
+ } filter .sessionToken = <str>$sessionToken;
515
+ `,
516
+ { sessionToken }
517
+ )
518
+
519
+ if (!sessionAndUser) {
520
+ return null
521
+ }
522
+
523
+ const { user, ...session } = sessionAndUser
524
+
525
+ if (!user || !session) {
526
+ return null
527
+ }
528
+
529
+ return {
530
+ user,
531
+ session,
532
+ }
533
+ },
534
+ async updateSession({ sessionToken, expires, userId }) {
535
+ return await client.querySingle<AdapterSession>(
536
+ `
537
+ with
538
+ sessionToken := <optional str>$sessionToken,
539
+ expires := <optional str>$expires,
540
+ userId := <optional str>$userId,
541
+ user := (
542
+ select User filter .id = <uuid>userId
543
+ )
544
+
545
+ select (
546
+ update Session
547
+ filter .sessionToken = <str>$sessionToken
548
+ set {
549
+ sessionToken := sessionToken ?? .sessionToken,
550
+ expires := <datetime>expires ?? .expires,
551
+ user := user ?? .user
552
+ }
553
+ ) {
554
+ sessionToken,
555
+ userId,
556
+ expires
557
+ }
558
+ `,
559
+ {
560
+ sessionToken,
561
+ expires: expires && new Date(expires).toISOString(),
562
+ userId,
563
+ }
564
+ )
565
+ },
566
+ async deleteSession(sessionToken) {
567
+ await client.query(
568
+ `delete Session filter .sessionToken = <str>$sessionToken`,
569
+ { sessionToken }
570
+ )
571
+ },
572
+ async createVerificationToken({ identifier, expires, token }) {
573
+ const createdVerificationToken =
574
+ await client.querySingle<VerificationToken>(
575
+ `
576
+ select (
577
+ insert VerificationToken {
578
+ identifier := <str>$identifier,
579
+ expires := <datetime>$expires,
580
+ token := <str>$token,
581
+ }
582
+ ) {
583
+ identifier,
584
+ expires,
585
+ token
586
+ }
587
+ `,
588
+ { identifier, expires, token }
589
+ )
590
+
591
+ return createdVerificationToken
592
+ },
593
+ async useVerificationToken({ token, identifier }) {
594
+ const verificationToken = await client.querySingle<VerificationToken>(
595
+ `
596
+ select (
597
+ delete VerificationToken filter .token = <str>$token
598
+ and
599
+ .identifier = <str>$identifier
600
+ ) {
601
+ identifier,
602
+ expires,
603
+ token
604
+ }
605
+ `,
606
+ { token, identifier }
607
+ )
608
+
609
+ if (verificationToken && "id" in verificationToken) {
610
+ delete verificationToken.id
611
+ }
612
+ return verificationToken
613
+ },
614
+ }
615
+ }