|
1
|
export const metadata = { |
|
2
|
title: `User Creation Flows`, |
|
3
|
} |
|
4
|
|
|
5
|
# {metadata.title} |
|
6
|
|
|
7
|
In this document, learn the different ways to create a user using the User Module. |
|
8
|
|
|
9
|
<Note title="Looking for no-code docs?"> |
|
10
|
|
|
11
|
Refer to this [Medusa Admin User Guide](!user-guide!/settings/users) to learn how to manage users using the dashboard. |
|
12
|
|
|
13
|
</Note> |
|
14
|
|
|
15
|
## Straightforward User Creation |
|
16
|
|
|
17
|
To create a user, use the [createUsers method of the User Module’s main service](/references/user/createUsers): |
|
18
|
|
|
19
|
```ts |
|
20
|
const user = await userModuleService.createUsers({ |
|
21
|
email: "user@example.com", |
|
22
|
}) |
|
23
|
``` |
|
24
|
|
|
25
|
You can pair this with the Auth Module to allow the user to authenticate, as explained in a [later section](#create-identity-with-the-auth-module). |
|
26
|
|
|
27
|
--- |
|
28
|
|
|
29
|
## Invite Users |
|
30
|
|
|
31
|
To create a user, you can create an invite for them using the [createInvites method](/references/user/createInvites) of the User Module's main service: |
|
32
|
|
|
33
|
```ts |
|
34
|
const invite = await userModuleService.createInvites({ |
|
35
|
email: "user@example.com", |
|
36
|
}) |
|
37
|
``` |
|
38
|
|
|
39
|
Later, you can accept the invite and create a new user for them: |
|
40
|
|
|
41
|
```ts |
|
42
|
const invite = |
|
43
|
await userModuleService.validateInviteToken("secret_123") |
|
44
|
|
|
45
|
await userModuleService.updateInvites({ |
|
46
|
id: invite.id, |
|
47
|
accepted: true, |
|
48
|
}) |
|
49
|
|
|
50
|
const user = await userModuleService.createUsers({ |
|
51
|
email: invite.email, |
|
52
|
}) |
|
53
|
``` |
|
54
|
|
|
55
|
### Invite Expiry |
|
56
|
|
|
57
|
An invite has an expiry date. You can renew the expiry date and refresh the token using the [refreshInviteTokens method](/references/user/refreshInviteTokens): |
|
58
|
|
|
59
|
```ts |
|
60
|
await userModuleService.refreshInviteTokens(["invite_123"]) |
|
61
|
``` |
|
62
|
|
|
63
|
--- |
|
64
|
|
|
65
|
## Create Identity with the Auth Module |
|
66
|
|
|
67
|
By combining the User and Auth Modules, you can use the Auth Module for authenticating users, and the User Module to manage those users. |
|
68
|
|
|
69
|
So, when a user is authenticated, and you receive the `AuthIdentity` object, you can use it to create a user if it doesn’t exist: |
|
70
|
|
|
71
|
```ts |
|
72
|
const { success, authIdentity } = |
|
73
|
await authModuleService.authenticate("emailpass", { |
|
74
|
// ... |
|
75
|
}) |
|
76
|
|
|
77
|
const [, count] = await userModuleService.listAndCountUsers({ |
|
78
|
email: authIdentity.entity_id, |
|
79
|
}) |
|
80
|
|
|
81
|
if (!count) { |
|
82
|
const user = await userModuleService.createUsers({ |
|
83
|
email: authIdentity.entity_id, |
|
84
|
}) |
|
85
|
} |
|
86
|
``` |