-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
entities.md
743 lines (582 loc) · 22.2 KB
/
entities.md
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
---
title: Accessing User Data
---
import ImgWithCaption from '@site/blog/components/ImgWithCaption'
import { Internal } from '@site/src/components/Tag'
import MultipleIdentitiesWarning from '../\_multiple-identities-warning.md';
import UsernameData from './\_username-data.md';
import EmailData from './\_email-data.md';
import GoogleData from './\_google-data.md';
import GithubData from './\_github-data.md';
import KeycloakData from './\_keycloak-data.md';
First, we'll check out the most practical info: **how to access the user's data in your app**.
Then, we'll dive into the details of the **auth entities** that Wasp creates behind the scenes to store the user's data. For auth each method, Wasp needs to store different information about the user. For example, username for [Username & password](./username-and-pass) auth, email verification status for [Email](./email) auth, and so on.
We'll also show you how you can use these entities to create a custom signup action.
## Accessing the Auth Fields
When you receive the `user` object [on the client or the server](../overview.md#accessing-the-logged-in-user), it will contain all the user fields you defined in the `User` entity in your Wasp file. In addition to that, it will also contain all the auth-related fields that Wasp stores. This includes things like the `username` or the email verification status. In Wasp, this data is called the `AuthUser` object.
### `AuthUser` Object Fields
All the `User` fields you defined will be present at the top level of the `AuthUser` object. The auth-related fields will be on the `identities` object. For each auth method you enable, there will be a separate data object in the `identities` object.
The `AuthUser` object will change depending on which auth method you have enabled in the Wasp file. For example, if you enabled the email auth and Google auth, it would look something like this:
<Tabs>
<TabItem value="google" label="User Signed Up with Google">
If the user has only the Google identity, the `AuthUser` object will look like this:
```ts
const user = {
// User data
id: 'cluqs9qyh00007cn73apj4hp7',
address: 'Some address',
// Auth methods specific data
identities: {
email: null,
google: {
id: '1117XXXX1301972049448',
},
},
}
```
</TabItem>
<TabItem value="email" label="User Signed Up with Email">
If the user has only the email identity, the `AuthUser` object will look like this:
```ts
const user = {
// User data
id: 'cluqsex9500017cn7i2hwsg17',
address: 'Some address',
// Auth methods specific data
identities: {
email: {
id: 'user@app.com',
isEmailVerified: true,
emailVerificationSentAt: '2024-04-08T10:06:02.204Z',
passwordResetSentAt: null,
},
google: null,
},
}
```
</TabItem>
</Tabs>
In the examples above, you can see the `identities` object contains the `email` and `google` objects. The `email` object contains the email-related data and the `google` object contains the Google-related data.
:::info Make sure to check if the data exists
Before accessing some auth method's data, you'll need to check if that data exists for the user and then access it:
```ts
if (user.identities.google !== null) {
const userId = user.identities.google.id
// ...
}
```
You need to do this because if a user didn't sign up with some auth method, the data for that auth method will be `null`.
:::
Let's look at the data for each of the available auth methods:
- [Username & password](../username-and-pass.md) data
<UsernameData />
- [Email](../email.md) data
<EmailData />
- [Google](../social-auth/google.md) data
<GoogleData />
- [GitHub](../social-auth/github.md) data
<GithubData />
- [Keycloak](../social-auth/keycloak.md) data
<KeycloakData />
If you support multiple auth methods, you'll need to find which identity exists for the user and then access its data:
```ts
if (user.identities.email !== null) {
const email = user.identities.email.id
// ...
} else if (user.identities.google !== null) {
const googleId = user.identities.google.id
// ...
}
```
### `getFirstProviderUserId` Helper
The `getFirstProviderUserId` method returns the first user ID that it finds for the user. For example if the user has signed up with email, it will return the email. If the user has signed up with Google, it will return the Google ID.
This can be useful if you support multiple authentication methods and you need _any_ ID that identifies the user in your app.
<Tabs groupId="js-ts">
<TabItem value="js" label="JavaScript">
```jsx title="src/MainPage.jsx"
const MainPage = ({ user }) => {
const userId = user.getFirstProviderUserId()
// ...
}
```
```js title=src/tasks.js
export const createTask = async (args, context) => {
const userId = context.user.getFirstProviderUserId()
// ...
}
```
</TabItem>
<TabItem value="ts" label="TypeScript">
```tsx title="src/MainPage.tsx"
import { type AuthUser } from 'wasp/auth'
const MainPage = ({ user }: { user: AuthUser }) => {
const userId = user.getFirstProviderUserId()
// ...
}
```
```ts title=src/tasks.ts
export const createTask: CreateTask<...> = async (args, context) => {
const userId = context.user.getFirstProviderUserId()
// ...
}
```
</TabItem>
</Tabs>
<small>
\* Multiple identities per user will be possible in the future and then the `getFirstProviderUserId` method will return the ID of the first identity that it finds without any guarantees about which one it will be.
</small>
## Including the User with Other Entities
Sometimes, you might want to include the user's data when fetching other entities. For example, you might want to include the user's data with the tasks they have created.
We'll mention the `auth` and the `identities` relations which we will explain in more detail later in the [Entities Explained](#entities-explained) section.
:::caution Be careful about sensitive data
You'll need to include the `auth` and the `identities` relations to get the full auth data about the user. However, you should keep in mind that the `providerData` field in the `identities` can contain sensitive data like the user's hashed password (in case of email or username auth), so you will likely want to exclude it if you are returning those values to the client.
:::
You can include the full user's data with other entities using the `include` option in the Prisma queries:
<Tabs groupId="js-ts">
<TabItem value="js" label="JavaScript">
```js title="src/tasks.js"
export const getAllTasks = async (args, context) => {
return context.entities.Task.findMany({
orderBy: { id: 'desc' },
select: {
id: true,
title: true,
// highlight-next-line
user: {
include: {
// highlight-next-line
auth: {
include: {
// highlight-next-line
identities: {
// Including only the `providerName` and `providerUserId` fields
select: {
providerName: true,
providerUserId: true,
},
},
},
},
},
},
},
})
}
```
</TabItem>
<TabItem value="ts" label="TypeScript">
```ts title="src/tasks.ts"
export const getAllTasks = (async (args, context) => {
return context.entities.Task.findMany({
orderBy: { id: 'desc' },
select: {
id: true,
title: true,
// highlight-next-line
user: {
include: {
// highlight-next-line
auth: {
include: {
// highlight-next-line
identities: {
// Including only the `providerName` and `providerUserId` fields
select: {
providerName: true,
providerUserId: true,
},
},
},
},
},
},
},
})
}) satisfies tasks.GetAllQuery<{}, {}>
```
</TabItem>
</Tabs>
If you have some **piece of the auth data that you want to access frequently** (for example the `username`), it's best to store it at the top level of the `User` entity.
For example, save the `username` or `email` as a property on the `User` and you'll be able to access it without including the `auth` and `identities` fields. We show an example in the [Defining Extra Fields on the User Entity](../overview.md#1-defining-extra-fields) section of the docs.
### Getting Auth Data from the User Object
When you have the `user` object with the `auth` and `identities` fields, it can be a bit tedious to obtain the auth data (like username or Google ID) from it:
<Tabs groupId="js-ts">
<TabItem value="js" label="JavaScript">
```jsx title="src/MainPage.jsx"
function MainPage() {
// ...
return (
<div className="tasks">
{tasks.map((task) => (
<div key={task.id} className="task">
{task.title} by {task.user.auth?.identities[0].providerUserId}
</div>
))}
</div>
)
}
```
</TabItem>
<TabItem value="ts" label="TypeScript">
```tsx title="src/MainPage.tsx"
function MainPage() {
// ...
return (
<div className="tasks">
{tasks.map((task) => (
<div key={task.id} className="task">
{task.title} by {task.user.auth?.identities[0].providerUserId}
</div>
))}
</div>
)
}
```
</TabItem>
</Tabs>
Wasp offers a few helper methods to access the user's auth data when you retrieve the `user` like this. They are `getUsername`, `getEmail` and `getFirstProviderUserId`. They can be used both on the client and the server.
#### `getUsername`
It accepts the `user` object and if the user signed up with the [Username & password](./username-and-pass) auth method, it returns the username or `null` otherwise. The `user` object needs to have the `auth` and the `identities` relations included.
<Tabs groupId="js-ts">
<TabItem value="js" label="JavaScript">
```jsx title="src/MainPage.jsx"
import { getUsername } from 'wasp/auth'
function MainPage() {
// ...
return (
<div className="tasks">
{tasks.map((task) => (
<div key={task.id} className="task">
{task.title} by {getUsername(task.user)}
</div>
))}
</div>
)
}
```
</TabItem>
<TabItem value="ts" label="TypeScript">
```tsx title="src/MainPage.tsx"
import { getUsername } from 'wasp/auth'
function MainPage() {
// ...
return (
<div className="tasks">
{tasks.map((task) => (
<div key={task.id} className="task">
{task.title} by {getUsername(task.user)}
</div>
))}
</div>
)
}
```
</TabItem>
</Tabs>
#### `getEmail`
It accepts the `user` object and if the user signed up with the [Email](./email) auth method, it returns the email or `null` otherwise. The `user` object needs to have the `auth` and the `identities` relations included.
<Tabs groupId="js-ts">
<TabItem value="js" label="JavaScript">
```jsx title="src/MainPage.jsx"
import { getEmail } from 'wasp/auth'
function MainPage() {
// ...
return (
<div className="tasks">
{tasks.map((task) => (
<div key={task.id} className="task">
{task.title} by {getEmail(task.user)}
</div>
))}
</div>
)
}
```
</TabItem>
<TabItem value="ts" label="TypeScript">
```tsx title="src/MainPage.tsx"
import { getEmail } from 'wasp/auth'
function MainPage() {
// ...
return (
<div className="tasks">
{tasks.map((task) => (
<div key={task.id} className="task">
{task.title} by {getEmail(task.user)}
</div>
))}
</div>
)
}
```
</TabItem>
</Tabs>
#### `getFirstProviderUserId`
It returns the first user ID that it finds for the user. For example if the user has signed up with email, it will return the email. If the user has signed up with Google, it will return the Google ID. The `user` object needs to have the `auth` and the `identities` relations included.
<Tabs groupId="js-ts">
<TabItem value="js" label="JavaScript">
```jsx title="src/MainPage.jsx"
import { getFirstProviderUserId } from 'wasp/auth'
function MainPage() {
// ...
return (
<div className="tasks">
{tasks.map((task) => (
<div key={task.id} className="task">
{task.title} by {getFirstProviderUserId(task.user)}
</div>
))}
</div>
)
}
```
</TabItem>
<TabItem value="ts" label="TypeScript">
```tsx title="src/MainPage.tsx"
import { getFirstProviderUserId } from 'wasp/auth'
function MainPage() {
// ...
return (
<div className="tasks">
{tasks.map((task) => (
<div key={task.id} className="task">
{task.title} by {getFirstProviderUserId(task.user)}
</div>
))}
</div>
)
}
```
</TabItem>
</Tabs>
## Entities Explained
To store user information, Wasp creates a few entities behind the scenes. In this section, we will explain what entities are created and how they are connected.
### User Entity
When you want to add authentication to your app, you need to specify the user entity e.g. `User` in your Wasp file. This entity is a "business logic user" which represents a user of your app.
You can use this entity to store any information about the user that you want to store. For example, you might want to store the user's name or address. You can also use the user entity to define the relations between users and other entities in your app. For example, you might want to define a relation between a user and the tasks that they have created.
```wasp
entity User {=psl
id Int @id @default(autoincrement())
// Any other fields you want to store about the user
psl=}
```
You **own** the user entity and you can modify it as you wish. You can add new fields to it, remove fields from it, or change the type of the fields. You can also add new relations to it or remove existing relations from it.
<ImgWithCaption alt="Auth Entities in a Wasp App" source="img/auth-entities/model.png" caption="Auth Entities in a Wasp App"/>
On the other hand, the `Auth`, `AuthIdentity` and `Session` entities are created behind the scenes and are used to store the user's login credentials. You as the developer don't need to care about this entity most of the time. Wasp **owns** these entities.
In the case you want to create a custom signup action, you will need to use the `Auth` and `AuthIdentity` entities directly.
### Example App Model
Let's imagine we created a simple tasks management app:
- The app has email and Google-based auth.
- Users can create tasks and see the tasks that they have created.
Let's look at how would that look in the database:
<ImgWithCaption alt="Example of Auth Entities" source="img/auth-entities/model-example.png" caption="Example of Auth Entities"/>
If we take a look at an example user in the database, we can see:
- The business logic user, `User` is connected to multiple `Task` entities.
- In this example, "Example User" has two tasks.
- The `User` is connected to exactly one `Auth` entity.
- Each `Auth` entity can have multiple `AuthIdentity` entities.
- In this example, the `Auth` entity has two `AuthIdentity` entities: one for the email-based auth and one for the Google-based auth.
- Each `Auth` entity can have multiple `Session` entities.
- In this example, the `Auth` entity has one `Session` entity.
<MultipleIdentitiesWarning />
### `Auth` Entity <Internal />
Wasp's internal `Auth` entity is used to connect the business logic user, `User` with the user's login credentials.
```wasp
entity Auth {=psl
id String @id @default(uuid())
userId Int? @unique
// Wasp injects this relation on the User entity as well
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
identities AuthIdentity[]
sessions Session[]
psl=}
```
The `Auth` fields:
- `id` is a unique identifier of the `Auth` entity.
- `userId` is a foreign key to the `User` entity.
- It is used to connect the `Auth` entity with the business logic user.
- `user` is a relation to the `User` entity.
- This relation is injected on the `User` entity as well.
- `identities` is a relation to the `AuthIdentity` entity.
- `sessions` is a relation to the `Session` entity.
### `AuthIdentity` Entity <Internal />
The `AuthIdentity` entity is used to store the user's login credentials for various authentication methods.
```wasp
entity AuthIdentity {=psl
providerName String
providerUserId String
providerData String @default("{}")
authId String
auth Auth @relation(fields: [authId], references: [id], onDelete: Cascade)
@@id([providerName, providerUserId])
psl=}
```
The `AuthIdentity` fields:
- `providerName` is the name of the authentication provider.
- For example, `email` or `google`.
- `providerUserId` is the user's ID in the authentication provider.
- For example, the user's email or Google ID.
- `providerData` is a JSON string that contains additional data about the user from the authentication provider.
- For example, for password based auth, this field contains the user's hashed password.
- This field is a `String` and not a `Json` type because [Prisma doesn't support the `Json` type for SQLite](https://github.com/prisma/prisma/issues/3786).
- `authId` is a foreign key to the `Auth` entity.
- It is used to connect the `AuthIdentity` entity with the `Auth` entity.
- `auth` is a relation to the `Auth` entity.
### `Session` Entity <Internal />
The `Session` entity is used to store the user's session information. It is used to keep the user logged in between page refreshes.
```wasp
entity Session {=psl
id String @id @unique
expiresAt DateTime
userId String
auth Auth @relation(references: [id], fields: [userId], onDelete: Cascade)
@@index([userId])
psl=}
```
The `Session` fields:
- `id` is a unique identifier of the `Session` entity.
- `expiresAt` is the date when the session expires.
- `userId` is a foreign key to the `Auth` entity.
- It is used to connect the `Session` entity with the `Auth` entity.
- `auth` is a relation to the `Auth` entity.
## Custom Signup Action
Let's take a look at how you can use the `Auth` and `AuthIdentity` entities to create custom login and signup actions. For example, you might want to create a custom signup action that creates a user in your app and also creates a user in a third-party service.
:::info Custom Signup Examples
In the [Email](./email#creating-a-custom-sign-up-action) section of the docs we give you an example for custom email signup and in the [Username & password](./username-and-pass#2-creating-your-custom-sign-up-action) section of the docs we give you an example for custom username & password signup.
:::
Below is a simplified version of a custom signup action which you probably wouldn't use in your app but it shows you how you can use the `Auth` and `AuthIdentity` entities to create a custom signup action.
<Tabs groupId="js-ts">
<TabItem value="js" label="JavaScript">
```wasp title="main.wasp"
// ...
action customSignup {
fn: import { signup } from "@src/auth/signup.js",
entities: [User]
}
```
```js title="src/auth/signup.js"
import {
createProviderId,
sanitizeAndSerializeProviderData,
createUser,
} from 'wasp/server/auth'
export const signup = async (args, { entities: { User } }) => {
try {
// Provider ID is a combination of the provider name and the provider user ID
// And it is used to uniquely identify the user in your app
const providerId = createProviderId('username', args.username)
// sanitizeAndSerializeProviderData hashes the password and returns a JSON string
const providerData = await sanitizeAndSerializeProviderData({
hashedPassword: args.password,
})
await createUser(
providerId,
providerData,
// Any additional data you want to store on the User entity
{}
)
// This is equivalent to:
// await User.create({
// data: {
// auth: {
// create: {
// identities: {
// create: {
// providerName: 'username',
// providerUserId: args.username
// providerData,
// },
// },
// }
// },
// }
// })
} catch (e) {
return {
success: false,
message: e.message,
}
}
// Your custom code after sign-up.
// ...
return {
success: true,
message: 'User created successfully',
}
}
```
</TabItem>
<TabItem value="ts" label="TypeScript">
```wasp title="main.wasp"
// ...
action customSignup {
fn: import { signup } from "@src/auth/signup.js",
entities: [User]
}
```
```ts title="src/auth/signup.ts"
import {
createProviderId,
sanitizeAndSerializeProviderData,
createUser,
} from 'wasp/server/auth'
import type { CustomSignup } from 'wasp/server/operations'
type CustomSignupInput = {
username: string
password: string
}
type CustomSignupOutput = {
success: boolean
message: string
}
export const signup: CustomSignup<
CustomSignupInput,
CustomSignupOutput
> = async (args, { entities: { User } }) => {
try {
// Provider ID is a combination of the provider name and the provider user ID
// And it is used to uniquely identify the user in your app
const providerId = createProviderId('username', args.username)
// sanitizeAndSerializeProviderData hashes the password and returns a JSON string
const providerData = await sanitizeAndSerializeProviderData<'username'>({
hashedPassword: args.password,
})
await createUser(
providerId,
providerData,
// Any additional data you want to store on the User entity
{}
)
// This is equivalent to:
// await User.create({
// data: {
// auth: {
// create: {
// identities: {
// create: {
// providerName: 'username',
// providerUserId: args.username
// providerData,
// },
// },
// }
// },
// }
// })
} catch (e) {
return {
success: false,
message: e.message,
}
}
// Your custom code after sign-up.
// ...
return {
success: true,
message: 'User created successfully',
}
}
```
</TabItem>
</Tabs>
You can use whichever method suits your needs better: either the `createUser` function or Prisma's `User.create` method. The `createUser` function is a bit more convenient to use because it hides some of the complexity. On the other hand, the `User.create` method gives you more control over the data that is stored in the `Auth` and `AuthIdentity` entities.