@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/index.js ADDED
@@ -0,0 +1,546 @@
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
+ *
20
+ * To use this Adapter, you need to install `edgedb`, `@edgedb/generate`, and the separate `@auth/edgedb-adapter` package:
21
+ *
22
+ * ```bash npm2yarn2pnpm
23
+ * npm install edgedb @auth/edgedb-adapter
24
+ * npm install @edgedb/generate --save-dev
25
+ * ```
26
+ *
27
+ * ## Installation
28
+ *
29
+ * First, ensure you have the EdgeDB CLI installed.
30
+ *
31
+ * 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
32
+ *
33
+ * ### Linux or macOS
34
+ * ```bash
35
+ * curl --proto '=https' --tlsv1.2 -sSf https://sh.edgedb.com | sh
36
+ * ```
37
+ *
38
+ * ### Windows
39
+ * ```powershell
40
+ * iwr https://ps1.edgedb.com -useb | iex
41
+ * ```
42
+ *
43
+ * 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.
44
+ *
45
+ * Once the CLI is installed, initialize a project from the application’s root directory. You’ll be presented with a series of prompts.
46
+ *
47
+ * ```bash
48
+ * edgedb project init
49
+ * ```
50
+ *
51
+ * 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.
52
+ *
53
+ * ## Setup
54
+ *
55
+ * ### NextAuth.js configuration
56
+ *
57
+ * Configure your NextAuth.js to use the EdgeDB Adapter:
58
+ *
59
+ * ```javascript title="pages/api/auth/[...nextauth].js"
60
+ * import NextAuth from "next-auth"
61
+ * import GoogleProvider from "next-auth/providers/google"
62
+ * import { EdgeDBAdapter } from "@auth/edgedb-adapter"
63
+ * import { createClient } from "edgedb"
64
+ *
65
+ * const client = createClient()
66
+ *
67
+ * export default NextAuth({
68
+ * adapter: EdgeDBAdapter(client),
69
+ * providers: [
70
+ * GoogleProvider({
71
+ * clientId: process.env.GOOGLE_CLIENT_ID,
72
+ * clientSecret: process.env.GOOGLE_CLIENT_SECRET,
73
+ * }),
74
+ * ],
75
+ * })
76
+ * ```
77
+ *
78
+ * ### Create the EdgeDB schema
79
+ *
80
+ * Replace the contents of the auto-generated file in `dbschema/default.esdl` with the following:
81
+ *
82
+ * > This schema is adapted for use in EdgeDB and based upon our main [schema](/adapters/models)
83
+ *
84
+ * ```json title="default.esdl"
85
+ * module default {
86
+ * type User {
87
+ * property name -> str;
88
+ * required property email -> str {
89
+ * constraint exclusive;
90
+ * }
91
+ * property emailVerified -> datetime;
92
+ * property image -> str;
93
+ * multi link accounts := .<user[is Account];
94
+ * multi link sessions := .<user[is Session];
95
+ * property createdAt -> datetime {
96
+ * default := datetime_current();
97
+ * };
98
+ * }
99
+ *
100
+ * type Account {
101
+ * required property userId := .user.id;
102
+ * required property type -> str;
103
+ * required property provider -> str;
104
+ * required property providerAccountId -> str {
105
+ * constraint exclusive;
106
+ * };
107
+ * property refresh_token -> str;
108
+ * property access_token -> str;
109
+ * property expires_at -> int64;
110
+ * property token_type -> str;
111
+ * property scope -> str;
112
+ * property id_token -> str;
113
+ * property session_state -> str;
114
+ * required link user -> User {
115
+ * on target delete delete source;
116
+ * };
117
+ * property createdAt -> datetime {
118
+ * default := datetime_current();
119
+ * };
120
+ *
121
+ * constraint exclusive on ((.provider, .providerAccountId))
122
+ * }
123
+ *
124
+ * type Session {
125
+ * required property sessionToken -> str {
126
+ * constraint exclusive;
127
+ * }
128
+ * required property userId := .user.id;
129
+ * required property expires -> datetime;
130
+ * required link user -> User {
131
+ * on target delete delete source;
132
+ * };
133
+ * property createdAt -> datetime {
134
+ * default := datetime_current();
135
+ * };
136
+ * }
137
+ *
138
+ * type VerificationToken {
139
+ * required property identifier -> str;
140
+ * required property token -> str {
141
+ * constraint exclusive;
142
+ * }
143
+ * required property expires -> datetime;
144
+ * property createdAt -> datetime {
145
+ * default := datetime_current();
146
+ * };
147
+ *
148
+ * constraint exclusive on ((.identifier, .token))
149
+ * }
150
+ * }
151
+ *
152
+ * # Disable the application of access policies within access policies
153
+ * # themselves. This behavior will become the default in EdgeDB 3.0.
154
+ * # See: https://www.edgedb.com/docs/reference/ddl/access_policies#nonrecursive
155
+ * using future nonrecursive_access_policies;
156
+ * ```
157
+ *
158
+ * ### Migrate the database schema
159
+ *
160
+ * Create a migration
161
+ *
162
+ * ```
163
+ * edgedb migration create
164
+ * ```
165
+ *
166
+ * Apply the migration
167
+ *
168
+ * ```
169
+ * edgedb migrate
170
+ * ```
171
+ *
172
+ * 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).
173
+ *
174
+ * ### Generate the query builder
175
+ *
176
+ * ```npm2yarn2pnpm
177
+ * npx @edgedb/generate edgeql-js
178
+ * ```
179
+ *
180
+ * 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.
181
+ *
182
+ * For example
183
+ *
184
+ * ```ts
185
+ * const query = e.select(e.User, () => ({
186
+ * id: true,
187
+ * email: true,
188
+ * emailVerified: true,
189
+ * name: true,
190
+ * image: true,
191
+ * filter_single: { email: 'johndoe@example.com' },
192
+ * }));
193
+ *
194
+ * return await query.run(client);
195
+ *
196
+ * // Return type:
197
+ * // {
198
+ * // id: string;
199
+ * // email: string;
200
+ * // emailVerified: Date | null;
201
+ * // image: string | null;
202
+ * // name: string | null;
203
+ * // } | null
204
+ *
205
+ * ```
206
+ *
207
+ *
208
+ * ## Deploying
209
+ *
210
+ * ### Deploy EdgeDB
211
+ *
212
+ * First deploy an EdgeDB instance on your preferred cloud provider:
213
+ *
214
+ * [AWS](https://www.edgedb.com/docs/guides/deployment/aws_aurora_ecs)
215
+ *
216
+ * [Google Cloud](https://www.edgedb.com/docs/guides/deployment/gcp)
217
+ *
218
+ * [Azure](https://www.edgedb.com/docs/guides/deployment/azure_flexibleserver)
219
+ *
220
+ * [DigitalOcean](https://www.edgedb.com/docs/guides/deployment/digitalocean)
221
+ *
222
+ * [Fly.io](https://www.edgedb.com/docs/guides/deployment/fly_io)
223
+ *
224
+ * [Docker](https://www.edgedb.com/docs/guides/deployment/docker) (cloud-agnostic)
225
+ *
226
+ * ### Find your instance’s DSN
227
+ *
228
+ * 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.
229
+ *
230
+ * ### Set an environment variable
231
+ *
232
+ * ```env title=".env"
233
+ * EDGEDB_DSN=edgedb://johndoe:supersecure@myhost.com:420
234
+ * ```
235
+ *
236
+ * ### Update the client
237
+ *
238
+ * ```diff title="pages/api/auth/[...nextauth].js"
239
+ * import NextAuth from "next-auth"
240
+ * import GoogleProvider from "next-auth/providers/google"
241
+ * import { EdgeDBAdapter } from "@auth/edgedb-adapter"
242
+ * import { createClient } from "edgedb"
243
+ *
244
+ * - const client = createClient()
245
+ * + const client = createClient({ dsn: process.env.EDGEDB_DSN })
246
+ *
247
+ * export default NextAuth({
248
+ * adapter: EdgeDBAdapter(client),
249
+ * providers: [
250
+ * GoogleProvider({
251
+ * clientId: process.env.GOOGLE_CLIENT_ID,
252
+ * clientSecret: process.env.GOOGLE_CLIENT_SECRET,
253
+ * }),
254
+ * ],
255
+ * })
256
+ * ```
257
+ *
258
+ *
259
+ *
260
+ * ### Apply migrations
261
+ *
262
+ * Use the DSN to apply migrations against your remote instance.
263
+ *
264
+ * ```bash
265
+ * edgedb migrate --dsn <your-instance-dsn>
266
+ * ```
267
+ *
268
+ * ### Set up a `prebuild` script
269
+ *
270
+ * 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.
271
+ *
272
+ * ```diff title="package.json"
273
+ * "scripts": {
274
+ * "dev": "next dev",
275
+ * "build": "next build",
276
+ * "start": "next start",
277
+ * "lint": "next lint",
278
+ * + "prebuild": "npx @edgedb/generate edgeql-js"
279
+ * },
280
+ * ```
281
+ *
282
+ */
283
+ export function EdgeDBAdapter(client) {
284
+ return {
285
+ async createUser({ email, emailVerified, name, image }) {
286
+ return await client.queryRequiredSingle(`
287
+ with
288
+ image := <optional str>$image,
289
+ name := <optional str>$name,
290
+ emailVerified := <optional str>$emailVerified
291
+
292
+ select (
293
+ insert User {
294
+ email:= <str>$email,
295
+ emailVerified:= <datetime>emailVerified,
296
+ name:= name,
297
+ image:= image,
298
+ }
299
+ ) {
300
+ id,
301
+ email,
302
+ emailVerified,
303
+ name,
304
+ image
305
+ }
306
+ `, {
307
+ email,
308
+ emailVerified: emailVerified && new Date(emailVerified).toISOString(),
309
+ name,
310
+ image,
311
+ });
312
+ },
313
+ async getUser(id) {
314
+ return await client.querySingle(`
315
+ select User {
316
+ id,
317
+ email,
318
+ emailVerified,
319
+ name,
320
+ image
321
+ } filter .id = <uuid>$id;
322
+ `, { id });
323
+ },
324
+ async getUserByEmail(email) {
325
+ return await client.querySingle(`
326
+ select User {
327
+ id,
328
+ email,
329
+ emailVerified,
330
+ name,
331
+ image
332
+ } filter .email = <str>$email;
333
+ `, { email });
334
+ },
335
+ async getUserByAccount({ providerAccountId, provider }) {
336
+ return await client.querySingle(`
337
+ with account := (
338
+ select Account
339
+ filter .providerAccountId = <str>$providerAccountId
340
+ and .provider = <str>$provider
341
+ )
342
+ select account.user {
343
+ id,
344
+ email,
345
+ image,
346
+ name,
347
+ emailVerified
348
+ }
349
+ `, { providerAccountId, provider });
350
+ },
351
+ async updateUser({ email, emailVerified, id, image, name }) {
352
+ return await client.queryRequiredSingle(`
353
+ with
354
+ email := <optional str>$email,
355
+ emailVerified := <optional str>$emailVerified,
356
+ image := <optional str>$image,
357
+ name := <optional str>$name
358
+
359
+ select (
360
+ update User
361
+ filter .id = <uuid>$id
362
+ set {
363
+ email := email ?? .email,
364
+ emailVerified := <datetime>emailVerified ?? .emailVerified,
365
+ image := image ?? .image,
366
+ name := name ?? .name,
367
+ }
368
+ ) {
369
+ id,
370
+ email,
371
+ emailVerified,
372
+ image,
373
+ name
374
+ }
375
+ `, {
376
+ email,
377
+ emailVerified: emailVerified && new Date(emailVerified).toISOString(),
378
+ id,
379
+ image,
380
+ name,
381
+ });
382
+ },
383
+ async deleteUser(id) {
384
+ await client.execute(`delete User filter .id = <uuid>$id;`, { id });
385
+ },
386
+ async linkAccount({ userId, type, provider, providerAccountId, refresh_token, access_token, expires_at, token_type, scope, id_token, session_state, }) {
387
+ await client.execute(`
388
+ with
389
+ userId := <optional str>$userId,
390
+ refresh_token := <optional str>$refresh_token,
391
+ access_token := <optional str>$access_token,
392
+ expires_at := <optional str>$expires_at,
393
+ token_type := <optional str>$token_type,
394
+ scope := <optional str>$scope,
395
+ id_token := <optional str>$id_token,
396
+ session_state := <optional str>$session_state
397
+
398
+ insert Account {
399
+ type := <str>$type,
400
+ provider := <str>$provider,
401
+ providerAccountId := <str>$providerAccountId,
402
+ refresh_token := refresh_token,
403
+ access_token := access_token,
404
+ expires_at := <int64>expires_at,
405
+ token_type := token_type,
406
+ scope := scope,
407
+ id_token := id_token,
408
+ session_state := session_state,
409
+ user := (
410
+ select User filter .id = <uuid>userId
411
+ )
412
+ }
413
+ `, {
414
+ userId,
415
+ type,
416
+ provider,
417
+ providerAccountId,
418
+ refresh_token,
419
+ access_token,
420
+ expires_at: expires_at && String(expires_at),
421
+ token_type,
422
+ scope,
423
+ id_token,
424
+ session_state,
425
+ });
426
+ },
427
+ async unlinkAccount({ providerAccountId, provider }) {
428
+ await client.execute(`
429
+ delete Account filter
430
+ .providerAccountId = <str>$providerAccountId
431
+ and
432
+ .provider = <str>$provider
433
+ `, { providerAccountId, provider });
434
+ },
435
+ async createSession({ expires, sessionToken, userId }) {
436
+ return await client.queryRequiredSingle(`
437
+ select (
438
+ insert Session {
439
+ expires := <datetime>$expires,
440
+ sessionToken := <str>$sessionToken,
441
+ user := (
442
+ select User filter .id = <uuid>$userId
443
+ )
444
+ }
445
+ ) {
446
+ expires,
447
+ sessionToken,
448
+ userId
449
+ };
450
+ `, { expires, sessionToken, userId });
451
+ },
452
+ async getSessionAndUser(sessionToken) {
453
+ const sessionAndUser = await client.querySingle(`
454
+ select Session {
455
+ userId,
456
+ id,
457
+ expires,
458
+ sessionToken,
459
+ user: {
460
+ id,
461
+ email,
462
+ emailVerified,
463
+ image,
464
+ name
465
+ }
466
+ } filter .sessionToken = <str>$sessionToken;
467
+ `, { sessionToken });
468
+ if (!sessionAndUser) {
469
+ return null;
470
+ }
471
+ const { user, ...session } = sessionAndUser;
472
+ if (!user || !session) {
473
+ return null;
474
+ }
475
+ return {
476
+ user,
477
+ session,
478
+ };
479
+ },
480
+ async updateSession({ sessionToken, expires, userId }) {
481
+ return await client.querySingle(`
482
+ with
483
+ sessionToken := <optional str>$sessionToken,
484
+ expires := <optional str>$expires,
485
+ userId := <optional str>$userId,
486
+ user := (
487
+ select User filter .id = <uuid>userId
488
+ )
489
+
490
+ select (
491
+ update Session
492
+ filter .sessionToken = <str>$sessionToken
493
+ set {
494
+ sessionToken := sessionToken ?? .sessionToken,
495
+ expires := <datetime>expires ?? .expires,
496
+ user := user ?? .user
497
+ }
498
+ ) {
499
+ sessionToken,
500
+ userId,
501
+ expires
502
+ }
503
+ `, {
504
+ sessionToken,
505
+ expires: expires && new Date(expires).toISOString(),
506
+ userId,
507
+ });
508
+ },
509
+ async deleteSession(sessionToken) {
510
+ await client.query(`delete Session filter .sessionToken = <str>$sessionToken`, { sessionToken });
511
+ },
512
+ async createVerificationToken({ identifier, expires, token }) {
513
+ const createdVerificationToken = await client.querySingle(`
514
+ select (
515
+ insert VerificationToken {
516
+ identifier := <str>$identifier,
517
+ expires := <datetime>$expires,
518
+ token := <str>$token,
519
+ }
520
+ ) {
521
+ identifier,
522
+ expires,
523
+ token
524
+ }
525
+ `, { identifier, expires, token });
526
+ return createdVerificationToken;
527
+ },
528
+ async useVerificationToken({ token, identifier }) {
529
+ const verificationToken = await client.querySingle(`
530
+ select (
531
+ delete VerificationToken filter .token = <str>$token
532
+ and
533
+ .identifier = <str>$identifier
534
+ ) {
535
+ identifier,
536
+ expires,
537
+ token
538
+ }
539
+ `, { token, identifier });
540
+ if (verificationToken && "id" in verificationToken) {
541
+ delete verificationToken.id;
542
+ }
543
+ return verificationToken;
544
+ },
545
+ };
546
+ }
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@auth/edgedb-adapter",
3
+ "version": "0.2.0",
4
+ "description": "EdgeDB adapter for next-auth.",
5
+ "homepage": "https://authjs.dev",
6
+ "repository": "https://github.com/nextauthjs/next-auth",
7
+ "bugs": {
8
+ "url": "https://github.com/nextauthjs/next-auth/issues"
9
+ },
10
+ "author": "Bruno Crosier",
11
+ "type": "module",
12
+ "types": "./index.d.ts",
13
+ "files": [
14
+ "*.d.ts*",
15
+ "*.js",
16
+ "lib",
17
+ "src"
18
+ ],
19
+ "exports": {
20
+ ".": {
21
+ "types": "./index.d.ts",
22
+ "import": "./index.js"
23
+ }
24
+ },
25
+ "license": "ISC",
26
+ "keywords": [
27
+ "next-auth",
28
+ "next.js",
29
+ "oauth",
30
+ "edgedb"
31
+ ],
32
+ "private": false,
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "peerDependencies": {
37
+ "edgedb": "^1.0.1",
38
+ "@auth/core": "^0.3.0"
39
+ },
40
+ "devDependencies": {
41
+ "@auth/adapter-test": "^0.0.0",
42
+ "@auth/tsconfig": "^0.0.0",
43
+ "jest": "^27.4.3",
44
+ "typescript": "^4.7.4",
45
+ "edgedb": "^1.0.1",
46
+ "@auth/core": "0.15.0"
47
+ },
48
+ "jest": {
49
+ "preset": "@auth/adapter-test/jest"
50
+ },
51
+ "scripts": {
52
+ "build": "tsc",
53
+ "test": "jest"
54
+ }
55
+ }