|
1
|
--- |
|
2
|
sidebar_label: "Phone Authentication" |
|
3
|
tags: |
|
4
|
- name: auth |
|
5
|
label: "Implement Phone Authentication" |
|
6
|
- name: customer |
|
7
|
label: "Implement Phone Authentication" |
|
8
|
- server |
|
9
|
- tutorial |
|
10
|
products: |
|
11
|
- customer |
|
12
|
- auth |
|
13
|
--- |
|
14
|
|
|
15
|
import { Github, PlaySolid } from "@medusajs/icons" |
|
16
|
import { Prerequisites, WorkflowDiagram, CardList } from "docs-ui" |
|
17
|
|
|
18
|
export const metadata = { |
|
19
|
title: `Implement Phone Authentication and Integrate Twilio SMS`, |
|
20
|
} |
|
21
|
|
|
22
|
# {metadata.title} |
|
23
|
|
|
24
|
In this tutorial, you will learn how to implement phone number authentication in your Medusa application. |
|
25
|
|
|
26
|
When you install a Medusa application, you get a fully-fledged commerce platform with a Framework for customization. The Medusa application's commerce features are built around [Commerce Modules](../../../commerce-modules/page.mdx), which are available out-of-the-box. These features include authentication with custom providers and for custom user or actor types. |
|
27
|
|
|
28
|
In this tutorial, you'll learn how to implement a custom authentication provider that allows customers to log in with their phone number. You'll also integrate [Twilio](https://www.twilio.com/en-us/messaging/channels/sms) to send SMS messages to those customers with the one-time password (OTP) for authentication. |
|
29
|
|
|
30
|
<Note> |
|
31
|
|
|
32
|
Twilio is just one option to deliver the OTP to the customer. You can integrate a different SMS provider or use a different method to send OTPs. |
|
33
|
|
|
34
|
</Note> |
|
35
|
|
|
36
|
## Summary |
|
37
|
|
|
38
|
By following this tutorial, you will learn how to: |
|
39
|
|
|
40
|
- Install and set up Medusa. |
|
41
|
- Implement a custom phone authentication provider. |
|
42
|
- Integrate Twilio to send OTPs by SMS. |
|
43
|
- Customize the Next.js Starter Storefront to allow customers to log in with their phone numbers. |
|
44
|
|
|
45
|
You can follow this tutorial whether you're new to Medusa or an advanced Medusa developer. |
|
46
|
|
|
47
|
 |
|
48
|
|
|
49
|
<Note> |
|
50
|
|
|
51
|
While this tutorial focuses on supporting phone authentication for customers, you can use the authentication provider for any actor type, such as admin user or vendor. [At the end of this tutorial](#next-steps), you'll learn how to authenticate other actor types. |
|
52
|
|
|
53
|
</Note> |
|
54
|
|
|
55
|
<CardList items={[ |
|
56
|
{ |
|
57
|
href: "https://github.com/medusajs/examples/tree/main/phone-auth", |
|
58
|
title: "Phone Authentication Repository", |
|
59
|
text: "Find the full code for this guide in this repository.", |
|
60
|
icon: Github, |
|
61
|
}, |
|
62
|
{ |
|
63
|
href: "https://res.cloudinary.com/dza7lstvk/raw/upload/v1747745832/OpenApi/Phone_Auth_g4xsqv.yaml", |
|
64
|
title: "OpenApi Specs for Postman", |
|
65
|
text: "Import this OpenApi Specs file into tools like Postman.", |
|
66
|
icon: PlaySolid, |
|
67
|
}, |
|
68
|
]} /> |
|
69
|
|
|
70
|
--- |
|
71
|
|
|
72
|
## Step 1: Install a Medusa Application |
|
73
|
|
|
74
|
<Prerequisites items={[ |
|
75
|
{ |
|
76
|
text: "Node.js v20.19.0+ or v22.12.0+", |
|
77
|
link: "https://nodejs.org/en/download" |
|
78
|
}, |
|
79
|
{ |
|
80
|
text: "Git CLI tool", |
|
81
|
link: "https://git-scm.com/downloads" |
|
82
|
}, |
|
83
|
{ |
|
84
|
text: "PostgreSQL", |
|
85
|
link: "https://www.postgresql.org/download/" |
|
86
|
} |
|
87
|
]} /> |
|
88
|
|
|
89
|
Start by installing the Medusa application on your machine with the following command: |
|
90
|
|
|
91
|
```bash npx2yarnExec |
|
92
|
npx create-medusa-app@latest |
|
93
|
``` |
|
94
|
|
|
95
|
You'll first be asked for the project's name. Then, when asked whether you want to install the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx), choose Yes. |
|
96
|
|
|
97
|
Afterward, the installation process will start, which will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory, and the Next.js Starter Storefront is installed in the `apps/storefront` directory. |
|
98
|
|
|
99
|
Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterward, you can log in with the new user and explore the dashboard. |
|
100
|
|
|
101
|
<Note title="Ran into Errors?"> |
|
102
|
|
|
103
|
Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help. |
|
104
|
|
|
105
|
</Note> |
|
106
|
|
|
107
|
<Note> |
|
108
|
|
|
109
|
In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project. |
|
110
|
|
|
111
|
</Note> |
|
112
|
|
|
113
|
--- |
|
114
|
|
|
115
|
## Step 2: Implement Phone Authentication Module Provider |
|
116
|
|
|
117
|
In Medusa, you integrate custom authentication providers by creating an [Authentication Module Provider](../../../commerce-modules/auth/auth-providers/page.mdx). Then, you can use that provider to authenticate users using custom logic. |
|
118
|
|
|
119
|
In this step, you'll create a Phone Authentication Module Provider that allows users to log in with their phone numbers and an OTP. Later, you'll integrate Twilio to send the OTPs to the users, and customize the storefront to allow customers to log in with their phone numbers. |
|
120
|
|
|
121
|
<Note title="Good to Know"> |
|
122
|
|
|
123
|
An Authentication Module Provider doesn't need to handle storing and managing specific user details, such as creating customers or admin users. Instead, it only focuses on the logic of authenticating a type of user using custom logic or integration. You can learn more in the [Auth Module](../../../commerce-modules/auth/page.mdx) documentation. |
|
124
|
|
|
125
|
</Note> |
|
126
|
|
|
127
|
### Prerequisite: Install jsonwebtoken |
|
128
|
|
|
129
|
In the Phone Authentication Module Provider, you'll use the `jsonwebtoken` package to sign and verify the OTPs. |
|
130
|
|
|
131
|
To install the package, run the following command in the Medusa application directory: |
|
132
|
|
|
133
|
```bash npm2yarn |
|
134
|
npm install jsonwebtoken |
|
135
|
npm install @types/jsonwebtoken --save-dev |
|
136
|
``` |
|
137
|
|
|
138
|
### a. Create Module Directory |
|
139
|
|
|
140
|
Modules are created under the `src/modules` directory. So, start by creating the directory `src/modules/phone-auth`. |
|
141
|
|
|
142
|
### b. Create Auth Module Provider Service |
|
143
|
|
|
144
|
A module has a service that contains its logic. For Authentication Module Providers, the service implements the logic to authenticate users. |
|
145
|
|
|
146
|
To create the service of the Phone Authentication Module Provider, create the file `src/modules/phone-auth/service.ts` with the following content: |
|
147
|
|
|
148
|
export const phoneAuthServiceHighlights = [ |
|
149
|
["10", "logger", "Resolve Logger class to log debug messages."], |
|
150
|
["11", "event_bus", "Resolve Event Module's service to emit events."], |
|
151
|
["15", "jwtSecret", "JWT secret to sign and verify OTPs."], |
|
152
|
["19", "DISPLAY_NAME", "Human-readable name for the provider."], |
|
153
|
["20", "identifier", "Unique identifier for the provider."], |
|
154
|
] |
|
155
|
|
|
156
|
```ts title="src/modules/phone-auth/service.ts" highlights={phoneAuthServiceHighlights} |
|
157
|
import { |
|
158
|
AbstractAuthModuleProvider, |
|
159
|
AbstractEventBusModuleService, |
|
160
|
} from "@medusajs/framework/utils" |
|
161
|
import { |
|
162
|
Logger, |
|
163
|
} from "@medusajs/framework/types" |
|
164
|
|
|
165
|
type InjectedDependencies = { |
|
166
|
logger: Logger |
|
167
|
event_bus: AbstractEventBusModuleService |
|
168
|
} |
|
169
|
|
|
170
|
type Options = { |
|
171
|
jwtSecret: string |
|
172
|
} |
|
173
|
|
|
174
|
class PhoneAuthService extends AbstractAuthModuleProvider { |
|
175
|
static DISPLAY_NAME = "Phone Auth" |
|
176
|
static identifier = "phone-auth" |
|
177
|
private options: Options |
|
178
|
private logger: Logger |
|
179
|
private event_bus: AbstractEventBusModuleService |
|
180
|
|
|
181
|
constructor(container: InjectedDependencies, options: Options) { |
|
182
|
// @ts-ignore |
|
183
|
super(...arguments) |
|
184
|
|
|
185
|
this.options = options |
|
186
|
this.logger = container.logger |
|
187
|
this.event_bus = container.event_bus |
|
188
|
} |
|
189
|
} |
|
190
|
|
|
191
|
export default PhoneAuthService |
|
192
|
``` |
|
193
|
|
|
194
|
An Authentication Module Provider's service must extend the `AbstractAuthModuleProvider` class. You'll get a type error about implementing the abstract methods of that class, which you'll add in the next steps. |
|
195
|
|
|
196
|
An Authentication Module Provider must also have the following static properties: |
|
197
|
|
|
198
|
- `identifier`: A unique identifier for the provider. |
|
199
|
- `DISPLAY_NAME`: A human-readable name for the provider. This name is used for display purposes. |
|
200
|
|
|
201
|
A module provider's constructor receives two parameters: |
|
202
|
|
|
203
|
- `container`: The [module's container](!docs!/learn/fundamentals/modules/container) that contains Framework resources available to the module. You access the following resources: |
|
204
|
- `logger`: A [Logger](!docs!/learn/debugging-and-testing/logging) class to log debug messages. |
|
205
|
- `event_bus`: The [Event Module](../../../infrastructure-modules/event/page.mdx)'s service to emit events. |
|
206
|
- `options`: Options that are passed to the module provider when it's registered in Medusa's configurations. You define the following option: |
|
207
|
- `jwtSecret`: A secret used to sign and verify the OTPs. |
|
208
|
|
|
209
|
<Note> |
|
210
|
|
|
211
|
You'll learn how to set this option when you [add the module provider to Medusa's configurations](#h-add-module-provider-to-medusas-configurations). |
|
212
|
|
|
213
|
</Note> |
|
214
|
|
|
215
|
In the constructor, you set the class's properties to the injected dependencies and options. |
|
216
|
|
|
217
|
In the next sections, you'll implement the methods of the `AbstractAuthModuleProvider` class. |
|
218
|
|
|
219
|
<Note> |
|
220
|
|
|
221
|
Refer to the [Create Auth Module Provider](/references/auth/provider) guide for detailed information about the methods. |
|
222
|
|
|
223
|
</Note> |
|
224
|
|
|
225
|
### c. Implement validateOptions Method |
|
226
|
|
|
227
|
The `validateOptions` method is used to validate the options passed to the module provider. If the method throws an error, the Medusa application won't start. |
|
228
|
|
|
229
|
So, add the `validateOptions` method to the `PhoneAuthService` class: |
|
230
|
|
|
231
|
```ts title="src/modules/phone-auth/service.ts" |
|
232
|
// other imports... |
|
233
|
import { |
|
234
|
MedusaError, |
|
235
|
} from "@medusajs/framework/utils" |
|
236
|
|
|
237
|
class PhoneAuthService extends AbstractAuthModuleProvider { |
|
238
|
// ... |
|
239
|
static validateOptions(options: Record<any, any>): void | never { |
|
240
|
if (!options.jwtSecret) { |
|
241
|
throw new MedusaError( |
|
242
|
MedusaError.Types.INVALID_DATA, |
|
243
|
"JWT secret is required" |
|
244
|
) |
|
245
|
} |
|
246
|
} |
|
247
|
} |
|
248
|
``` |
|
249
|
|
|
250
|
The `validateOptions` method receives the options passed to the module provider as a parameter. |
|
251
|
|
|
252
|
In the method, you throw an error if the `jwtSecret` option is not set. |
|
253
|
|
|
254
|
### d. Implement register Method |
|
255
|
|
|
256
|
When a customer (or another actor type) registers in your application, they must also have an [auth identity](../../../commerce-modules/auth/auth-identity-and-actor-types/page.mdx) that allows them to login. |
|
257
|
|
|
258
|
The `register` method of an auth provider uses custom logic to create the auth identity for the actor type (such as customer). In the method, you can perform custom validation and specify the custom authentication details to store for the user's auth identity. |
|
259
|
|
|
260
|
Medusa uses the `register` method to create an auth identity that will be associated with the customer when they register. You can learn more in the [Authentication Flows](../../../commerce-modules/auth/auth-flows/page.mdx) documentation. |
|
261
|
|
|
262
|
 |
|
263
|
|
|
264
|
So, add the `register` method to the `PhoneAuthService` class: |
|
265
|
|
|
266
|
export const registerHighlights = [ |
|
267
|
["14", "phone", "Extract phone from request body."], |
|
268
|
["24", "retrieve", "Check if user with phone number already exists."], |
|
269
|
["33", "create", "Create a new auth identity for the user."], |
|
270
|
] |
|
271
|
|
|
272
|
```ts title="src/modules/phone-auth/service.ts" highlights={registerHighlights} |
|
273
|
// other imports... |
|
274
|
import { |
|
275
|
AuthenticationInput, |
|
276
|
AuthIdentityProviderService, |
|
277
|
AuthenticationResponse, |
|
278
|
} from "@medusajs/framework/types" |
|
279
|
|
|
280
|
class PhoneAuthService extends AbstractAuthModuleProvider { |
|
281
|
// ... |
|
282
|
async register( |
|
283
|
data: AuthenticationInput, |
|
284
|
authIdentityProviderService: AuthIdentityProviderService |
|
285
|
): Promise<AuthenticationResponse> { |
|
286
|
const { phone } = data.body || {} |
|
287
|
|
|
288
|
if (!phone) { |
|
289
|
return { |
|
290
|
success: false, |
|
291
|
error: "Phone number is required", |
|
292
|
} |
|
293
|
} |
|
294
|
|
|
295
|
try { |
|
296
|
await authIdentityProviderService.retrieve({ |
|
297
|
entity_id: phone, |
|
298
|
}) |
|
299
|
|
|
300
|
return { |
|
301
|
success: false, |
|
302
|
error: "User with phone number already exists", |
|
303
|
} |
|
304
|
} catch (error) { |
|
305
|
const user = await authIdentityProviderService.create({ |
|
306
|
entity_id: phone, |
|
307
|
}) |
|
308
|
|
|
309
|
return { |
|
310
|
success: true, |
|
311
|
authIdentity: user, |
|
312
|
} |
|
313
|
} |
|
314
|
} |
|
315
|
} |
|
316
|
``` |
|
317
|
|
|
318
|
#### Parameters |
|
319
|
|
|
320
|
The `register` method receives an object parameter with the following properties: |
|
321
|
|
|
322
|
- `data`: An object containing properties like `body` that holds request-body parameters. Clients will pass relevant authentication data, such as the user's phone number, in the request body. |
|
323
|
- `authIdentityProviderService`: A service injected by the [Auth Module](../../../commerce-modules/auth/page.mdx) that allows you to manage auth identities. |
|
324
|
|
|
325
|
<Note> |
|
326
|
|
|
327
|
The method receives other parameters, which you can find in the [Create Auth Module Provider](/references/auth/provider#register) guide. |
|
328
|
|
|
329
|
</Note> |
|
330
|
|
|
331
|
#### Method Logic |
|
332
|
|
|
333
|
In the method, you extract the `phone` property from the request body, and return an error if it's not provided. You also return an error if another user is using the same phone number. |
|
334
|
|
|
335
|
Otherwise, you create a new auth identity for the user. You set the phone number as the `entity_id` of the auth identity, which is a unique identifier. |
|
336
|
|
|
337
|
#### Return Value |
|
338
|
|
|
339
|
Finally, you return an object with the following properties: |
|
340
|
|
|
341
|
- `success`: A boolean indicating whether the registration was successful. |
|
342
|
- `authIdentity`: The created auth identity of the user. This property is only set if the registration was successful. |
|
343
|
- `error`: An error message if the registration failed. |
|
344
|
|
|
345
|
### e. Implement authenticate Method |
|
346
|
|
|
347
|
When a customer (or another actor type) logs in, the `authenticate` method of an auth provider is called. This method uses custom logic to authenticate the user. |
|
348
|
|
|
349
|
Authentication providers may implement one of the following flows: |
|
350
|
|
|
351
|
- Direct authentication, where the user is authenticated using this method only. For example, authenticating with an email and password. |
|
352
|
- Authentication with callback verification, where the user is authenticated using this method and then a callback is used to verify additional information. |
|
353
|
|
|
354
|
For the Phone Authentication Module Provider, you'll implement the second flow. The user will first be authenticated using the `authenticate` method to make sure the user exists and generate an OTP. Then, they need to supply the OTP to verify their identity. |
|
355
|
|
|
356
|
 |
|
357
|
|
|
358
|
So, add the `authenticate` method to the `PhoneAuthService` class: |
|
359
|
|
|
360
|
export const authenticateHighlights = [ |
|
361
|
["13", "phone", "Extract from request body."], |
|
362
|
["23", "retrieve", "Check that the user exists."], |
|
363
|
["33", "generateOTP", "Generate a 6-digit OTP."], |
|
364
|
["35", "update", "Store OTP in the provider metadata."], |
|
365
|
["41", "emit", "Emit an event with the generated OTP."], |
|
366
|
["51", "location", "Indicate that more actions are required."], |
|
367
|
["55", "generateOTP", "A method to generate the OTP"], |
|
368
|
["60", "logger", "Log the generated OTP for debugging."], |
|
369
|
["63", "expiresIn", "Expire the OTP in 60 seconds."] |
|
370
|
] |
|
371
|
|
|
372
|
```ts title="src/modules/phone-auth/service.ts" highlights={authenticateHighlights} |
|
373
|
// other imports... |
|
374
|
import { |
|
375
|
AuthIdentityDTO, |
|
376
|
} from "@medusajs/framework/types" |
|
377
|
import jwt from "jsonwebtoken" |
|
378
|
|
|
379
|
class PhoneAuthService extends AbstractAuthModuleProvider { |
|
380
|
// ... |
|
381
|
async authenticate( |
|
382
|
data: AuthenticationInput, |
|
383
|
authIdentityProviderService: AuthIdentityProviderService |
|
384
|
): Promise<AuthenticationResponse> { |
|
385
|
const { phone } = data.body || {} |
|
386
|
|
|
387
|
if (!phone) { |
|
388
|
return { |
|
389
|
success: false, |
|
390
|
error: "Phone number is required", |
|
391
|
} |
|
392
|
} |
|
393
|
|
|
394
|
try { |
|
395
|
await authIdentityProviderService.retrieve({ |
|
396
|
entity_id: phone, |
|
397
|
}) |
|
398
|
} catch (error) { |
|
399
|
return { |
|
400
|
success: false, |
|
401
|
error: "User with phone number does not exist", |
|
402
|
} |
|
403
|
} |
|
404
|
|
|
405
|
const { hashedOTP, otp } = await this.generateOTP() |
|
406
|
|
|
407
|
await authIdentityProviderService.update(phone, { |
|
408
|
provider_metadata: { |
|
409
|
otp: hashedOTP, |
|
410
|
}, |
|
411
|
}) |
|
412
|
|
|
413
|
await this.event_bus.emit({ |
|
414
|
name: "phone-auth.otp.generated", |
|
415
|
data: { |
|
416
|
otp, |
|
417
|
phone, |
|
418
|
}, |
|
419
|
}, {}) |
|
420
|
|
|
421
|
return { |
|
422
|
success: true, |
|
423
|
location: "otp", |
|
424
|
} |
|
425
|
} |
|
426
|
|
|
427
|
async generateOTP(): Promise<{ hashedOTP: string, otp: string }> { |
|
428
|
// Generate a 6-digit OTP |
|
429
|
const otp = Math.floor(100000 + Math.random() * 900000).toString() |
|
430
|
|
|
431
|
// for debug |
|
432
|
this.logger.info(`Generated OTP: ${otp}`) |
|
433
|
|
|
434
|
const hashedOTP = jwt.sign({ otp }, this.options.jwtSecret, { |
|
435
|
expiresIn: "60s", |
|
436
|
}) |
|
437
|
|
|
438
|
return { hashedOTP, otp } |
|
439
|
} |
|
440
|
} |
|
441
|
``` |
|
442
|
|
|
443
|
You add two methods: the `authenticate` method, and a helper `generateOTP` method. |
|
444
|
|
|
445
|
#### authenticate Parameters |
|
446
|
|
|
447
|
The `authenticate` method receives an object parameter with the following properties: |
|
448
|
|
|
449
|
- `data`: An object containing properties like `body` that holds request-body parameters. Clients will pass relevant authentication data, such as the user's phone number, in the request body. |
|
450
|
- `authIdentityProviderService`: A service injected by the [Auth Module](../../../commerce-modules/auth/page.mdx) that allows you to manage auth identities. |
|
451
|
|
|
452
|
<Note> |
|
453
|
|
|
454
|
The method receives other parameters, which you can find in the [Create Auth Module Provider](/references/auth/provider#authenticate) guide. |
|
455
|
|
|
456
|
</Note> |
|
457
|
|
|
458
|
#### authenticate Logic |
|
459
|
|
|
460
|
In the method, you return an error if the `phone` property is not provided in the request body, or if a user with that phone number doesn't exist. |
|
461
|
|
|
462
|
Next, you generate a 6-digit OTP using the `generateOTP` method. Notice that you currently log the OTP for debugging purposes. You can remove this line later once you integrate Twilio. |
|
463
|
|
|
464
|
The OTP is hashed and stored in the `provider_metadata` property of the user's auth identity. The `provider_metadata` property is a JSON object that stores additional information about the auth identity. |
|
465
|
|
|
466
|
Then, you emit an event with the generated OTP and the user's phone number. This allows you later to handle the event and send the OTP to the user using services like Twilio. |
|
467
|
|
|
468
|
#### authenticate Return Value |
|
469
|
|
|
470
|
Finally, you return an object with the following properties: |
|
471
|
|
|
472
|
- `success`: A boolean indicating whether the authentication was successful. |
|
473
|
- `location`: A string indicating a URL to perform additional actions in. In this case, you set the location to `otp`, indicating that the user should verify with the OTP. |
|
474
|
- `error`: An error message if the authentication failed. |
|
475
|
|
|
476
|
### f. Implement validateCallback Method |
|
477
|
|
|
478
|
When an authentication provider requires a callback to verify the user, the Medusa application calls the `validateCallback` method. |
|
479
|
|
|
480
|
You can use this method to verify the OTP that the user entered. If valid, you return the logged in user, and the Medusa application will return a JWT token that the user can use to authenticate in the application. |
|
481
|
|
|
482
|
 |
|
483
|
|
|
484
|
So, add the `validateCallback` method to the `PhoneAuthService` class: |
|
485
|
|
|
486
|
export const validateCallbackHighlights = [ |
|
487
|
["9", "phone", "Extract phone from request query."], |
|
488
|
["9", "otp", "Extract OTP from request query."], |
|
489
|
["18", "retrieve", "Check that the user exists."], |
|
490
|
["39", "verify", "Verify that the OTP is correct and hasn't expired."], |
|
491
|
["57", "update", "Remove OTP from provider metadata."], |
|
492
|
] |
|
493
|
|
|
494
|
```ts title="src/modules/phone-auth/service.ts" highlights={validateCallbackHighlights} |
|
495
|
import { MedusaError } from "@medusajs/framework/utils" |
|
496
|
|
|
497
|
class PhoneAuthService extends AbstractAuthModuleProvider { |
|
498
|
// ... |
|
499
|
async validateCallback( |
|
500
|
data: AuthenticationInput, |
|
501
|
authIdentityProviderService: AuthIdentityProviderService |
|
502
|
): Promise<AuthenticationResponse> { |
|
503
|
const { phone, otp } = data.query || {} |
|
504
|
|
|
505
|
if (!phone || !otp) { |
|
506
|
return { |
|
507
|
success: false, |
|
508
|
error: "Phone number and OTP are required", |
|
509
|
} |
|
510
|
} |
|
511
|
|
|
512
|
const user = await authIdentityProviderService.retrieve({ |
|
513
|
entity_id: phone, |
|
514
|
}) |
|
515
|
|
|
516
|
if (!user) { |
|
517
|
return { |
|
518
|
success: false, |
|
519
|
error: "User with phone number does not exist", |
|
520
|
} |
|
521
|
} |
|
522
|
|
|
523
|
// verify that OTP is correct |
|
524
|
const userProvider = user.provider_identities?.find((provider) => provider.provider === this.identifier) |
|
525
|
if (!userProvider || !userProvider.provider_metadata?.otp) { |
|
526
|
return { |
|
527
|
success: false, |
|
528
|
error: "User with phone number does not have a phone auth provider", |
|
529
|
} |
|
530
|
} |
|
531
|
|
|
532
|
try { |
|
533
|
const decodedOTP = jwt.verify( |
|
534
|
userProvider.provider_metadata.otp as string, |
|
535
|
this.options.jwtSecret |
|
536
|
) as { otp: string } |
|
537
|
|
|
538
|
if (decodedOTP.otp !== otp) { |
|
539
|
throw new MedusaError( |
|
540
|
MedusaError.Types.UNAUTHORIZED, |
|
541
|
"Invalid OTP" |
|
542
|
) |
|
543
|
} |
|
544
|
} catch (error) { |
|
545
|
return { |
|
546
|
success: false, |
|
547
|
error: error.message || "Invalid OTP", |
|
548
|
} |
|
549
|
} |
|
550
|
|
|
551
|
const updatedUser = await authIdentityProviderService.update(phone, { |
|
552
|
provider_metadata: { |
|
553
|
otp: null, |
|
554
|
}, |
|
555
|
}) |
|
556
|
|
|
557
|
return { |
|
558
|
success: true, |
|
559
|
authIdentity: updatedUser, |
|
560
|
} |
|
561
|
} |
|
562
|
} |
|
563
|
``` |
|
564
|
|
|
565
|
#### Parameters |
|
566
|
|
|
567
|
The `validateCallback` method receives an object parameter with the following properties: |
|
568
|
|
|
569
|
- `data`: An object containing properties like `query` that holds query parameters. Clients will pass relevant authentication data, such as the user's phone number and OTP, in the request query. |
|
570
|
- `authIdentityProviderService`: A service injected by the [Auth Module](../../../commerce-modules/auth/page.mdx) that allows you to manage auth identities. |
|
571
|
|
|
572
|
<Note> |
|
573
|
|
|
574
|
The method receives other parameters, which you can find in the [Create Auth Module Provider](/references/auth/provider#validatecallback) guide. |
|
575
|
|
|
576
|
</Note> |
|
577
|
|
|
578
|
#### Method Logic |
|
579
|
|
|
580
|
In the method, you return an error if the phone and otp aren't provided in the request query, or if a user with that phone number doesn't exist. |
|
581
|
|
|
582
|
Next, you verify that the OTP provided by the user is correct. You retrieve the hashed OTP from the `provider_metadata` property of the user's auth identity. If the OTP is not valid, you return an error. |
|
583
|
|
|
584
|
<Note> |
|
585
|
|
|
586
|
Since you set the hash expiration to 60 seconds, the OTP will be valid for 60 seconds. After that, the user will need to request a new OTP. |
|
587
|
|
|
588
|
</Note> |
|
589
|
|
|
590
|
After that, you update the user's auth identity to remove the OTP from the `provider_metadata` property. |
|
591
|
|
|
592
|
#### Return Value |
|
593
|
|
|
594
|
Finally, you return an object with the following properties: |
|
595
|
|
|
596
|
- `success`: A boolean indicating whether the authentication was successful. |
|
597
|
- `authIdentity`: The user's auth identity. This property is only set if the authentication was successful. |
|
598
|
- `error`: An error message if the authentication failed. |
|
599
|
|
|
600
|
### g. Export Module Definition |
|
601
|
|
|
602
|
You've now finished implementing the necessary methods for the Phone Authentication Module Provider. |
|
603
|
|
|
604
|
The final piece to a module is its definition, which you export in an `index.ts` file at the module's root directory. This definition tells Medusa the name of the module, its service, and optionally its loaders. |
|
605
|
|
|
606
|
To create the module's definition, create the file `src/modules/phone-auth/index.ts` with the following content: |
|
607
|
|
|
608
|
```ts title="src/modules/phone-auth/index.ts" |
|
609
|
import PhoneAuthService from "./service" |
|
610
|
import { |
|
611
|
ModuleProvider, |
|
612
|
Modules, |
|
613
|
} from "@medusajs/framework/utils" |
|
614
|
|
|
615
|
export default ModuleProvider(Modules.AUTH, { |
|
616
|
services: [PhoneAuthService], |
|
617
|
}) |
|
618
|
``` |
|
619
|
|
|
620
|
You use `ModuleProvider` from the Modules SDK to create the module provider's definition. It accepts two parameters: |
|
621
|
|
|
622
|
1. The name of the module that this provider belongs to, which is `Modules.AUTH` in this case. |
|
623
|
2. An object with a required property `services` indicating the module provider's services. Each of these services will be registered as authentication providers in Medusa. |
|
624
|
|
|
625
|
### h. Add Module Provider to Medusa's Configurations |
|
626
|
|
|
627
|
Once you finish building the module, add it to Medusa's configurations to start using it. |
|
628
|
|
|
629
|
In `medusa-config.ts`, add a `modules` property: |
|
630
|
|
|
631
|
```ts title="medusa-config.ts" |
|
632
|
// other imports... |
|
633
|
import { Modules, ContainerRegistrationKeys } from "@medusajs/framework/utils" |
|
634
|
|
|
635
|
module.exports = defineConfig({ |
|
636
|
// ... |
|
637
|
modules: [ |
|
638
|
{ |
|
639
|
resolve: "@medusajs/medusa/auth", |
|
640
|
dependencies: [ |
|
641
|
Modules.CACHE, |
|
642
|
ContainerRegistrationKeys.LOGGER, |
|
643
|
Modules.EVENT_BUS, |
|
644
|
], |
|
645
|
options: { |
|
646
|
providers: [ |
|
647
|
// default provider |
|
648
|
{ |
|
649
|
resolve: "@medusajs/medusa/auth-emailpass", |
|
650
|
id: "emailpass", |
|
651
|
}, |
|
652
|
{ |
|
653
|
resolve: "./src/modules/phone-auth", |
|
654
|
id: "phone-auth", |
|
655
|
options: { |
|
656
|
jwtSecret: process.env.PHONE_AUTH_JWT_SECRET || "supersecret", |
|
657
|
}, |
|
658
|
}, |
|
659
|
], |
|
660
|
}, |
|
661
|
}, |
|
662
|
], |
|
663
|
}) |
|
664
|
``` |
|
665
|
|
|
666
|
To pass an Auth Module Provider to the Auth Module, you add the `modules` property to the Medusa configuration and pass the Auth Module in its value. |
|
667
|
|
|
668
|
The Auth Module accepts a `dependencies` option, allowing you to inject dependencies into the containers of the module and its providers. The Auth Module requires passing the [Cache Module](../../../infrastructure-modules/cache/page.mdx) and Logger, but you also inject the `event_bus` dependency to use the Event Module's service in the Phone Authentication Module Provider. |
|
669
|
|
|
670
|
The Auth Module also accepts a `providers` option, which is an array of Auth Module Providers to register. You register the `emailpass` provider, which is registered by default when you don't provide any other providers. |
|
671
|
|
|
672
|
To register the Phone Authentication Module Provider, you add an object to the `providers` array with the following properties: |
|
673
|
|
|
674
|
- `resolve`: The NPM package or path to the module provider. In this case, it's the path to the `src/modules/phone-auth` directory. |
|
675
|
- `id`: The ID of the module provider. The auth provider is then registered with the ID `au_{id}`. |
|
676
|
- `options`: The options to pass to the module provider. These are the options you defined in the `Options` interface of the module provider's service. |
|
677
|
|
|
678
|
### i. Enable Phone Authentication for Customers |
|
679
|
|
|
680
|
By default, customers and admin users can be authenticated using the `emailpass` provider. When you add a new provider, you need to specify which actor types can use it. |
|
681
|
|
|
682
|
In `medusa-config.ts`, add to `projectConfig.http` a new `authMethodsPerActor` property: |
|
683
|
|
|
684
|
export const authMethodsPerActorHighlights = [ |
|
685
|
["8", "customer", "Enable the emailpass and phone-auth providers for customers."], |
|
686
|
] |
|
687
|
|
|
688
|
```ts title="medusa-config.ts" highlights={authMethodsPerActorHighlights} |
|
689
|
module.exports = defineConfig({ |
|
690
|
projectConfig: { |
|
691
|
// ... |
|
692
|
http: { |
|
693
|
// ... |
|
694
|
authMethodsPerActor: { |
|
695
|
user: ["emailpass"], |
|
696
|
customer: ["emailpass", "phone-auth"], |
|
697
|
}, |
|
698
|
}, |
|
699
|
}, |
|
700
|
// ... |
|
701
|
}) |
|
702
|
``` |
|
703
|
|
|
704
|
The `authMethodsPerActor` property is an object whose keys are actor types. The values are arrays of authentication method IDs that can be used for that actor type. |
|
705
|
|
|
706
|
In this case, you enable the `phone-auth` provider for customers. You can also enable it for other actor types, such as admin users or vendors. |
|
707
|
|
|
708
|
### Test Out Phone Authentication |
|
709
|
|
|
710
|
In this section, you'll test out the Phone Authentication Module Provider using Medusa's API routes. You can, instead, test it out later using the [Next.js Starter Storefront](#step-4-use-phone-authentication-in-the-nextjs-starter-storefront). |
|
711
|
|
|
712
|
First, start the Medusa application with the following command: |
|
713
|
|
|
714
|
```bash npm2yarn |
|
715
|
npm run start |
|
716
|
``` |
|
717
|
|
|
718
|
#### Prerequisite: Retrieve Publishable API Key |
|
719
|
|
|
720
|
Before you start testing the authentication provider using the API routes, you need to retrieve your application's publishable API key. This key is necessary to send requests to API routes starting with `/store`. |
|
721
|
|
|
722
|
To retrieve the publishable API key: |
|
723
|
|
|
724
|
1. Open the Medusa Admin dashboard at `http://localhost:9000/admin` and log in. |
|
725
|
2. Go to Settings -> Publishable API Keys. |
|
726
|
3. Click on the API key in the table. |
|
727
|
4. In its details page, click on the API key to copy it. |
|
728
|
|
|
729
|
 |
|
730
|
|
|
731
|
#### a. Retrieve Registration Token |
|
732
|
|
|
733
|
The first step is to retrieve a registration token for a new customer. This token will allow them to register in the application. |
|
734
|
|
|
735
|
To retrieve the registration token, send a `POST` request to `/auth/customer/phone-auth/register`: |
|
736
|
|
|
737
|
```bash |
|
738
|
curl -X POST 'http://localhost:9000/auth/customer/phone-auth/register' \ |
|
739
|
--header 'Content-Type: application/json' \ |
|
740
|
--data '{ |
|
741
|
"phone": "+19077890116" |
|
742
|
}' |
|
743
|
``` |
|
744
|
|
|
745
|
Make sure to replace the phone number with the one you want to use. |
|
746
|
|
|
747
|
This will return a `token` in the response: |
|
748
|
|
|
749
|
```json title="Example Response" |
|
750
|
{ |
|
751
|
"token": "123..." |
|
752
|
} |
|
753
|
``` |
|
754
|
|
|
755
|
#### b. Register Customer |
|
756
|
|
|
757
|
Next, you'll register the customer using the [Register Customer](!api!/store/customers/register-customer) API route. You'll pass the registration token you received in the previous step in the header of this request. |
|
758
|
|
|
759
|
So, send a `POST` request to `/store/customers`: |
|
760
|
|
|
761
|
```bash |
|
762
|
curl -X POST 'http://localhost:9000/store/customers' \ |
|
763
|
--header 'x-publishable-api-key: {publishable_api_key}' \ |
|
764
|
--header 'Content-Type: application/json' \ |
|
765
|
--header 'Authorization: Bearer {reg_token}' \ |
|
766
|
--data-raw '{ |
|
767
|
"email": "+19077890116@gmail.com", |
|
768
|
"phone": "19077890116", |
|
769
|
"first_name": "John", |
|
770
|
"last_name": "Smith" |
|
771
|
}' |
|
772
|
``` |
|
773
|
|
|
774
|
Make sure to replace: |
|
775
|
|
|
776
|
- `{publishable_api_key}` with the publishable API key you retrieved from the Medusa Admin dashboard. |
|
777
|
- `{reg_token}` with the registration token you received in the previous step. |
|
778
|
- The customer details in the request body with the ones you want to use. Use the same phone number you used in the previous step. |
|
779
|
- You pass the email because it's required by the [Register Customer](!api!/store/customers/register-customer) API route. You set it to the phone number with a `gmail.com` domain. |
|
780
|
|
|
781
|
The request will return the created customer's details: |
|
782
|
|
|
783
|
```json title="Example Response" |
|
784
|
{ |
|
785
|
"customer": { |
|
786
|
"id": "cus_01JVPESW5SM1MSVPNM2MSC0ZEC", |
|
787
|
"email": "+19077890116@gmail.com", |
|
788
|
"company_name": null, |
|
789
|
"first_name": "John", |
|
790
|
"last_name": "Smith", |
|
791
|
"phone": "19077890116", |
|
792
|
"metadata": null, |
|
793
|
"has_account": true, |
|
794
|
"deleted_at": null, |
|
795
|
"created_at": "2025-05-20T09:01:13.273Z", |
|
796
|
"updated_at": "2025-05-20T09:01:13.273Z", |
|
797
|
"addresses": [] |
|
798
|
} |
|
799
|
} |
|
800
|
``` |
|
801
|
|
|
802
|
The customer can now authenticate using the phone number and OTP. |
|
803
|
|
|
804
|
#### c. Authenticate Customer |
|
805
|
|
|
806
|
Next, you'll authenticate the customer using the [Authenticate Customer](!api!/store/auth/authenticate-customer) API route. This would send the customer an OTP to their phone number (which you'll implement in the next step). |
|
807
|
|
|
808
|
So, send a `POST` request to `/auth/customer/phone-auth`: |
|
809
|
|
|
810
|
```bash |
|
811
|
curl -X POST 'http://localhost:9000/auth/customer/phone-auth' \ |
|
812
|
--header 'Content-Type: application/json' \ |
|
813
|
--data '{ |
|
814
|
"phone": "+19077890116" |
|
815
|
}' |
|
816
|
``` |
|
817
|
|
|
818
|
Make sure to replace the phone number with the one you used to register the customer. |
|
819
|
|
|
820
|
This will return a `location` in the response: |
|
821
|
|
|
822
|
```json title="Example Response" |
|
823
|
{ |
|
824
|
"location": "otp" |
|
825
|
} |
|
826
|
``` |
|
827
|
|
|
828
|
Indicating that the user should verify their OTP. |
|
829
|
|
|
830
|
<Note> |
|
831
|
|
|
832
|
You can also use this route to resend the OTP if the user didn't receive it or if a minute has passed since the last OTP was sent. |
|
833
|
|
|
834
|
</Note> |
|
835
|
|
|
836
|
#### d. Verify OTP |
|
837
|
|
|
838
|
If you check the logs of the Medusa application, you'll see that the OTP was generated and logged: |
|
839
|
|
|
840
|
```bash |
|
841
|
info: Generated OTP: 576794 |
|
842
|
``` |
|
843
|
|
|
844
|
As mentioned before, this is only for debugging purposes. In the next step, you'll implement the logic to send the OTP to the user using Twilio. |
|
845
|
|
|
846
|
So, to verify the OTP, you'll send a request to the [Verify Callback API route](!api!/store/auth/validate-authentication-callback): |
|
847
|
|
|
848
|
```bash |
|
849
|
curl -X POST 'http://localhost:9000/auth/customer/phone-auth/callback?phone=%2B19077890116&otp=476588' |
|
850
|
``` |
|
851
|
|
|
852
|
You pass the following query parameters: |
|
853
|
|
|
854
|
- `phone`: The phone number of the customer. Make sure to use the same phone number you used to register the customer, and to encode it. For example, the `+` sign should be encoded as `%2B`. |
|
855
|
- `otp`: The OTP that the customer received. Make sure to use the same OTP shown in the logs. |
|
856
|
|
|
857
|
If the OTP is valid, you'll receive a JWT token in the response: |
|
858
|
|
|
859
|
```json title="Example Response" |
|
860
|
{ |
|
861
|
"token": "123..." |
|
862
|
} |
|
863
|
``` |
|
864
|
|
|
865
|
You can use this token to authenticate the customer in the application. For example, you can use the token to [retrieve the customer's details](!api!/store/customers/get-customer). |
|
866
|
|
|
867
|
<Note> |
|
868
|
|
|
869
|
If the OTP has expired, send a request to the [Authenticate Customer](#c-authenticate-customer) API route to generate a new OTP |
|
870
|
|
|
871
|
</Note> |
|
872
|
|
|
873
|
--- |
|
874
|
|
|
875
|
## Step 3: Integrate Twilio SMS |
|
876
|
|
|
877
|
Similar to the Auth Module, the [Notification Module](../../../infrastructure-modules/notification/page.mdx) allows registering custom providers to send notifications, such as SMS or email. |
|
878
|
|
|
879
|
In this step, you'll create a Twilio Notification Module Provider, then use it to send the OTP to the customer. |
|
880
|
|
|
881
|
<Prerequisites |
|
882
|
items={[ |
|
883
|
{ |
|
884
|
text: "Twilio Account", |
|
885
|
link: "https://console.twilio.com/" |
|
886
|
}, |
|
887
|
{ |
|
888
|
text: "Twilio From Phone Number", |
|
889
|
link: "https://www.twilio.com/docs/phone-numbers" |
|
890
|
}, |
|
891
|
{ |
|
892
|
text: "Twilio Account SID, which you can retrieve from the Twilio Console homepage.", |
|
893
|
link: "https://www.twilio.com/docs/usage/tutorials/how-to-use-your-free-trial-account-namer#console-dashboard-home-page" |
|
894
|
}, |
|
895
|
{ |
|
896
|
text: "Twilio Auth Token, which you can retrieve from the Twilio Console homepage.", |
|
897
|
link: "https://www.twilio.com/docs/usage/tutorials/how-to-use-your-free-trial-account-namer#console-dashboard-home-page" |
|
898
|
} |
|
899
|
]} |
|
900
|
/> |
|
901
|
|
|
902
|
### a. Install Twilio SDK |
|
903
|
|
|
904
|
Before you start implementing the Twilio Notification Module Provider, install the Twilio SDK to interact with the Twilio API. |
|
905
|
|
|
906
|
Run the following command in the Medusa application directory: |
|
907
|
|
|
908
|
```bash npm2yarn |
|
909
|
npm install twilio |
|
910
|
``` |
|
911
|
|
|
912
|
You'll use the Twilio SDK in the Notification Module Provider's service. |
|
913
|
|
|
914
|
### b. Create Module Directory |
|
915
|
|
|
916
|
Create the directory `src/modules/twilio-sms` to create the Twilio Notification Module Provider. |
|
917
|
|
|
918
|
### c. Create Notification Module Provider Service |
|
919
|
|
|
920
|
A Notification Module Provider has a service that contains the sending logic. The service must extend the `AbstractNotificationProviderService` class. |
|
921
|
|
|
922
|
So, create the file `src/modules/twilio-sms/service.ts` with the following content: |
|
923
|
|
|
924
|
export const twilioSmsServiceHighlights = [ |
|
925
|
["9", "accountSid", "Twilio account SID."], |
|
926
|
["10", "authToken", "Twilio auth token."], |
|
927
|
["11", "from", "Twilio phone number to send the SMS from."], |
|
928
|
["15", "identifier", "Unique identifier for the module."], |
|
929
|
["16", "client", "Twilio client to send the SMS."], |
|
930
|
] |
|
931
|
|
|
932
|
```ts title="src/modules/twilio-sms/service.ts" highlights={twilioSmsServiceHighlights} |
|
933
|
import { |
|
934
|
AbstractNotificationProviderService, |
|
935
|
} from "@medusajs/framework/utils" |
|
936
|
import { Twilio } from "twilio" |
|
937
|
|
|
938
|
type InjectedDependencies = {} |
|
939
|
|
|
940
|
type TwilioSmsServiceOptions = { |
|
941
|
accountSid: string |
|
942
|
authToken: string |
|
943
|
from: string |
|
944
|
} |
|
945
|
|
|
946
|
class TwilioSmsService extends AbstractNotificationProviderService { |
|
947
|
static readonly identifier = "twilio-sms" |
|
948
|
private readonly client: Twilio |
|
949
|
private readonly from: string |
|
950
|
|
|
951
|
constructor(container: InjectedDependencies, options: TwilioSmsServiceOptions) { |
|
952
|
super() |
|
953
|
|
|
954
|
this.client = new Twilio(options.accountSid, options.authToken) |
|
955
|
this.from = options.from |
|
956
|
} |
|
957
|
} |
|
958
|
``` |
|
959
|
|
|
960
|
You'll get a type error about implementing the abstract methods of the `AbstractNotificationProviderService` class, which you'll add in the next steps. |
|
961
|
|
|
962
|
A Notification Module Provider must have an `identifier` static property, which is a unique identifier for the module. This identifier is used to register the module in the Medusa application. |
|
963
|
|
|
964
|
A module provider's constructor receives two parameters: |
|
965
|
|
|
966
|
- `container`: The [module's container](!docs!/learn/fundamentals/modules/container) that contains Framework resources available to the module. You don't need to access any resources for this provider. |
|
967
|
- `options`: Options that are passed to the module provider when it's registered in Medusa's configurations. You define the following option: |
|
968
|
- `accountSid`: The Twilio account SID. |
|
969
|
- `authToken`: The Twilio auth token. |
|
970
|
- `from`: The Twilio phone number to send the SMS from. |
|
971
|
|
|
972
|
<Note> |
|
973
|
|
|
974
|
You'll learn how to set these options when you [add the module provider to Medusa's configurations](#g-add-module-provider-to-medusas-configurations). |
|
975
|
|
|
976
|
</Note> |
|
977
|
|
|
978
|
In the constructor, you set the class's properties to the injected dependencies and options. |
|
979
|
|
|
980
|
In the next sections, you'll implement the methods of the `AbstractNotificationProviderService` class. |
|
981
|
|
|
982
|
<Note> |
|
983
|
|
|
984
|
Refer to the [Create Notification Module Provider](/references/notification-provider-module) guide for detailed information about the methods. |
|
985
|
|
|
986
|
</Note> |
|
987
|
|
|
988
|
### d. Implement validateOptions Method |
|
989
|
|
|
990
|
The `validateOptions` method is used to validate the options passed to the module provider. If the method throws an error, the Medusa application won't start. |
|
991
|
|
|
992
|
So, add the `validateOptions` method to the `TwilioSmsService` class: |
|
993
|
|
|
994
|
```ts title="src/modules/twilio-sms/service.ts" |
|
995
|
import { MedusaError } from "@medusajs/framework/utils" |
|
996
|
|
|
997
|
class TwilioSmsService extends AbstractNotificationProviderService { |
|
998
|
// ... |
|
999
|
static validateOptions(options: Record<any, any>): void | never { |
|
1000
|
if (!options.accountSid) { |
|
1001
|
throw new MedusaError( |
|
1002
|
MedusaError.Types.INVALID_ARGUMENT, |
|
1003
|
"Account SID is required" |
|
1004
|
) |
|
1005
|
} |
|
1006
|
if (!options.authToken) { |
|
1007
|
throw new MedusaError( |
|
1008
|
MedusaError.Types.INVALID_ARGUMENT, |
|
1009
|
"Auth token is required" |
|
1010
|
) |
|
1011
|
} |
|
1012
|
if (!options.from) { |
|
1013
|
throw new MedusaError( |
|
1014
|
MedusaError.Types.INVALID_ARGUMENT, |
|
1015
|
"From is required" |
|
1016
|
) |
|
1017
|
} |
|
1018
|
} |
|
1019
|
} |
|
1020
|
``` |
|
1021
|
|
|
1022
|
The `validateOptions` method receives the options passed to the module provider as a parameter. |
|
1023
|
|
|
1024
|
In the method, you throw an error if any of the options are not set. |
|
1025
|
|
|
1026
|
### e. Implement send Method |
|
1027
|
|
|
1028
|
The only required method for a Notification Module Provider is the `send` method. When the Medusa application needs to send a notification using the provider's channel (such as SMS), it calls this method of the registered provider. |
|
1029
|
|
|
1030
|
So, add the `send` method to the `TwilioSmsService` class: |
|
1031
|
|
|
1032
|
export const sendHighlights = [ |
|
1033
|
["13", "to", "Extract the phone number to send the SMS to."], |
|
1034
|
["13", "content", "Extract the content of the SMS."], |
|
1035
|
["13", "template", "Extract the template to use for the SMS."], |
|
1036
|
["13", "data", "Extract the data to use in the template."], |
|
1037
|
["14", "contentText", "Set the content text to either the text or template content."], |
|
1038
|
["14", "getTemplateContent", "Get the content for the template."], |
|
1039
|
["18", "message", "Send the SMS using Twilio's client."], |
|
1040
|
["29", "getTemplateContent", "A method to get the content for the template."], |
|
1041
|
] |
|
1042
|
|
|
1043
|
```ts title="src/modules/twilio-sms/service.ts" highlights={sendHighlights} |
|
1044
|
// other imports... |
|
1045
|
import { |
|
1046
|
ProviderSendNotificationDTO, |
|
1047
|
ProviderSendNotificationResultsDTO, |
|
1048
|
} from "@medusajs/framework/types" |
|
1049
|
import { MedusaError } from "@medusajs/framework/utils" |
|
1050
|
|
|
1051
|
class TwilioSmsService extends AbstractNotificationProviderService { |
|
1052
|
// ... |
|
1053
|
async send( |
|
1054
|
notification: ProviderSendNotificationDTO |
|
1055
|
): Promise<ProviderSendNotificationResultsDTO> { |
|
1056
|
const { to, content, template, data } = notification |
|
1057
|
const contentText = content?.text || await this.getTemplateContent( |
|
1058
|
template, data |
|
1059
|
) |
|
1060
|
|
|
1061
|
const message = await this.client.messages.create({ |
|
1062
|
body: contentText, |
|
1063
|
from: this.from, |
|
1064
|
to, |
|
1065
|
}) |
|
1066
|
|
|
1067
|
return { |
|
1068
|
id: message.sid, |
|
1069
|
} |
|
1070
|
} |
|
1071
|
|
|
1072
|
async getTemplateContent( |
|
1073
|
template: string, |
|
1074
|
data?: Record<string, unknown> | null |
|
1075
|
): Promise<string> { |
|
1076
|
switch (template) { |
|
1077
|
case "otp-template": |
|
1078
|
if (!data?.otp) { |
|
1079
|
throw new MedusaError( |
|
1080
|
MedusaError.Types.INVALID_DATA, |
|
1081
|
"OTP is required for OTP template" |
|
1082
|
) |
|
1083
|
} |
|
1084
|
|
|
1085
|
return `Your OTP is ${data.otp}` |
|
1086
|
default: |
|
1087
|
throw new MedusaError( |
|
1088
|
MedusaError.Types.NOT_FOUND, |
|
1089
|
`Template ${template} not found` |
|
1090
|
) |
|
1091
|
} |
|
1092
|
} |
|
1093
|
} |
|
1094
|
``` |
|
1095
|
|
|
1096
|
You implement the `send` method and a helper `getTemplateContent` method. |
|
1097
|
|
|
1098
|
#### send Parameters |
|
1099
|
|
|
1100
|
The `send` method receives an object parameter with the following properties: |
|
1101
|
|
|
1102
|
- `to`: The phone number to send the SMS to. |
|
1103
|
- `content`: An object containing the content of the SMS. The `text` property is the text to send. |
|
1104
|
- `template`: The template to use for the SMS. This is used to retrieve the fallback content of the SMS if `content.text` is not provided. |
|
1105
|
- `data`: An object containing the data to use in the template. This is used to replace placeholders in the template with actual values. |
|
1106
|
|
|
1107
|
<Note> |
|
1108
|
|
|
1109
|
The method receives other parameters, which you can find in the [Create Notification Module Provider](/references/notification-provider-module#send) guide. |
|
1110
|
|
|
1111
|
</Note> |
|
1112
|
|
|
1113
|
#### send Method Logic |
|
1114
|
|
|
1115
|
In the method, you set the SMS content either to the `text` property of the `content` object or to the template content. You define a `getTemplateContent` method that retrieves the content for a template. |
|
1116
|
|
|
1117
|
Then, you use the `messages.create` method of the Twilio client to send the SMS. You pass the following parameters: |
|
1118
|
|
|
1119
|
- `body`: The content of the SMS. |
|
1120
|
- `from`: The Twilio phone number to send the SMS from. |
|
1121
|
- `to`: The phone number to send the SMS to. |
|
1122
|
|
|
1123
|
#### send Return Value |
|
1124
|
|
|
1125
|
Finally, you return an object that has an `id` property with the ID of the sent SMS. This ID is stored in the notification record in the database. |
|
1126
|
|
|
1127
|
### f. Export Module Definition |
|
1128
|
|
|
1129
|
You've now finished implementing the necessary methods for the Twilio Notification Module Provider. You only need to export its definition. |
|
1130
|
|
|
1131
|
To create the module's definition, create the file `src/modules/twilio-sms/index.ts` with the following content: |
|
1132
|
|
|
1133
|
```ts title="src/modules/twilio-sms/index.ts" |
|
1134
|
import { |
|
1135
|
ModuleProvider, |
|
1136
|
Modules, |
|
1137
|
} from "@medusajs/framework/utils" |
|
1138
|
import TwilioSMSNotificationService from "./service" |
|
1139
|
|
|
1140
|
export default ModuleProvider(Modules.NOTIFICATION, { |
|
1141
|
services: [TwilioSMSNotificationService], |
|
1142
|
}) |
|
1143
|
``` |
|
1144
|
|
|
1145
|
You use `ModuleProvider` from the Modules SDK to create the module provider's definition passing it two parameters: |
|
1146
|
|
|
1147
|
1. The name of the module that this provider belongs to, which is `Modules.NOTIFICATION` in this case. |
|
1148
|
2. An object with a required property `services` indicating the module provider's services. Each of these services will be registered as notification providers in Medusa. |
|
1149
|
|
|
1150
|
### g. Add Module Provider to Medusa's Configurations |
|
1151
|
|
|
1152
|
You'll now add the Twilio Notification Module Provider to Medusa's configurations to start using it. |
|
1153
|
|
|
1154
|
In `medusa-config.ts`, add the following to the `modules` property: |
|
1155
|
|
|
1156
|
```ts title="medusa-config.ts" |
|
1157
|
module.exports = defineConfig({ |
|
1158
|
// ... |
|
1159
|
modules: [ |
|
1160
|
// ... |
|
1161
|
{ |
|
1162
|
resolve: "@medusajs/medusa/notification", |
|
1163
|
options: { |
|
1164
|
providers: [ |
|
1165
|
// default provider |
|
1166
|
{ |
|
1167
|
resolve: "@medusajs/medusa/notification-local", |
|
1168
|
id: "local", |
|
1169
|
options: { |
|
1170
|
name: "Local Notification Provider", |
|
1171
|
channels: ["feed"], |
|
1172
|
}, |
|
1173
|
}, |
|
1174
|
{ |
|
1175
|
resolve: "./src/modules/twilio-sms", |
|
1176
|
id: "twilio-sms", |
|
1177
|
options: { |
|
1178
|
channels: ["sms"], |
|
1179
|
accountSid: process.env.TWILIO_ACCOUNT_SID, |
|
1180
|
authToken: process.env.TWILIO_AUTH_TOKEN, |
|
1181
|
from: process.env.TWILIO_FROM, |
|
1182
|
}, |
|
1183
|
}, |
|
1184
|
], |
|
1185
|
}, |
|
1186
|
}, |
|
1187
|
], |
|
1188
|
}) |
|
1189
|
``` |
|
1190
|
|
|
1191
|
You pass the Notification Module in the `modules` property to register the Twilio Notification Module Provider. |
|
1192
|
|
|
1193
|
The Notification Module accepts a `providers` option, which is an array of Notification Module Providers to register. You register the `local` provider, which is registered by default when you don't provide any other providers. |
|
1194
|
|
|
1195
|
To register the Twilio Notification Module Provider, you add an object with the following properties: |
|
1196
|
|
|
1197
|
- `resolve`: The path to the module provider. |
|
1198
|
- `id`: The ID of the module provider. The notification provider is then registered with the ID `np_{identifier}_{id}`. |
|
1199
|
- `options`: The options to pass to the module provider. These include the options you defined in the `Options` interface of the module provider's service. |
|
1200
|
- `channels`: The channels that the notification provider supports. In this case, you set it to `sms`, which is the channel used to send SMS notifications. |
|
1201
|
- `accountSid`: The Twilio account SID. |
|
1202
|
- `authToken`: The Twilio auth token. |
|
1203
|
- `from`: The Twilio phone number to send the SMS from. |
|
1204
|
|
|
1205
|
### h. Add Environment Variables |
|
1206
|
|
|
1207
|
To set the value of the Twilio options, add the following environment variables to your `.env` file: |
|
1208
|
|
|
1209
|
```shell title=".env" |
|
1210
|
TWILIO_ACCOUNT_SID=AC... |
|
1211
|
TWILIO_AUTH_TOKEN=05... |
|
1212
|
TWILIO_FROM=+1... |
|
1213
|
``` |
|
1214
|
|
|
1215
|
Where: |
|
1216
|
|
|
1217
|
- `TWILIO_ACCOUNT_SID`: The Twilio account SID. |
|
1218
|
- `TWILIO_AUTH_TOKEN`: The Twilio auth token. |
|
1219
|
- `TWILIO_FROM`: The Twilio phone number to send the SMS from. Make sure to use the phone number you purchased from Twilio. |
|
1220
|
|
|
1221
|
You can retrieve these information from the Twilio Console homepage. |
|
1222
|
|
|
1223
|
 |
|
1224
|
|
|
1225
|
### i. Handle OTP Generated Event |
|
1226
|
|
|
1227
|
Now that you have integrated Twilio into Medusa, you can use it to send the OTP to the customer. To do that, you need to handle the `phone-auth.otp.generated` event that you emitted in the `authenticate` method of the Phone Authentication Module Provider. |
|
1228
|
|
|
1229
|
You can listen to events in a [subscriber](!docs!/learn/fundamentals/events-and-subscribers). A subscriber is an asynchronous function that listens to events to perform actions when the event is emitted. |
|
1230
|
|
|
1231
|
In this step, you'll create a subscriber that listens to the `phone-auth.otp.generated` event and sends an SMS to the customer with the OTP. |
|
1232
|
|
|
1233
|
<Note> |
|
1234
|
|
|
1235
|
Refer to the [Events and Subscribers](!docs!/learn/fundamentals/events-and-subscribers) documentation to learn more. |
|
1236
|
|
|
1237
|
</Note> |
|
1238
|
|
|
1239
|
Subscribers are created in a TypeScript or JavaScript file under the `src/subscribers` directory. So, to create a subscriber, create the file `src/subscribers/send-otp.ts` with the following content: |
|
1240
|
|
|
1241
|
export const sendOtpHighlights = [ |
|
1242
|
["14", "notificationModuleService", "Resolve the Notification Module's service."], |
|
1243
|
["18", "createNotifications", "Send the OTP to the user using Twilio."], |
|
1244
|
["29", `"phone-auth.otp.generated"`, "The event the subscriber is listening to."], |
|
1245
|
] |
|
1246
|
|
|
1247
|
```ts title="src/subscribers/send-otp.ts" highlights={sendOtpHighlights} |
|
1248
|
import { |
|
1249
|
SubscriberArgs, |
|
1250
|
type SubscriberConfig, |
|
1251
|
} from "@medusajs/medusa" |
|
1252
|
import { Modules } from "@medusajs/framework/utils" |
|
1253
|
|
|
1254
|
export default async function sendOtpHandler({ |
|
1255
|
event: { data: { |
|
1256
|
phone, |
|
1257
|
otp, |
|
1258
|
} }, |
|
1259
|
container, |
|
1260
|
}: SubscriberArgs<{ phone: string, otp: string }>) { |
|
1261
|
const notificationModuleService = container.resolve( |
|
1262
|
Modules.NOTIFICATION |
|
1263
|
) |
|
1264
|
|
|
1265
|
await notificationModuleService.createNotifications({ |
|
1266
|
to: phone, |
|
1267
|
channel: "sms", |
|
1268
|
template: "otp-template", |
|
1269
|
data: { |
|
1270
|
otp, |
|
1271
|
}, |
|
1272
|
}) |
|
1273
|
} |
|
1274
|
|
|
1275
|
export const config: SubscriberConfig = { |
|
1276
|
event: "phone-auth.otp.generated", |
|
1277
|
} |
|
1278
|
``` |
|
1279
|
|
|
1280
|
The subscriber file must export: |
|
1281
|
|
|
1282
|
- An asynchronous subscriber function that's executed whenever the associated event is triggered. |
|
1283
|
- A configuration object with an event property whose value is the event the subscriber is listening to, which is `phone-auth.otp.generated`. |
|
1284
|
|
|
1285
|
The subscriber function accepts an object with the following properties: |
|
1286
|
|
|
1287
|
- `event`: An object with the event's data payload. In the `authenticate` method, you emitted the event with the following data: |
|
1288
|
- `phone`: The phone number of the user. |
|
1289
|
- `otp`: The OTP that was generated. |
|
1290
|
- `container`: The [Medusa container](!docs!/learn/fundamentals/medusa-container), which you can use to resolve Framework and commerce resources. |
|
1291
|
|
|
1292
|
In the subscriber function, you resolve the Notification Module's service from the Medusa container. Then, you use its `createNotifications` method to send the OTP to the user. |
|
1293
|
|
|
1294
|
Under the hood, the Notification Module's service delegates the sending to the Notification Module Provider of the `sms` channel, which is the Twilio Notification Module Provider in this case. |
|
1295
|
|
|
1296
|
The `createNotifications` method accepts an object with the following properties: |
|
1297
|
|
|
1298
|
- `to`: The phone number to send the notification to. You use the phone number from the event's data payload. |
|
1299
|
- `channel`: The channel to use to send the notification, which is `sms`. |
|
1300
|
- `template`: The template to use for the notification content, which is `otp-template`. |
|
1301
|
- `data`: An object containing the data to use in the template. You pass the OTP to the template. |
|
1302
|
|
|
1303
|
### j. Test it Out |
|
1304
|
|
|
1305
|
To test out the Twilio Notification Module Provider, you can follow the steps in the [Test Out Phone Authentication](#test-out-phone-authentication) section. |
|
1306
|
|
|
1307
|
After you authenticate the customer, the OTP will be sent to the customer's phone number using Twilio. Then, you can use the OTP to verify the authentication and receive a JWT token. |
|
1308
|
|
|
1309
|
Alternatively, you can also test it out after customizing the Next.js Starter Storefront, which you'll do in the next step. |
|
1310
|
|
|
1311
|
<Note> |
|
1312
|
|
|
1313
|
Make sure to remove the OTP logging line in the `generateOTP` method of the Phone Authentication Module Provider's service now that you have integrated Twilio. |
|
1314
|
|
|
1315
|
</Note> |
|
1316
|
|
|
1317
|
--- |
|
1318
|
|
|
1319
|
## Step 4: Use Phone Authentication in the Next.js Starter Storefront |
|
1320
|
|
|
1321
|
In this step, you'll customize the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx) to allow customers to authenticate using their phone number and OTP. |
|
1322
|
|
|
1323
|
By default, the Next.js Starter Storefront supports email and password authentication. You'll replace it with phone authentication, but you can also keep both authentication methods if you want to. |
|
1324
|
|
|
1325
|
<Note title="Reminder" forceMultiline> |
|
1326
|
|
|
1327
|
The Next.js Starter Storefront is available in the `apps/storefront` directory of your project: |
|
1328
|
|
|
1329
|
```bash |
|
1330
|
cd apps/storefront |
|
1331
|
``` |
|
1332
|
|
|
1333
|
</Note> |
|
1334
|
|
|
1335
|
### a. Install Phone Input Package |
|
1336
|
|
|
1337
|
To easily show a phone input where the user can enter their phone number, install the `react-phone-number-input` package: |
|
1338
|
|
|
1339
|
```bash npm2yarn badgeLabel="Storefront" badgeColor="blue" |
|
1340
|
npm install react-phone-number-input |
|
1341
|
``` |
|
1342
|
|
|
1343
|
You'll use it in the login and registration forms to show a phone input. |
|
1344
|
|
|
1345
|
### b. Add Authenticate Function |
|
1346
|
|
|
1347
|
Before adding the forms, you'll add the functions that send requests to the Medusa API to authenticate the customer. |
|
1348
|
|
|
1349
|
The first one you'll add is the `authenticateWithPhone` function, which sends a request to the `/auth/customer/phone-auth` API route to authenticate the customer using their phone number. |
|
1350
|
|
|
1351
|
In `src/lib/data/customer.ts`, add the following function: |
|
1352
|
|
|
1353
|
```ts title="src/lib/data/customer.ts" badgeLabel="Storefront" badgeColor="blue" |
|
1354
|
export const authenticateWithPhone = async (phone: string) => { |
|
1355
|
try { |
|
1356
|
const response = await sdk.auth.login("customer", "phone-auth", { |
|
1357
|
phone, |
|
1358
|
}) |
|
1359
|
|
|
1360
|
if ( |
|
1361
|
typeof response === "string" || |
|
1362
|
!response.location || |
|
1363
|
response.location !== "otp" |
|
1364
|
) { |
|
1365
|
throw new Error("Failed to login") |
|
1366
|
} |
|
1367
|
|
|
1368
|
return true |
|
1369
|
} catch (error: any) { |
|
1370
|
return error.toString() |
|
1371
|
} |
|
1372
|
} |
|
1373
|
``` |
|
1374
|
|
|
1375
|
The function accepts the phone number as a parameter. |
|
1376
|
|
|
1377
|
In the function, you use the [JS SDK](../../../js-sdk/page.mdx), which is configured within the Next.js Starter Storefront, to send a request to the `/auth/customer/phone-auth` API route. You pass the phone number in the request body. |
|
1378
|
|
|
1379
|
If the request doesn't return a `location` property set to `otp`, you throw an error. Otherwise, you return `true` to indicate that the request was successful. |
|
1380
|
|
|
1381
|
### c. add Verify OTP Function |
|
1382
|
|
|
1383
|
Next, you'll add the `verifyOTP` function, which sends a request to the `/auth/customer/phone-auth/callback` API route to verify the OTP. |
|
1384
|
|
|
1385
|
In `src/lib/data/customer.ts`, add the following function: |
|
1386
|
|
|
1387
|
export const verifyOtpHighlights = [ |
|
1388
|
["9", "callback", "Verify the OTP using the callback API route."], |
|
1389
|
["14", "setAuthToken", "Set the authentication token."], |
|
1390
|
["17", "revalidateTag", "Revalidate the customer cache tag to refresh customer-related UI."], |
|
1391
|
["19", "transferCart", "Transfer the cart from guest to authenticated customer."], |
|
1392
|
] |
|
1393
|
|
|
1394
|
```ts title="src/lib/data/customer.ts" badgeLabel="Storefront" badgeColor="blue" highlights={verifyOtpHighlights} |
|
1395
|
export const verifyOtp = async ({ |
|
1396
|
otp, |
|
1397
|
phone, |
|
1398
|
}: { |
|
1399
|
otp: string |
|
1400
|
phone: string |
|
1401
|
}) => { |
|
1402
|
try { |
|
1403
|
const token = await sdk.auth.callback("customer", "phone-auth", { |
|
1404
|
phone, |
|
1405
|
otp, |
|
1406
|
}) |
|
1407
|
|
|
1408
|
await setAuthToken(token) |
|
1409
|
|
|
1410
|
const customerCacheTag = await getCacheTag("customers") |
|
1411
|
revalidateTag(customerCacheTag) |
|
1412
|
|
|
1413
|
await transferCart() |
|
1414
|
|
|
1415
|
return true |
|
1416
|
} catch (e: any) { |
|
1417
|
return e.toString() |
|
1418
|
} |
|
1419
|
} |
|
1420
|
``` |
|
1421
|
|
|
1422
|
The function accepts an object with the following properties: |
|
1423
|
|
|
1424
|
- `otp`: The OTP to verify. |
|
1425
|
- `phone`: The phone number of the customer. |
|
1426
|
|
|
1427
|
In the function, you use the JS SDK to send a request to the `/auth/customer/phone-auth/callback` API route. You pass the phone number and OTP in the request body. |
|
1428
|
|
|
1429
|
If the request is successful and you receive a token, you set the token in the cookies and refresh the customer cache. This ensures that all customer-related UI is updated after logging in, such as showing the customer's profile when accessing the `/account` page. |
|
1430
|
|
|
1431
|
Then, you call the `transferCart` function to transfer the cart from the guest user to the authenticated customer. |
|
1432
|
|
|
1433
|
Finally, you return `true` to indicate that the request was successful. |
|
1434
|
|
|
1435
|
### d. Add Registration Function |
|
1436
|
|
|
1437
|
The last function you'll add is the `registerWithPhone` function, which will register the customer using their phone number. |
|
1438
|
|
|
1439
|
In `src/lib/data/customer.ts`, add the following function: |
|
1440
|
|
|
1441
|
export const registerWithPhoneHighlights = [ |
|
1442
|
["11", "regToken", "Retrieve the registration token."], |
|
1443
|
["20", "setAuthToken", "Set the authentication token."], |
|
1444
|
["33", "create", "Create the customer."], |
|
1445
|
["39", "authenticateWithPhone", "Authenticate the customer using their phone number."], |
|
1446
|
] |
|
1447
|
|
|
1448
|
```ts title="src/lib/data/customer.ts" badgeLabel="Storefront" badgeColor="blue" highlights={registerWithPhoneHighlights} |
|
1449
|
export const registerWithPhone = async ({ |
|
1450
|
firstName, |
|
1451
|
lastName, |
|
1452
|
phone, |
|
1453
|
}: { |
|
1454
|
firstName: string |
|
1455
|
lastName: string |
|
1456
|
phone: string |
|
1457
|
}) => { |
|
1458
|
try { |
|
1459
|
const { token: regToken } = await sdk.client.fetch< |
|
1460
|
{ token: string } |
|
1461
|
>(`/auth/customer/phone-auth/register`, { |
|
1462
|
method: "POST", |
|
1463
|
body: { |
|
1464
|
phone, |
|
1465
|
}, |
|
1466
|
}) |
|
1467
|
|
|
1468
|
await setAuthToken(regToken as string) |
|
1469
|
const headers = { |
|
1470
|
...(await getAuthHeaders()), |
|
1471
|
} |
|
1472
|
|
|
1473
|
const email = `${phone}@gmail.com` |
|
1474
|
const customerData = { |
|
1475
|
email, |
|
1476
|
first_name: firstName, |
|
1477
|
last_name: lastName, |
|
1478
|
phone, |
|
1479
|
} |
|
1480
|
|
|
1481
|
await sdk.store.customer.create( |
|
1482
|
customerData, |
|
1483
|
{}, |
|
1484
|
headers |
|
1485
|
) |
|
1486
|
|
|
1487
|
return await authenticateWithPhone(phone) |
|
1488
|
} catch (error: any) { |
|
1489
|
return error.toString() |
|
1490
|
} |
|
1491
|
} |
|
1492
|
``` |
|
1493
|
|
|
1494
|
The function accepts an object with the following properties: |
|
1495
|
|
|
1496
|
- `firstName`: The first name of the customer. |
|
1497
|
- `lastName`: The last name of the customer. |
|
1498
|
- `phone`: The phone number of the customer. |
|
1499
|
|
|
1500
|
In the function, you retrieve a registration token for the customer using the `/auth/customer/phone-auth/register` API route. You pass the phone number in the request body. |
|
1501
|
|
|
1502
|
Then, after setting the registration token in the cookies, you create a customer using the [Create Customer](!api!/store/customers/register-customer) API route. You pass the following properties in the request body: |
|
1503
|
|
|
1504
|
- `email`: The email of the customer. You set it to the phone number with a `@gmail.com` domain. |
|
1505
|
- `first_name`: The first name of the customer. |
|
1506
|
- `last_name`: The last name of the customer. |
|
1507
|
- `phone`: The phone number of the customer. |
|
1508
|
|
|
1509
|
Finally, you call the `authenticateWithPhone` function to authenticate the customer using their phone number. At this step, the customer would receive an OTP to login. |
|
1510
|
|
|
1511
|
### e. Add OTP Form |
|
1512
|
|
|
1513
|
Next, you'll add an OTP form that allows the customer to enter the OTP they receive after login or registration. Later, you'll reuse this form in both the login and registration pages. |
|
1514
|
|
|
1515
|
Create the file `src/modules/account/components/otp/index.tsx` with the following content: |
|
1516
|
|
|
1517
|
export const otpHighlights = [ |
|
1518
|
["13", "otp", "The OTP entered by the customer."], |
|
1519
|
["14", "error", "The error message to show if the OTP verification fails."], |
|
1520
|
["15", "isLoading", "A boolean indicating whether the OTP verification is in progress."], |
|
1521
|
["16", "countdown", "The countdown timer for resending the OTP."], |
|
1522
|
["17", "inputRefs", "A ref to store the input elements for the OTP digits."], |
|
1523
|
["19", "handleSubmit", "Verify OTP on submission."], |
|
1524
|
["33", "handleResend", "Resend OTP to the customer."], |
|
1525
|
["38", "handlePaste", "Improve paste experience for OTP input."], |
|
1526
|
] |
|
1527
|
|
|
1528
|
```tsx title="src/modules/account/components/otp/index.tsx" badgeLabel="Storefront" badgeColor="blue" highlights={otpHighlights} |
|
1529
|
"use client" |
|
1530
|
|
|
1531
|
import { Input } from "@medusajs/ui" |
|
1532
|
import { useState, useRef, useEffect } from "react" |
|
1533
|
import { authenticateWithPhone, verifyOtp } from "../../../../lib/data/customer" |
|
1534
|
import ErrorMessage from "../../../checkout/components/error-message" |
|
1535
|
|
|
1536
|
type Props = { |
|
1537
|
phone: string |
|
1538
|
} |
|
1539
|
|
|
1540
|
export const Otp = ({ phone }: Props) => { |
|
1541
|
const [otp, setOtp] = useState<string>("") |
|
1542
|
const [error, setError] = useState<string>("") |
|
1543
|
const [isLoading, setIsLoading] = useState<boolean>(false) |
|
1544
|
const [countdown, setCountdown] = useState<number>(60) |
|
1545
|
const inputRefs = useRef<(HTMLInputElement | null)[]>([]) |
|
1546
|
|
|
1547
|
const handleSubmit = async () => { |
|
1548
|
setIsLoading(true) |
|
1549
|
const response = await verifyOtp({ |
|
1550
|
otp, |
|
1551
|
phone, |
|
1552
|
}) |
|
1553
|
setOtp("") |
|
1554
|
setIsLoading(false) |
|
1555
|
|
|
1556
|
if (typeof response === "string") { |
|
1557
|
setError(response) |
|
1558
|
} |
|
1559
|
} |
|
1560
|
|
|
1561
|
const handleResend = async () => { |
|
1562
|
authenticateWithPhone(phone) |
|
1563
|
setCountdown(60) |
|
1564
|
} |
|
1565
|
|
|
1566
|
const handlePaste = (e: React.ClipboardEvent) => { |
|
1567
|
e.preventDefault() |
|
1568
|
const pastedData = e.clipboardData.getData("text") |
|
1569
|
const numericValue = pastedData.replace(/\D/g, "").slice(0, 6) |
|
1570
|
|
|
1571
|
if (numericValue) { |
|
1572
|
setOtp(numericValue) |
|
1573
|
// Focus the next empty input after pasted content |
|
1574
|
const nextEmptyIndex = Math.min(numericValue.length, 5) |
|
1575
|
inputRefs.current[nextEmptyIndex]?.focus() |
|
1576
|
} |
|
1577
|
} |
|
1578
|
|
|
1579
|
// TODO add use effects |
|
1580
|
} |
|
1581
|
``` |
|
1582
|
|
|
1583
|
You create an `Otp` component that accepts the phone number as a prop. |
|
1584
|
|
|
1585
|
In the component, you define the following state variables: |
|
1586
|
|
|
1587
|
- `otp`: The OTP entered by the customer. |
|
1588
|
- `error`: The error message to show if the OTP verification fails. |
|
1589
|
- `isLoading`: A boolean indicating whether the OTP verification is in progress. |
|
1590
|
- `countdown`: The countdown timer for resending the OTP. |
|
1591
|
- `inputRefs`: A ref to store the input elements for the OTP digits. You'll show six input elements for the OTP digits. |
|
1592
|
|
|
1593
|
You also define the following functions: |
|
1594
|
|
|
1595
|
- `handleSubmit`: This function is called when the customer submits the OTP. It calls the `verifyOtp` function to verify the OTP entered by the customer. |
|
1596
|
- `handleResend`: This function is called when the customer clicks the "Resend OTP" button that you'll add later. It calls the `authenticateWithPhone` function to resend the OTP to the customer's phone number. |
|
1597
|
- `handlePaste`: This function is called when the customer pastes the OTP in the input field. It improves the experience of pasting the OTP without having to enter it manually. |
|
1598
|
|
|
1599
|
#### Handle Variable Changes |
|
1600
|
|
|
1601
|
Next, you'll add `useEffect` hooks to handle changes in the state variables. |
|
1602
|
|
|
1603
|
Replace the `TODO` with the following: |
|
1604
|
|
|
1605
|
export const useEffectHighlights = [ |
|
1606
|
["1", "useEffect", "Focus the first input element when the component mounts."], |
|
1607
|
["7", "useEffect", "Automatically submit the OTP when the customer enters six digits."], |
|
1608
|
["15", "useEffect", "Add an interval to update the countdown timer every second."], |
|
1609
|
] |
|
1610
|
|
|
1611
|
```tsx title="src/modules/account/components/otp/index.tsx" badgeLabel="Storefront" badgeColor="blue" highlights={useEffectHighlights} |
|
1612
|
useEffect(() => { |
|
1613
|
if (inputRefs.current[0]) { |
|
1614
|
inputRefs.current[0].focus() |
|
1615
|
} |
|
1616
|
}, [inputRefs.current]) |
|
1617
|
|
|
1618
|
useEffect(() => { |
|
1619
|
if (otp.length !== 6 || isLoading) { |
|
1620
|
return |
|
1621
|
} |
|
1622
|
|
|
1623
|
handleSubmit() |
|
1624
|
}, [otp, isLoading]) |
|
1625
|
|
|
1626
|
useEffect(() => { |
|
1627
|
const timer = setInterval(() => { |
|
1628
|
setCountdown((prev) => { |
|
1629
|
return prev > 0 ? prev - 1 : 0 |
|
1630
|
}) |
|
1631
|
}, 1000) |
|
1632
|
|
|
1633
|
return () => clearInterval(timer) |
|
1634
|
}, []) |
|
1635
|
|
|
1636
|
// TODO render form |
|
1637
|
``` |
|
1638
|
|
|
1639
|
You add three `useEffect` hooks: |
|
1640
|
|
|
1641
|
1. The first one focuses the first input element when the component mounts. |
|
1642
|
2. The second one automatically submits the OTP when the customer enters six digits. |
|
1643
|
3. The third one adds an interval to update the countdown timer every second. |
|
1644
|
|
|
1645
|
### f. Render OTP Form |
|
1646
|
|
|
1647
|
Lastly, you'll render the OTP form with the input elements and the resend button. |
|
1648
|
|
|
1649
|
Replace the `TODO` with the following: |
|
1650
|
|
|
1651
|
```tsx title="src/modules/account/components/otp/index.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
1652
|
return ( |
|
1653
|
<div |
|
1654
|
className="max-w-sm flex flex-col items-center" |
|
1655
|
data-testid="otp-page" |
|
1656
|
> |
|
1657
|
<h1 className="text-large-semi uppercase mb-6"> |
|
1658
|
Verify Phone Number |
|
1659
|
</h1> |
|
1660
|
<p className="text-center text-base-regular text-ui-fg-base mb-4"> |
|
1661
|
Enter the code sent to your phone number to login. |
|
1662
|
</p> |
|
1663
|
<div className="flex gap-2 mb-4"> |
|
1664
|
{[...Array(6)].map((_, index) => ( |
|
1665
|
<Input |
|
1666
|
key={index} |
|
1667
|
type="text" |
|
1668
|
maxLength={1} |
|
1669
|
pattern="\d*" |
|
1670
|
inputMode="numeric" |
|
1671
|
disabled={isLoading} |
|
1672
|
className="w-10 h-10 text-center" |
|
1673
|
ref={(el) => { |
|
1674
|
inputRefs.current[index] = el |
|
1675
|
}} |
|
1676
|
onPaste={handlePaste} |
|
1677
|
value={otp[index] || ""} |
|
1678
|
onChange={(e) => { |
|
1679
|
const elm = e.target |
|
1680
|
const value = elm.value |
|
1681
|
setOtp((prev) => { |
|
1682
|
const newOtp = prev.split("") |
|
1683
|
newOtp[index] = value |
|
1684
|
return newOtp.join("") |
|
1685
|
}) |
|
1686
|
if (value && /^\d+$/.test(value)) { |
|
1687
|
// Move focus to next input |
|
1688
|
const nextInput = elm.parentElement?.nextElementSibling?.querySelector("input") |
|
1689
|
nextInput?.focus() |
|
1690
|
} |
|
1691
|
}} |
|
1692
|
onKeyDown={(e) => { |
|
1693
|
if (e.key === "Backspace" && !e.currentTarget.value) { |
|
1694
|
// Move focus to previous input on backspace |
|
1695
|
const prevInput = e.currentTarget.parentElement?.previousElementSibling?.querySelector("input") |
|
1696
|
prevInput?.focus() |
|
1697
|
} |
|
1698
|
}} |
|
1699
|
/> |
|
1700
|
))} |
|
1701
|
</div> |
|
1702
|
<div className="flex items-center gap-x-2 mb-4"> |
|
1703
|
<button |
|
1704
|
className="text-small-regular text-ui-fg-interactive disabled:text-ui-fg-disabled disabled:cursor-not-allowed" |
|
1705
|
onClick={handleResend} |
|
1706
|
disabled={countdown > 0} |
|
1707
|
> |
|
1708
|
{countdown > 0 ? `Resend code in ${countdown}s` : "Resend Code"} |
|
1709
|
</button> |
|
1710
|
</div> |
|
1711
|
<ErrorMessage error={error} /> |
|
1712
|
</div> |
|
1713
|
) |
|
1714
|
``` |
|
1715
|
|
|
1716
|
You show six input elements for the OTP digits. When a value is entered in an input, the focus moves to the next input. In addition, when the customer presses backspace on an empty input, the focus moves to the previous input. |
|
1717
|
|
|
1718
|
You also show a resend button that allows the customer to resend the OTP once the countdown timer reaches zero. |
|
1719
|
|
|
1720
|
You now have an OTP form that you can use in both the login and registration pages. |
|
1721
|
|
|
1722
|
### g. Add Registration Form |
|
1723
|
|
|
1724
|
You'll now add a registration form that allows the customer to register using their phone number. |
|
1725
|
|
|
1726
|
First, in `src/modules/account/templates/login-template.tsx`, update the `LOGIN_VIEW` to the following: |
|
1727
|
|
|
1728
|
```tsx title="src/modules/account/templates/login-template.tsx" badgeLabel="Storefront" badgeColor="blue" highlights={[["4"], ["5"]]} |
|
1729
|
export enum LOGIN_VIEW { |
|
1730
|
SIGN_IN = "sign-in", |
|
1731
|
REGISTER = "register", |
|
1732
|
REGISTER_PHONE = "register-phone", |
|
1733
|
SIGN_IN_PHONE = "sign-in-phone", |
|
1734
|
} |
|
1735
|
``` |
|
1736
|
|
|
1737
|
By default, the login template supports switching between the login and registration views for email and password authentication. With the above change, you add two new views: login and registration with phone number. |
|
1738
|
|
|
1739
|
Then, to add the registration form, create the file `src/modules/account/components/register-phone/index.tsx` with the following content: |
|
1740
|
|
|
1741
|
export const registerPhoneHighlights = [ |
|
1742
|
["20", "firstName", "The first name of the customer."], |
|
1743
|
["21", "lastName", "The last name of the customer."], |
|
1744
|
["22", "phone", "The phone number of the customer."], |
|
1745
|
["23", "error", "The error message to show if the registration fails."], |
|
1746
|
["24", "loading", "A boolean indicating whether the registration is in progress."], |
|
1747
|
["25", "enterOtp", "A boolean indicating whether to show the OTP form."], |
|
1748
|
["26", "countryCode", "The country code of the customer."], |
|
1749
|
["28", "handleSubmit", "Register customer on form submission."], |
|
1750
|
["45", "enterOtp", "Show the OTP form after successful registration."], |
|
1751
|
] |
|
1752
|
|
|
1753
|
```tsx title="src/modules/account/components/register-phone/index.tsx" badgeLabel="Storefront" badgeColor="blue" highlights={registerPhoneHighlights} |
|
1754
|
"use client" |
|
1755
|
|
|
1756
|
import { useState } from "react" |
|
1757
|
import Input from "@modules/common/components/input" |
|
1758
|
import { LOGIN_VIEW } from "@modules/account/templates/login-template" |
|
1759
|
import ErrorMessage from "@modules/checkout/components/error-message" |
|
1760
|
import LocalizedClientLink from "@modules/common/components/localized-client-link" |
|
1761
|
import { registerWithPhone } from "@lib/data/customer" |
|
1762
|
import "react-phone-number-input/style.css" |
|
1763
|
import PhoneInput from "react-phone-number-input" |
|
1764
|
import { Otp } from "../otp" |
|
1765
|
import { useParams } from "next/navigation" |
|
1766
|
import { Button } from "@medusajs/ui" |
|
1767
|
|
|
1768
|
type Props = { |
|
1769
|
setCurrentView: (view: LOGIN_VIEW) => void |
|
1770
|
} |
|
1771
|
|
|
1772
|
const RegisterPhone = ({ setCurrentView }: Props) => { |
|
1773
|
const [firstName, setFirstName] = useState("") |
|
1774
|
const [lastName, setLastName] = useState("") |
|
1775
|
const [phone, setPhone] = useState("") |
|
1776
|
const [error, setError] = useState("") |
|
1777
|
const [loading, setLoading] = useState(false) |
|
1778
|
const [enterOtp, setEnterOtp] = useState(false) |
|
1779
|
const { countryCode } = useParams() as { countryCode: string } |
|
1780
|
|
|
1781
|
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { |
|
1782
|
e.preventDefault() |
|
1783
|
setLoading(true) |
|
1784
|
const response = await registerWithPhone({ |
|
1785
|
firstName, |
|
1786
|
lastName, |
|
1787
|
phone, |
|
1788
|
}) |
|
1789
|
setLoading(false) |
|
1790
|
if (typeof response === "string") { |
|
1791
|
setError(response) |
|
1792
|
return |
|
1793
|
} |
|
1794
|
|
|
1795
|
setEnterOtp(true) |
|
1796
|
} |
|
1797
|
|
|
1798
|
if (enterOtp) { |
|
1799
|
return <Otp phone={phone} /> |
|
1800
|
} |
|
1801
|
|
|
1802
|
// TODO render form |
|
1803
|
} |
|
1804
|
|
|
1805
|
export default RegisterPhone |
|
1806
|
``` |
|
1807
|
|
|
1808
|
You create a `RegisterPhone` component that accepts a `setCurrentView` prop to switch between the login and registration views. |
|
1809
|
|
|
1810
|
In the component, you define the following state variables: |
|
1811
|
|
|
1812
|
- `firstName`, `lastName`, and `phone` to store the form inputs' values. |
|
1813
|
- `error`: The error message to show if the registration fails. |
|
1814
|
- `loading`: A boolean indicating whether the registration is in progress. |
|
1815
|
- `enterOtp`: A boolean indicating whether to show the OTP form. This is enabled once the customer is registered and they need to authenticate using the OTP. |
|
1816
|
- `countryCode`: The country code of the customer, which is retrieved from the URL parameters. You'll use this to show the phone input with a default selected country. |
|
1817
|
|
|
1818
|
You also define a `handleSubmit` function that handles the form submission. It calls the `registerWithPhone` function to register the customer using their phone number. |
|
1819
|
|
|
1820
|
If the registration is successful, you set `enterOtp` to `true` to show the OTP form. Otherwise, you set the error message. |
|
1821
|
|
|
1822
|
#### Render Registration Form |
|
1823
|
|
|
1824
|
Next, you'll render the registration form with the input fields and the submit button. |
|
1825
|
|
|
1826
|
Replace the `TODO` with the following: |
|
1827
|
|
|
1828
|
```tsx title="src/modules/account/components/register-phone/index.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
1829
|
return ( |
|
1830
|
<div |
|
1831
|
className="max-w-sm flex flex-col items-center" |
|
1832
|
data-testid="register-page" |
|
1833
|
> |
|
1834
|
<h1 className="text-large-semi uppercase mb-6"> |
|
1835
|
Become a Medusa Store Member |
|
1836
|
</h1> |
|
1837
|
<p className="text-center text-base-regular text-ui-fg-base mb-4"> |
|
1838
|
Create your Medusa Store Member profile, and get access to an enhanced |
|
1839
|
shopping experience. |
|
1840
|
</p> |
|
1841
|
<form className="w-full flex flex-col" onSubmit={handleSubmit}> |
|
1842
|
<div className="flex flex-col w-full gap-y-2"> |
|
1843
|
<Input |
|
1844
|
label="First name" |
|
1845
|
name="first_name" |
|
1846
|
required |
|
1847
|
autoComplete="given-name" |
|
1848
|
data-testid="first-name-input" |
|
1849
|
value={firstName} |
|
1850
|
onChange={(e) => setFirstName(e.target.value)} |
|
1851
|
/> |
|
1852
|
<Input |
|
1853
|
label="Last name" |
|
1854
|
name="last_name" |
|
1855
|
required |
|
1856
|
autoComplete="family-name" |
|
1857
|
data-testid="last-name-input" |
|
1858
|
value={lastName} |
|
1859
|
onChange={(e) => setLastName(e.target.value)} |
|
1860
|
/> |
|
1861
|
<PhoneInput |
|
1862
|
placeholder="Enter phone number" |
|
1863
|
value={phone} |
|
1864
|
onChange={(value) => setPhone(value as string)} |
|
1865
|
name="phone" |
|
1866
|
required |
|
1867
|
autoComplete="off" |
|
1868
|
// @ts-ignore |
|
1869
|
defaultCountry={countryCode.toUpperCase()} |
|
1870
|
/> |
|
1871
|
</div> |
|
1872
|
<ErrorMessage error={error} data-testid="register-error" /> |
|
1873
|
<span className="text-center text-ui-fg-base text-small-regular mt-6"> |
|
1874
|
By creating an account, you agree to Medusa Store's{" "} |
|
1875
|
<LocalizedClientLink |
|
1876
|
href="/content/privacy-policy" |
|
1877
|
className="underline" |
|
1878
|
> |
|
1879
|
Privacy Policy |
|
1880
|
</LocalizedClientLink>{" "} |
|
1881
|
and{" "} |
|
1882
|
<LocalizedClientLink |
|
1883
|
href="/content/terms-of-use" |
|
1884
|
className="underline" |
|
1885
|
> |
|
1886
|
Terms of Use |
|
1887
|
</LocalizedClientLink> |
|
1888
|
. |
|
1889
|
</span> |
|
1890
|
<Button |
|
1891
|
className="w-full mt-6" |
|
1892
|
type="submit" |
|
1893
|
size="large" |
|
1894
|
variant="primary" |
|
1895
|
isLoading={loading} |
|
1896
|
> |
|
1897
|
Join |
|
1898
|
</Button> |
|
1899
|
</form> |
|
1900
|
<span className="text-center text-ui-fg-base text-small-regular mt-6"> |
|
1901
|
Already a member?{" "} |
|
1902
|
<button |
|
1903
|
onClick={() => setCurrentView(LOGIN_VIEW.SIGN_IN_PHONE)} |
|
1904
|
className="underline" |
|
1905
|
> |
|
1906
|
Sign in |
|
1907
|
</button> |
|
1908
|
. |
|
1909
|
</span> |
|
1910
|
</div> |
|
1911
|
) |
|
1912
|
``` |
|
1913
|
|
|
1914
|
You render the registration form with input fields for the first name, last name, and phone number. |
|
1915
|
|
|
1916
|
For the phone number input, you use the `PhoneInput` component from the `react-phone-number-input` package. You set the `defaultCountry` prop to the country code retrieved from the URL parameters. |
|
1917
|
|
|
1918
|
You also show a submit button that calls the `handleSubmit` function when clicked, and a button to switch to the login form. |
|
1919
|
|
|
1920
|
#### Add to Login Template |
|
1921
|
|
|
1922
|
Next, you'll add the `RegisterPhone` component to the login template. |
|
1923
|
|
|
1924
|
In `src/modules/account/templates/login-template.tsx`, add the following import: |
|
1925
|
|
|
1926
|
```tsx title="src/modules/account/templates/login-template.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
1927
|
import RegisterPhone from "@modules/account/components/register-phone" |
|
1928
|
``` |
|
1929
|
|
|
1930
|
Then, change the `return` statement of the `LoginTemplate` component to the following: |
|
1931
|
|
|
1932
|
```tsx title="src/modules/account/templates/login-template.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
1933
|
return ( |
|
1934
|
<div className="w-full flex justify-start px-8 py-8"> |
|
1935
|
{currentView === "sign-in" ? ( |
|
1936
|
<Login setCurrentView={setCurrentView} /> |
|
1937
|
) : currentView === "register" ? ( |
|
1938
|
<Register setCurrentView={setCurrentView} /> |
|
1939
|
) : currentView === "register-phone" ? ( |
|
1940
|
<RegisterPhone setCurrentView={setCurrentView} /> |
|
1941
|
) : ( |
|
1942
|
// TODO: Add login phone view |
|
1943
|
<></> |
|
1944
|
)} |
|
1945
|
</div> |
|
1946
|
) |
|
1947
|
``` |
|
1948
|
|
|
1949
|
You show the registration form when the `currentView` is set to `register-phone`. You'll also add the login form later. |
|
1950
|
|
|
1951
|
### h. Add Login Form |
|
1952
|
|
|
1953
|
Next, you'll add a login form that allows the customer to log in using their phone number. |
|
1954
|
|
|
1955
|
To create the form, create the file `src/modules/account/components/login-phone/index.tsx` with the following content: |
|
1956
|
|
|
1957
|
export const loginPhoneHighlights = [ |
|
1958
|
["18", "phone", "The phone number entered by the customer."], |
|
1959
|
["19", "error", "The error message to show if the login fails."], |
|
1960
|
["20", "loading", "A boolean indicating whether the login is in progress."], |
|
1961
|
["21", "enterOtp", "A boolean indicating whether to show the OTP form."], |
|
1962
|
["22", "countryCode", "The country code of the customer."], |
|
1963
|
["24", "handleSubmit", "Authenticate customer on form submission."], |
|
1964
|
["37", "enterOtp", "Show the OTP form after successful login."], |
|
1965
|
] |
|
1966
|
|
|
1967
|
```tsx title="src/modules/account/components/login-phone/index.tsx" badgeLabel="Storefront" badgeColor="blue" highlights={loginPhoneHighlights} |
|
1968
|
"use client" |
|
1969
|
|
|
1970
|
import { authenticateWithPhone } from "@lib/data/customer" |
|
1971
|
import { LOGIN_VIEW } from "@modules/account/templates/login-template" |
|
1972
|
import ErrorMessage from "@modules/checkout/components/error-message" |
|
1973
|
import { useState } from "react" |
|
1974
|
import "react-phone-number-input/style.css" |
|
1975
|
import PhoneInput from "react-phone-number-input" |
|
1976
|
import { Otp } from "../otp" |
|
1977
|
import { useParams } from "next/navigation" |
|
1978
|
import { Button } from "@medusajs/ui" |
|
1979
|
|
|
1980
|
type Props = { |
|
1981
|
setCurrentView: (view: LOGIN_VIEW) => void |
|
1982
|
} |
|
1983
|
|
|
1984
|
const LoginPhone = ({ setCurrentView }: Props) => { |
|
1985
|
const [phone, setPhone] = useState("") |
|
1986
|
const [error, setError] = useState("") |
|
1987
|
const [loading, setLoading] = useState(false) |
|
1988
|
const [enterOtp, setEnterOtp] = useState(false) |
|
1989
|
const { countryCode } = useParams() as { countryCode: string } |
|
1990
|
|
|
1991
|
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { |
|
1992
|
e.preventDefault() |
|
1993
|
setLoading(true) |
|
1994
|
const response = await authenticateWithPhone(phone) |
|
1995
|
setLoading(false) |
|
1996
|
if (typeof response === "string") { |
|
1997
|
setError(response) |
|
1998
|
return |
|
1999
|
} |
|
2000
|
|
|
2001
|
setEnterOtp(true) |
|
2002
|
} |
|
2003
|
|
|
2004
|
if (enterOtp) { |
|
2005
|
return <Otp phone={phone} /> |
|
2006
|
} |
|
2007
|
|
|
2008
|
// TODO render form |
|
2009
|
} |
|
2010
|
|
|
2011
|
export default LoginPhone |
|
2012
|
``` |
|
2013
|
|
|
2014
|
You create a `LoginPhone` component that accepts a `setCurrentView` prop to switch between the login and registration views. |
|
2015
|
|
|
2016
|
In the component, you define the following state variables: |
|
2017
|
|
|
2018
|
- `phone`: The phone number entered by the customer. |
|
2019
|
- `error`: The error message to show if the login fails. |
|
2020
|
- `loading`: A boolean indicating whether the login is in progress. |
|
2021
|
- `enterOtp`: A boolean indicating whether to show the OTP form. This is enabled after the form is submitted. |
|
2022
|
- `countryCode`: The country code of the customer, which is retrieved from the URL parameters. You'll use this to show the phone input with a default selected country. |
|
2023
|
|
|
2024
|
You also define a `handleSubmit` function that handles the form submission. It calls the `authenticateWithPhone` function to authenticate the customer using their phone number. Then, it enables `enterOtp` to show the OTP form. |
|
2025
|
|
|
2026
|
#### Render Login Form |
|
2027
|
|
|
2028
|
Next, you'll render the login form with the input field and the submit button. |
|
2029
|
|
|
2030
|
Replace the `TODO` with the following: |
|
2031
|
|
|
2032
|
```tsx title="src/modules/account/components/login-phone/index.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
2033
|
return ( |
|
2034
|
<div |
|
2035
|
className="max-w-sm w-full flex flex-col items-center" |
|
2036
|
data-testid="login-page" |
|
2037
|
> |
|
2038
|
<h1 className="text-large-semi uppercase mb-6">Welcome back</h1> |
|
2039
|
<p className="text-center text-base-regular text-ui-fg-base mb-8"> |
|
2040
|
Sign in to access an enhanced shopping experience. |
|
2041
|
</p> |
|
2042
|
<form className="w-full" onSubmit={handleSubmit}> |
|
2043
|
<div className="flex flex-col w-full gap-y-2"> |
|
2044
|
<PhoneInput |
|
2045
|
placeholder="Enter phone number" |
|
2046
|
value={phone} |
|
2047
|
onChange={(value) => setPhone(value as string)} |
|
2048
|
name="phone" |
|
2049
|
required |
|
2050
|
// @ts-ignore |
|
2051
|
defaultCountry={countryCode.toUpperCase()} |
|
2052
|
/> |
|
2053
|
</div> |
|
2054
|
{error && <ErrorMessage error={error} data-testid="login-error-message" />} |
|
2055
|
<Button |
|
2056
|
className="w-full mt-6" |
|
2057
|
disabled={loading} |
|
2058
|
type="submit" |
|
2059
|
size="large" |
|
2060
|
variant="primary" |
|
2061
|
isLoading={loading} |
|
2062
|
> |
|
2063
|
Sign in |
|
2064
|
</Button> |
|
2065
|
</form> |
|
2066
|
<span className="text-center text-ui-fg-base text-small-regular mt-6"> |
|
2067
|
Not a member?{" "} |
|
2068
|
<button |
|
2069
|
onClick={() => setCurrentView(LOGIN_VIEW.REGISTER_PHONE)} |
|
2070
|
className="underline" |
|
2071
|
data-testid="register-button" |
|
2072
|
> |
|
2073
|
Join us |
|
2074
|
</button> |
|
2075
|
. |
|
2076
|
</span> |
|
2077
|
</div> |
|
2078
|
) |
|
2079
|
``` |
|
2080
|
|
|
2081
|
You render the login form with an input field for the phone number. You also show a submit button that calls the `handleSubmit` function when clicked. |
|
2082
|
|
|
2083
|
### i. Add to Login Template |
|
2084
|
|
|
2085
|
Next, you'll add the `LoginPhone` component to the login template. |
|
2086
|
|
|
2087
|
In `src/modules/account/templates/login-template.tsx`, add the following import: |
|
2088
|
|
|
2089
|
```tsx title="src/modules/account/templates/login-template.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
2090
|
import LoginPhone from "../components/login-phone" |
|
2091
|
``` |
|
2092
|
|
|
2093
|
Next, in the `LoginTemplate` component, change the default value of the `currentView` state to `LOGIN_VIEW.SIGN_IN_PHONE`: |
|
2094
|
|
|
2095
|
```tsx title="src/modules/account/templates/login-template.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
2096
|
const [currentView, setCurrentView] = useState(LOGIN_VIEW.SIGN_IN_PHONE) |
|
2097
|
``` |
|
2098
|
|
|
2099
|
This ensures the phone login form is shown by default. |
|
2100
|
|
|
2101
|
Finally, replace the `return` statement of the `LoginTemplate` component to the following: |
|
2102
|
|
|
2103
|
```tsx title="src/modules/account/templates/login-template.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
2104
|
return ( |
|
2105
|
<div className="w-full flex justify-start px-8 py-8"> |
|
2106
|
{currentView === "sign-in" ? ( |
|
2107
|
<Login setCurrentView={setCurrentView} /> |
|
2108
|
) : currentView === "register" ? ( |
|
2109
|
<Register setCurrentView={setCurrentView} /> |
|
2110
|
) : currentView === "register-phone" ? ( |
|
2111
|
<RegisterPhone setCurrentView={setCurrentView} /> |
|
2112
|
) : ( |
|
2113
|
<LoginPhone setCurrentView={setCurrentView} /> |
|
2114
|
)} |
|
2115
|
</div> |
|
2116
|
) |
|
2117
|
``` |
|
2118
|
|
|
2119
|
You show the login form when the `currentView` is set to `sign-in-phone`. |
|
2120
|
|
|
2121
|
### Test it Out |
|
2122
|
|
|
2123
|
You can now test out the phone authentication feature in the Next.js Starter Storefront. |
|
2124
|
|
|
2125
|
First, start the Medusa application by running the following command in the Medusa project's directory: |
|
2126
|
|
|
2127
|
```bash npm2yarn badgeLabel="Medusa Application" badgeColor="green" |
|
2128
|
npm run dev |
|
2129
|
``` |
|
2130
|
|
|
2131
|
Then, start the Next.js Starter Storefront by running the following command in the storefront project's directory: |
|
2132
|
|
|
2133
|
```bash npm2yarn badgeLabel="Storefront" badgeColor="blue" |
|
2134
|
npm run dev |
|
2135
|
``` |
|
2136
|
|
|
2137
|
Open your browser, navigate to `http://localhost:8000`, and click on the "Account" link at the top right. This will show the login form with just the phone number input. |
|
2138
|
|
|
2139
|
 |
|
2140
|
|
|
2141
|
You can also switch to the registration form by clicking on the "Join" link below the login form. |
|
2142
|
|
|
2143
|
 |
|
2144
|
|
|
2145
|
You can try to login with the account you created before, or register with a new one. Once successful, you'll see the OTP form to enter the OTP you received as SMS. |
|
2146
|
|
|
2147
|
 |
|
2148
|
|
|
2149
|
After you enter the six digits, you'll be logged in and you'll see your profile page. |
|
2150
|
|
|
2151
|
 |
|
2152
|
|
|
2153
|
--- |
|
2154
|
|
|
2155
|
## Step 5: Disallow Phone Updates |
|
2156
|
|
|
2157
|
The phone authentication feature is now complete, but there are two improvements you can make: |
|
2158
|
|
|
2159
|
1. Show the phone number in the profile page: Currently, it shows the email address, which is a fake address you've set. |
|
2160
|
2. Disable phone and email updates: Currently, the customer can update their phone number, which is not allowed for phone authentication. |
|
2161
|
|
|
2162
|
### a. Show Phone Number in Profile Page |
|
2163
|
|
|
2164
|
To show the phone number in the profile page instead of the email, in `src/modules/account/components/overview/index.tsx`, find the following in the `return` statement: |
|
2165
|
|
|
2166
|
```tsx title="src/modules/account/components/overview/index.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
2167
|
<span |
|
2168
|
className="font-semibold" |
|
2169
|
data-testid="customer-email" |
|
2170
|
data-value={customer?.email} |
|
2171
|
> |
|
2172
|
{customer?.email} |
|
2173
|
</span> |
|
2174
|
``` |
|
2175
|
|
|
2176
|
And replace it with the following: |
|
2177
|
|
|
2178
|
```tsx title="src/modules/account/components/overview/index.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
2179
|
<span |
|
2180
|
className="font-semibold" |
|
2181
|
data-testid="customer-phone" |
|
2182
|
data-value={customer?.phone} |
|
2183
|
> |
|
2184
|
{customer?.phone} |
|
2185
|
</span> |
|
2186
|
``` |
|
2187
|
|
|
2188
|
If you check the profile page now, you'll see the phone number instead of the email address at the top right. |
|
2189
|
|
|
2190
|
 |
|
2191
|
|
|
2192
|
### b. Remove Email and Phone Fields |
|
2193
|
|
|
2194
|
Next, you'll remove the fields to update email and phone number from the profile page. |
|
2195
|
|
|
2196
|
In `src/app/[countryCode]/(main)/account/@dashboard/profile/page.tsx`, find the following lines to remove from the `return` statement: |
|
2197
|
|
|
2198
|
```tsx title="src/app/[countryCode]/(main)/account/@dashboard/profile/page.tsx" badgeLabel="Storefront" badgeColor="blue" |
|
2199
|
<div className="flex flex-col gap-y-8 w-full"> |
|
2200
|
{/* ... */} |
|
2201
|
{/* Remove the following */} |
|
2202
|
<Divider /> |
|
2203
|
<ProfileEmail customer={customer} /> |
|
2204
|
<Divider /> |
|
2205
|
<ProfilePhone customer={customer} /> |
|
2206
|
{/* ... */} |
|
2207
|
</div> |
|
2208
|
``` |
|
2209
|
|
|
2210
|
If you go to your profile page and click on "Profile" in the sidebar, the email and phone number sections will be removed. |
|
2211
|
|
|
2212
|
 |
|
2213
|
|
|
2214
|
### c. Disable Phone Updates in Medusa |
|
2215
|
|
|
2216
|
While removing the email and phone fields from the profile page prevents customers using the storefront from updating their phone number, it doesn't prevent them from updating it using Medusa's API. |
|
2217
|
|
|
2218
|
In this section, you'll add a [middleware](!docs!/learn/fundamentals/api-routes/middlewares) to the `/store/customers/me` API route that prevents customers from updating their phone number. |
|
2219
|
|
|
2220
|
A middleware is a function that's executed whenever a request is sent to an API route. It's executed before the route handler, allowing you to validate requests, apply authentication guards, and more. |
|
2221
|
|
|
2222
|
<Note> |
|
2223
|
|
|
2224
|
Learn more in the [Middlewares](!docs!/learn/fundamentals/api-routes/middlewares) documentation. |
|
2225
|
|
|
2226
|
</Note> |
|
2227
|
|
|
2228
|
To add a middleware in your Medusa application, create the file `src/api/middlewares.ts` with the following content: |
|
2229
|
|
|
2230
|
```ts title="src/api/middlewares.ts" badgeLabel="Medusa Application" badgeColor="green" |
|
2231
|
import { defineMiddlewares } from "@medusajs/framework/http" |
|
2232
|
|
|
2233
|
export default defineMiddlewares({ |
|
2234
|
routes: [ |
|
2235
|
{ |
|
2236
|
matcher: "/store/customers/me", |
|
2237
|
method: ["POST"], |
|
2238
|
middlewares: [ |
|
2239
|
async (req, res, next) => { |
|
2240
|
const { phone } = req.body as Record<string, string> |
|
2241
|
|
|
2242
|
if (phone) { |
|
2243
|
return res.status(400).json({ |
|
2244
|
error: "Phone number is not allowed to be updated", |
|
2245
|
}) |
|
2246
|
} |
|
2247
|
|
|
2248
|
next() |
|
2249
|
}, |
|
2250
|
], |
|
2251
|
}, |
|
2252
|
], |
|
2253
|
}) |
|
2254
|
``` |
|
2255
|
|
|
2256
|
You define middlewares using the `defineMiddlewares` function. It accepts an object having a `routes` property that holds all middlewares applied to API routes. |
|
2257
|
|
|
2258
|
Each object in `routes` has the following properties: |
|
2259
|
|
|
2260
|
- `matcher`: The API route path to apply the middleware on. You set it to `/store/customers/me`. |
|
2261
|
- `method`: The HTTP method to apply the middleware to. You set it to `POST` so that the middleware is applied only on `POST` requests sent to the `/store/customers/me` route. |
|
2262
|
- `middlewares`: An array of middlewares to apply on the route. You add a middleware that throws an error if the request body contains a `phone` property. This prevents customers from updating their phone number using the API. |
|
2263
|
|
|
2264
|
Any `POST` request to the `/store/customers/me` route will now be validated to ensure it's not updating the phone number. |
|
2265
|
|
|
2266
|
--- |
|
2267
|
|
|
2268
|
## Next Steps |
|
2269
|
|
|
2270
|
You've now implemented phone authentication in Medusa with Twilio integration. You can further customize the phone authentication feature based on your business use case. |
|
2271
|
|
|
2272
|
### Authenticate Other Actor Types |
|
2273
|
|
|
2274
|
This tutorial focused on authenticating customers using their phone number. However, you can also authenticate other actor types, such as admin users and vendors. |
|
2275
|
|
|
2276
|
To do that, first, enable the `phone-auth` authentication strategy in `medusa-config.ts` for the actor types. For example: |
|
2277
|
|
|
2278
|
```ts title="medusa-config.ts" |
|
2279
|
module.exports = defineConfig({ |
|
2280
|
projectConfig: { |
|
2281
|
// ... |
|
2282
|
http: { |
|
2283
|
// ... |
|
2284
|
authMethodsPerActor: { |
|
2285
|
user: ["emailpass", "phone-auth"], |
|
2286
|
customer: ["emailpass", "phone-auth"], |
|
2287
|
vendor: ["emailpass", "phone-auth"], |
|
2288
|
}, |
|
2289
|
}, |
|
2290
|
}, |
|
2291
|
}) |
|
2292
|
``` |
|
2293
|
|
|
2294
|
Then, when sending requests to the authentication API routes mentioned in the [Test Out Phone Authentication](#test-out-phone-authentication) section, replace `customer` in the API route paths with the actor type you want to authenticate: |
|
2295
|
|
|
2296
|
- `/auth/customer/phone-auth/register` -> `/auth/user/phone-auth/register` |
|
2297
|
- `/auth/customer/phone-auth` -> `/auth/user/phone-auth` |
|
2298
|
- `/auth/customer/phone-auth/callback` -> `/auth/user/phone-auth/callback` |
|
2299
|
|
|
2300
|
Finally, update the UI to show the phone authentication option for the actor type you want to authenticate. This depends on the UI you're using, but you can follow an approach similar to the Next.js Starter Storefront customizations. |
|
2301
|
|
|
2302
|
<Note> |
|
2303
|
|
|
2304
|
The login form of Medusa Admin can't be customized, so you'll have to build a custom admin dashboard to support phone authentication for admin users. |
|
2305
|
|
|
2306
|
</Note> |
|
2307
|
|
|
2308
|
### Learn More about Medusa |
|
2309
|
|
|
2310
|
If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth learning of all the concepts you've used in this guide and more. |
|
2311
|
|
|
2312
|
To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx). |
|
2313
|
|
|
2314
|
### Troubleshooting |
|
2315
|
|
|
2316
|
If you encounter issues during your development, check out the [troubleshooting guides](../../../troubleshooting/page.mdx). |
|
2317
|
|
|
2318
|
### Getting Help |
|
2319
|
|
|
2320
|
If you encounter issues not covered in the troubleshooting guides: |
|
2321
|
|
|
2322
|
1. Visit the [Medusa GitHub repository](https://github.com/medusajs/medusa) to report issues or ask questions. |
|
2323
|
2. Join the [Medusa Discord community](https://discord.gg/medusajs) for real-time support from community members. |
|
2324
|
3. Contact the [sales team](https://medusajs.com/contact/) to get help from the Medusa team. |