docs: added docs for reset password (#9306)

- Added to docs on implementing auth flows using the module and API routes how to update a user's password
- Added guide on how to send a notification when a password token is generated
- Added a guide on implementing reset password flow in storefront
- Added OAS for the `/update` and `/reset-password` routes + generated specs for the API reference
This commit is contained in:
Shahed Nasser
2024-10-07 08:04:01 +00:00
committed by GitHub
parent adb3a8246a
commit 781d0ca624
38 changed files with 1479 additions and 40 deletions
@@ -8,7 +8,7 @@ export const metadata = {
# {metadata.title}
In this document, you'll learn how to use the Auth Module's main service's methods to implement an authentication flow.
In this document, you'll learn how to use the Auth Module's main service's methods to implement authentication flows and reset a user's password.
## Authentication Methods
@@ -149,3 +149,32 @@ if (success) {
If the returned `success` property is `true`, the authentication with the third-party provider was successful.
![Diagram showcasing the second part of the third-party authentication flow](https://res.cloudinary.com/dza7lstvk/image/upload/v1711375123/Medusa%20Resources/third-party-auth-2_kmjxju.jpg)
---
## Reset Password
To update a user's password or other authentication details, use the `updateProvider` method of the Auth Module's main service. It calls the `update` method of the specified authentication provider.
For example:
```ts
const { success } = await authModuleService.update(
"emailpass",
// passed to the auth provider
{
email: "user@example.com",
password: "supersecret",
}
)
if (success) {
// password reset successfully
}
```
The method accepts as a first parameter the ID of the provider, and as a second parameter the data necessary to reset the password.
In the example above, you use the `emailpass` provider, so you have to pass an object having an `email` and `password` properties.
If the returned `success` property is `true`, the password has reset successfully.
@@ -4,11 +4,11 @@ export const metadata = {
# {metadata.title}
In this document, you'll learn about the authentication routes and how to use them to create or log-in users.
In this document, you'll learn about the authentication routes and how to use them to create and log-in users, and reset their password.
<Note>
These routes are added by Medusa's application layer, not the Auth Module.
These routes are added by Medusa's HTTP layer, not the Auth Module.
</Note>
@@ -117,7 +117,7 @@ Use that token in the header of subsequent requests to send authenticated reques
---
## Auth Route
## Login Route
The Medusa application defines an API route at `/auth/{actor_type}/{provider}` that authenticates a user of an actor type. It returns a JWT token that can be passed in [the header of subsequent requests](!api!/store#authentication) to send authenticated requests.
@@ -238,4 +238,106 @@ If the token was refreshed successfully, you'll receive a `token` field in the r
}
```
Use that token in the header of subsequent requests to send authenticated requests.
Use that token in the header of subsequent requests to send authenticated requests.
---
## Reset Password Routes
To reset a user's password:
1. Generate a token using the [Generate Reset Password Token API route](#generate-reset-password-token-route).
- The API route emits the `auth.password_reset` event, passing the token in the payload.
- You can create a subscriber, as seen in [this guide](../reset-password/page.mdx), that listens to the event and send a notification to the user.
2. Pass the token to the [Reset Password API route](#reset-password-route) to reset the password.
- The URL in the user's notification should direct them to a frontend URL, which sends a request to this route.
<Note title="Example">
[Storefront Development: How to Reset a Customer's Password.](../../../storefront-development/customers/reset-password/page.mdx)
</Note>
### Generate Reset Password Token Route
The Medusa application defines an API route at `/auth/{actor_type}/{auth_provider}/reset-password` that emits the `auth.password_reset` event, passing the token in the payload.
```bash
curl -X POST http://localhost:9000/auth/{actor_type}/{providers}/reset-password
-H 'Content-Type: application/json' \
--data-raw '{
"identifier": "Whitney_Schultz@gmail.com"
}'
```
<Note>
This API route is useful for providers like `emailpass` that store a user's password and use it for authentication.
</Note>
#### Path Parameters
Its path parameters are:
- `{actor_type}`: the actor type of the user you're authenticating. For example, `customer`.
- `{provider}`: the auth provider to handle the authentication. For example, `emailpass`.
#### Request Body Parameters
This route accepts in the request body an object having the following property:
- `identifier`: The user's identifier in the specified auth provider. For example, for the `emailpass` auth provider, you pass the user's email.
#### Response Fields
If the authentication is successful, the request returns a `201` response code.
### Reset Password Route
The Medusa application defines an API route at `/auth/{actor_type}/{auth_provider}/update` that accepts a token and, if valid, updates the user's password.
```bash
curl -X POST http://localhost:9000/auth/{actor_type}/{providers}/update?token=123
-H 'Content-Type: application/json' \
--data-raw '{
"email": "Whitney_Schultz@gmail.com",
"password": "supersecret"
}'
```
<Note>
This API route is useful for providers like `emailpass` that store a user's password and use it for logging them in.
</Note>
#### Path Parameters
Its path parameters are:
- `{actor_type}`: the actor type of the user you're authenticating. For example, `customer`.
- `{provider}`: the auth provider to handle the authentication. For example, `emailpass`.
#### Query Parameters
The route accepts a `token` query parameter, which is the token generated using the [Generate Reset Password Token route](#generate-reset-password-token-route).
### Request Body Parameters
This route accepts in the request body an object that has the data necessary for the provider to update the user's password.
For the `emailpass` provider, you must pass the following properties:
- `email`: The user's email.
- `password`: The new password.
### Response Fields
If the authentication is successful, the request returns an object with a `success` property set to `true`:
```json
{
"success": "true"
}
```
@@ -0,0 +1,128 @@
import { Prerequisites } from "docs-ui"
export const metadata = {
title: `How to Handle Password Reset Token Event`,
}
# {metadata.title}
In this guide, you'll learn how to handle the `auth.password_reset` event, which is emitted when a request is sent to the [Generate Reset Password Token API route](../authentication-route/page.mdx#generate-reset-password-token-route), to send reset instructions to the user.
<Prerequisites
items={[
{
text: "A notification provider module, such as SendGrid",
link: "/architectural-modules/notification/sendgrid"
}
]}
/>
## 1. Create Subscriber
The first step is to create a subscriber that listens to the `auth.password_reset` and sends the user a notification with instructions to reset their password.
Create the file `src/subscribers/handle-reset.ts` with the following content:
export const highlights=[
["8", "data", "The data payload of the event."],
["9", "entity_id", "The user's identifier, which is the email when using the `emailpass` provider."],
["10", "token", "The password reset token."],
["11", "actor_type", "The user's actor type."],
["19", "urlPrefix", "Set the page's URL based on the user's actor type."],
["21", "createNotifications", "Send a notification to the user."],
["23", `"email"`, "The channel to send the notification through."],
["24", "template", "The template defined in the third-party provider."],
["25", "data", "The data to pass to the template in the third-party provider."],
["27", "url", "The frontend URL to redirect the user to reset their password."]
]
```ts title="src/subscribers/handle-reset.ts" collapsibleLines="1-6" expandMoreLabel="Show Imports"
import {
SubscriberArgs,
type SubscriberConfig,
} from "@medusajs/medusa"
import { Modules } from "@medusajs/framework/utils"
export default async function resetPasswordTokenHandler({
event: { data: {
entity_id: email,
token,
actor_type,
} },
container,
}: SubscriberArgs<{ entity_id: string, token: string, actor_type: string }>) {
const notificationModuleService = container.resolve(
Modules.NOTIFICATION
)
const urlPrefix = actor_type === "customer" ? "https://storefront.com" : "https://admin.com"
await notificationModuleService.createNotifications({
to: email,
channel: "email",
template: "reset-password-template",
data: {
// a URL to a frontend application
url: `${urlPrefix}/reset-password?token=${token}&email=${email}`,
},
})
}
export const config: SubscriberConfig = {
event: "auth.password_reset",
}
```
You subscribe to the `auth.password_reset` event. The event has a data payload object with the following properties:
- `entity_id`: The identifier of the user. When using the `emailpass` provider, it's the user's email.
- `token`: The token to reset the user's password.
- `actor_type`: The user's actor type. For example, if the user is a customer, the `actor_type` is `customer`. If it's an admin user, the `actor_type` is `user`.
In the subscriber, you:
- Decide the frontend URL based on whether the user is a customer or admin user by checking the value of `actor_type`.
- Resolve the Notification Module and use its `createNotifications` method to send the notification.
- You pass to the `createNotifications` method an object having the following properties:
- `to`: The identifier to send the notification to, which in this case is the email.
- `channel`: The channel to send the notification through, which in this case is email.
- `template`: The template ID in the third-party service.
- `data`: The data payload to pass to the template. You pass the URL to redirect the user to. You must pass the token and email in the URL so that the frontend can send them later to the Medusa application when reseting the password.
---
## 2. Test it Out: Generate Reset Password Token
To test the subscriber out, send a request to the `/auth/{actor_type}/{auth_provider}/reset-password` API route, replacing `{actor_type}` and `{auth_provider}` with the user's actor type and provider used for authentication respectively.
For example, to generate a reset password token for an admin user using the `emailpass` provider, send the following request:
```bash
curl --location 'http://localhost:9000/auth/user/emailpass/reset-password' \
--header 'Content-Type: application/json' \
--data-raw '{
"identifier": "admin-test@gmail.com"
}'
```
In the request body, you must pass an `identifier` parameter. Its value is the user's identifier, which is the email in this case.
If the token is generated successfully, the request returns a response with `201` status code. In the terminal, you'll find the following message indicating that the `auth.password_reset` event was emitted and your subscriber ran:
```plain
info: Processing auth.password_reset which has 1 subscribers
```
The notification is sent to the user with the frontend URL to enter a new password.
---
## Next Steps: Implementing Frontend
In your frontend, you must have a page that accepts `token` and `email` query parameters.
The page shows the user password fields to enter their new password, then submits the new password, token, and email to the [Reset Password Route](../authentication-route/page.mdx#reset-password-route).
### Examples
- [Storefront Guide: Reset Customer Password](../../../storefront-development/customers/reset-password/page.mdx)