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)
@@ -0,0 +1,285 @@
import { CodeTabs, CodeTab, Prerequisites } from "docs-ui"
export const metadata = {
title: `Reset Customer Password in Storefront`,
}
# {metadata.title}
Customers reset their password if they forget it.
To implement the flow to reset a customer's password, you need two pages in your storefront:
1. A page to request the password reset.
2. A page that prompts the customer to enter a new password.
---
## 1. Request Reset Password Page
The request password reset page prompts the customer to enter their email. Then, it sends a request to the [Request Reset Password Token API route](!api!/store#auth_postactor_typeauth_providerresetpassword) to send the customer an email with the URL to reset their password.
<Prerequisites
items={[
{
text: "While it's not required, it's recommended to implement the subscriber that sends the customer an email with the URL to reset their password.",
link: "/commerce-modules/auth/reset-password"
}
]}
/>
For example:
<CodeTabs group="store-request">
<CodeTab label="Fetch API" value="fetch">
export const fetchHighlights = [
["5", "email", "Assuming the email is retrieved from an input field."],
["10", "fetch", "Send a request to send the token to the customer."],
["17", "identifier", "Pass the email in the `identifier` request body parameter."]
]
```ts highlights={fetchHighlights}
const handleSubmit = async (
e: React.FormEvent<HTMLFormElement> // or other form event
) => {
e.preventDefault()
if (!email) {
alert("Email is required")
return
}
fetch(`http://localhost:9000/auth/customer/emailpass/reset-password`, {
credentials: "include",
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
identifier: email,
}),
})
.then(() => {
alert("If an account exists with the specified email, it'll receive instructions to reset the password.")
})
}
```
</CodeTab>
<CodeTab label="React" value="react">
export const highlights = [
["19", "fetch", "Send a request to send the token to the customer."],
["26", "identifier", "Pass the email in the `identifier` request body parameter."]
]
```tsx highlights={highlights}
"use client" // include with Next.js 13+
import { useState } from "react"
export default function RequestResetPassword() {
const [loading, setLoading] = useState(false)
const [email, setEmail] = useState("")
const handleSubmit = async (
e: React.FormEvent<HTMLFormElement>
) => {
e.preventDefault()
if (!email) {
alert("Email is required")
return
}
setLoading(true)
fetch(`http://localhost:9000/auth/customer/emailpass/reset-password`, {
credentials: "include",
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
identifier: email,
}),
})
.then(() => {
alert("If an account exists with the specified email, it'll receive instructions to reset the password.")
setLoading(false)
})
}
return (
<form onSubmit={handleSubmit}>
<label>Email</label>
<input
placeholder="Email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<button type="submit" disabled={loading}>
Request Password Reset
</button>
</form>
)
}
```
</CodeTab>
</CodeTabs>
In this example, you send a request to `http://localhost:9000/auth/customer/emailpass/reset-password` API route when the form that has the email field is submitted.
In the request body, you pass an `identifier` parameter, which is the customer's email.
<Note title="Tip">
The Request Reset Password Token API route returns a successful response always, even if the customer's email doesn't exist. However, the customer only receives an email if they have an account with that email.
</Note>
---
## 2. Reset Password Page
The reset password page is the URL used in the email sent to the customer. It receives a `token` and `email` query parameters, prompts the customer for a new password, and sends a request to the [Reset Password API route](!api!/store#auth_postactor_typeauth_providerupdate).
<Note>
If you followed [this guide](../../../commerce-modules/auth/reset-password/page.mdx) to set up a subscriber that sends the customer an email, make sure to use the URL of this page in the notification's data payload.
</Note>
For example:
<CodeTabs group="store-request">
<CodeTab label="Fetch API" value="fetch">
export const resetPasswordFetchHighlights = [
["2", "token", "Receive the token from a query parameter."],
["3", "email", "Receive the email from a query parameter."],
["9", "password", "Assuming the password is retrieved from an input field."],
["14", "fetch", "Send a request to update the customer's password."],
["14", "token", "Pass the token as a query parameter."],
["20", "body", "Pass the email and password in the request body."]
]
```ts highlights={resetPasswordFetchHighlights}
const queryParams = new URLSearchParams(window.location.search)
const token = queryParams.get("token")
const email = queryParams.get("email")
const handleSubmit = async (
e: React.FormEvent<HTMLFormElement>
) => {
e.preventDefault()
if (!password) {
alert("Password is required")
return
}
fetch(`http://localhost:9000/auth/customer/emailpass/update?token=${token}`, {
credentials: "include",
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email,
password,
}),
})
.then((res) => res.json())
.then(({ success }) => {
alert(success ? "Password reset successfully!" : "Couldn't reset password")
})
}
```
</CodeTab>
<CodeTab label="React" value="react">
export const resetPasswordHighlights = [
["18", "token", "Receive the token from a query parameter."],
["21", "email", "Receive the email from a query parameter."],
["35", "fetch", "Send a request to update the customer's password."],
["35", "token", "Pass the token as a query parameter."],
["41", "body", "Pass the email and password in the request body."]
]
```tsx highlights={resetPasswordHighlights}
"use client" // include with Next.js 13+
import { useMemo, useState } from "react"
export default function ResetPassword() {
const [loading, setLoading] = useState(false)
const [password, setPassword] = useState("")
// for other than Next.js
const searchParams = useMemo(() => {
if (typeof window === "undefined") {
return
}
return new URLSearchParams(
window.location.search
)
}, [])
const token = useMemo(() => {
return searchParams?.get("token")
}, [searchParams])
const email = useMemo(() => {
return searchParams?.get("email")
}, [searchParams])
const handleSubmit = async (
e: React.FormEvent<HTMLFormElement>
) => {
e.preventDefault()
if (!password) {
alert("Password is required")
return
}
setLoading(true)
fetch(`http://localhost:9000/auth/customer/emailpass/update?token=${token}`, {
credentials: "include",
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email,
password,
}),
})
.then((res) => res.json())
.then(({ success }) => {
alert(success ? "Password reset successfully!" : "Couldn't reset password")
setLoading(false)
})
}
return (
<form onSubmit={handleSubmit}>
<label>Password</label>
<input
placeholder="Password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit" disabled={loading}>
Reset Password
</button>
</form>
)
}
```
</CodeTab>
</CodeTabs>
In this example, you receive the `token` and `email` from the page's query parameters.
Then, when the form that has the password field is submitted, you send a request to the `http://localhost:9000/auth/customer/emailpass/update` API route. You pass it the token as a query parameter, and the email and password in the request body.
@@ -8,4 +8,6 @@ export const metadata = {
This section of the documentation holds guides to help you build a storefront for your Medusa application.
<ChildDocs />
<ChildDocs onlyTopLevel={true} showItems={["Tips", "Publishable API Key"]} />
<ChildDocs hideItems={["Tips", "Publishable API Key"]} />