Files
medusa-store/www/docs/content/modules/users/admin/manage-profile.mdx
Shahed Nasser 914d773d3a api-ref: custom API reference (#4770)
* initialized next.js project

* finished markdown sections

* added operation schema component

* change page metadata

* eslint fixes

* fixes related to deployment

* added response schema

* resolve max stack issue

* support for different property types

* added support for property types

* added loading for components

* added more loading

* type fixes

* added oneOf type

* removed console

* fix replace with push

* refactored everything

* use static content for description

* fixes and improvements

* added code examples section

* fix path name

* optimizations

* fixed tag navigation

* add support for admin and store references

* general enhancements

* optimizations and fixes

* fixes and enhancements

* added search bar

* loading enhancements

* added loading

* added code blocks

* added margin top

* add empty response text

* fixed oneOf parameters

* added path and query parameters

* general fixes

* added base path env variable

* small fix for arrays

* enhancements

* design enhancements

* general enhancements

* fix isRequired

* added enum values

* enhancements

* general fixes

* general fixes

* changed oas generation script

* additions to the introduction section

* added copy button for code + other enhancements

* fix response code block

* fix metadata

* formatted store introduction

* move sidebar logic to Tags component

* added test env variables

* fix code block bug

* added loading animation

* added expand param + loading

* enhance operation loading

* made responsive + improvements

* added loading provider

* fixed loading

* adjustments for small devices

* added sidebar label for endpoints

* added feedback component

* fixed analytics

* general fixes

* listen to scroll for other headings

* added sample env file

* update api ref files + support new fields

* fix for external docs link

* added new sections

* fix last item in sidebar not showing

* move docs content to www/docs

* change redirect url

* revert change

* resolve build errors

* configure rewrites

* changed to environment variable url

* revert changing environment variable name

* add environment variable for API path

* fix links

* fix tailwind settings

* remove vercel file

* reconfigured api route

* move api page under api

* fix page metadata

* fix external link in navigation bar

* update api spec

* updated api specs

* fixed google lint error

* add max-height on request samples

* add padding before loading

* fix for one of name

* fix undefined types

* general fixes

* remove response schema example

* redesigned navigation bar

* redesigned sidebar

* fixed up paddings

* added feedback component + report issue

* fixed up typography, padding, and general styling

* redesigned code blocks

* optimization

* added error timeout

* fixes

* added indexing with algolia + fixes

* fix errors with algolia script

* redesign operation sections

* fix heading scroll

* design fixes

* fix padding

* fix padding + scroll issues

* fix scroll issues

* improve scroll performance

* fixes for safari

* optimization and fixes

* fixes to docs + details animation

* padding fixes for code block

* added tab animation

* fixed incorrect link

* added selection styling

* fix lint errors

* redesigned details component

* added detailed feedback form

* api reference fixes

* fix tabs

* upgrade + fixes

* updated documentation links

* optimizations to sidebar items

* fix spacing in sidebar item

* optimizations and fixes

* fix endpoint path styling

* remove margin

* final fixes

* change margin on small devices

* generated OAS

* fixes for mobile

* added feedback modal

* optimize dark mode button

* fixed color mode useeffect

* minimize dom size

* use new style system

* radius and spacing design system

* design fixes

* fix eslint errors

* added meta files

* change cron schedule

* fix docusaurus configurations

* added operating system to feedback data

* change content directory name

* fixes to contribution guidelines

* revert renaming content

* added api-reference to documentation workflow

* fixes for search

* added dark mode + fixes

* oas fixes

* handle bugs

* added code examples for clients

* changed tooltip text

* change authentication to card

* change page title based on selected section

* redesigned mobile navbar

* fix icon colors

* fix key colors

* fix medusa-js installation command

* change external regex in algolia

* change changeset

* fix padding on mobile

* fix hydration error

* update depedencies
2023-08-15 18:07:54 +03:00

529 lines
12 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
description: 'Learn how to implement user profile management features using the admin APIs. This includes user authentication, updating the profile, and resetting the password.'
addHowToData: true
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
# How to Implement User Profiles
In this document, youll learn how to implement user profile management features using the admin APIs.
## Overview
The users admin APIs allow you to retrieve and perform admin functionalities on users.
### Scenario
You want to add or use the following admin functionalities:
- User authentication, meaning user log in and log out.
- Manage profile, including retrieving profile details and updating profile.
- Reset password
---
## Prerequisites
It is assumed that you already have a Medusa backend installed and set up. If not, you can follow the [quickstart guide](../../../development/backend/install.mdx) to get started.
### JS Client
This guide includes code snippets to send requests to your Medusa backend using Medusas JS Client, JavaScripts Fetch API, or cURL.
If you follow the JS Client code blocks, its assumed you already have [Medusas JS Client](../../../js-client/overview.md) installed and have [created an instance of the client](../../../js-client/overview.md#configuration).
### Medusa React
This guide also includes code snippets to send requests to your Medusa backend using Medusa React, among other methods.
If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.mdx) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.mdx#usage).
### Authenticated Admin User
Aside from the User Login and Reset Password steps, other endpoints require you to be an authenticated admin user.
You can learn more about [authenticating as an admin user in the API reference](https://docs.medusajs.com/api/admin#authentication).
---
## User Authentication
### User Login
You can log in a user by sending a request to the [User Login endpoint](https://docs.medusajs.com/api/admin#auth_postauth):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.auth.createSession({
email: "user@example.com",
password: "supersecret",
})
.then(({ user }) => {
console.log(user.id)
})
```
</TabItem>
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminLogin } from "medusa-react"
const Login = () => {
const adminLogin = useAdminLogin()
// ...
const handleLogin = () => {
adminLogin.mutate({
email: "user@example.com",
password: "supersecret",
})
}
// ...
}
export default Login
```
</TabItem>
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<BACKEND_URL>/admin/auth`, {
credentials: "include",
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: "user@example.com",
password: "supersecret",
}),
})
.then((response) => response.json())
.then(({ user }) => {
console.log(user.id)
})
```
</TabItem>
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<BACKEND_URL>/admin/auth' \
-H 'Content-Type: application/json' \
--data-raw '{
"email": "user@example.com",
"password": "supersecret"
}'
```
</TabItem>
</Tabs>
This endpoint requires the following request body parameters:
- `email`: a string indicating the users email.
- `password`: a string indicating the users password.
The request returns the logged-in user as an object.
### User Logout
You can log out a user by sending a request to the [User Logout endpoint](https://docs.medusajs.com/api/admin#auth_deleteauth):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.auth.deleteSession()
.then(() => {
// logged out successfully
})
```
</TabItem>
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminDeleteSession } from "medusa-react"
const Logout = () => {
const adminLogout = useAdminDeleteSession()
// ...
const handleLogout = () => {
adminLogout.mutate()
}
// ...
}
export default Logout
```
</TabItem>
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<BACKEND_URL>/admin/auth`, {
credentials: "include",
method: "DELETE",
})
.then((response) => response.json())
.then(() => {
// logged out successfully
})
```
</TabItem>
<TabItem value="curl" label="cURL">
```bash
curl -L -X DELETE '<BACKEND_URL>/admin/auth' \
-H 'Authorization: Bearer <API_TOKEN>'
```
</TabItem>
</Tabs>
The endpoint does not require any path or query parameters.
The request does not return any data. The response code will be `200` for successful log out.
---
## Retrieve User Profile Details
You can retrieve the current users details for their profile by sending a request to the [Get Current User endpoint](https://docs.medusajs.com/api/admin#auth_getauth):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.auth.getSession()
.then(({ user }) => {
console.log(user.id)
})
```
</TabItem>
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminGetSession } from "medusa-react"
const Profile = () => {
const { user, isLoading } = useAdminGetSession()
return (
<div>
{isLoading && <span>Loading...</span>}
{user && <span>{user.email}</span>}
</div>
)
}
export default Profile
```
</TabItem>
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<BACKEND_URL>/admin/auth`, {
credentials: "include",
})
.then((response) => response.json())
.then(({ user }) => {
console.log(user.id)
})
```
</TabItem>
<TabItem value="curl" label="cURL">
```bash
curl -L -X GET '<BACKEND_URL>/admin/auth' \
-H 'Authorization: Bearer <API_TOKEN>'
```
</TabItem>
</Tabs>
This endpoint does not require any parameters.
The request returns the current user as an object.
---
## Update Users Profile Details
You can update a users details in their profile by sending a request to the [Update User endpoint](https://docs.medusajs.com/api/admin#users_postusersuser):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.users.update(userId, {
first_name: "Marcellus",
})
.then(({ user }) => {
console.log(user.id)
})
```
</TabItem>
<TabItem value="medusa-react" label="Medusa React">
```tsx
import {
useAdminDeleteSession,
useAdminUpdateUser,
} from "medusa-react"
const Profile = () => {
const updateUser = useAdminUpdateUser(userId)
// ...
const handleUpdate = () => {
updateUser.mutate({
first_name: "Marcellus",
})
}
// ...
}
export default Profile
```
</TabItem>
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<BACKEND_URL>/admin/users/${userId}`, {
credentials: "include",
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
first_name: "Marcellus",
}),
})
.then((response) => response.json())
.then(({ user }) => {
console.log(user.id)
})
```
</TabItem>
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<BACKEND_URL>/admin/users/<USER_ID>' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
"first_name": "Marcellus"
}'
```
</TabItem>
</Tabs>
This endpoint requires the ID of the user as a path parameter.
In the request body, you can pass any of the users fields that you want to update as a parameter. In the example above, you pass the `first_name` parameter to update the users first name. You can refer to the [API reference](https://docs.medusajs.com/api/admin#users_postusersuser) to learn about other available parameters.
The request returns the updated user as an object.
---
## Reset Password
This section explains how you can reset the password of a user if they forgot their password.
### Step 1: Request Password Reset
The first step is to request a password reset. This would create in the Medusa backend a reset password token, which you typically would use in an email sent to the user. The email would include a link that allows the user to enter a new password, and the link would accept a token query parameter to be used in step 2.
:::note
Sending the password reset email is not handled by default in the Medusa backend. You can either use the SendGrid plugin which handles it, or manually subscribe to the `user.password_reset` event and send the email.
:::
You can request a password reset by sending a request to the [Request Password Reset endpoint](https://docs.medusajs.com/api/admin#users_postusersuserpasswordtoken):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.users.sendResetPasswordToken({
email: "user@example.com",
})
.then(() => {
// successful
})
```
</TabItem>
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminSendResetPasswordToken } from "medusa-react"
const Login = () => {
const requestPasswordReset = useAdminSendResetPasswordToken()
// ...
const handleResetPassword = () => {
requestPasswordReset.mutate({
email: "user@example.com",
})
}
// ...
}
export default Login
```
</TabItem>
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<BACKEND_URL>/admin/users/password-token`, {
credentials: "include",
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: "user@example.com",
}),
})
.then((response) => response.json())
.then(() => {
// successful
})
```
</TabItem>
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<BACKEND_URL>/admin/users/password-token' \
-H 'Content-Type: application/json' \
--data-raw '{
"email": "user@example.com"
}'
```
</TabItem>
</Tabs>
This endpoint requires the `email` parameter in the request body, which is the email of the user requesting to reset their password.
The request does not return any data. The response code will be `204` if the request was processed successfully.
### Step 2: Reset Password
After the user resets their password and, typically, receives an email with a link to reset their password, they should enter their new password. The new password, along with the token passed to this page are used to reset the password on the Medusa backend.
You can reset the password by sending a request to the [Reset Password endpoint](https://docs.medusajs.com/api/admin#users_postusersuserpassword):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.users.resetPassword({
token: "supersecrettoken",
password: "supersecret",
})
.then(({ user }) => {
console.log(user.id)
})
```
</TabItem>
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminResetPassword } from "medusa-react"
const ResetPassword = () => {
const resetPassword = useAdminResetPassword()
// ...
const handleResetPassword = () => {
resetPassword.mutate({
token: "supersecrettoken",
password: "supersecret",
})
}
// ...
}
export default ResetPassword
```
</TabItem>
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<BACKEND_URL>/admin/users/reset-password`, {
credentials: "include",
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
token: "supersecrettoken",
password: "supersecret",
}),
})
.then((response) => response.json())
.then(({ user }) => {
console.log(user.id)
})
```
</TabItem>
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<BACKEND_URL>/admin/users/reset-password' \
-H 'Content-Type: application/json' \
--data-raw '{
"token": "supersecrettoken",
"password": "supersecret"
}'
```
</TabItem>
</Tabs>
This endpoint requires the following request body parameters:
- `token`: a string indicating the password reset token.
- `password`: a string indicating the new password for the user.
You can also optionally pass the `email` parameter in the request body.
The request returns the user as an object, and the user is automatically logged in.
---
## See Also
- [How to manage users](./manage-users.mdx)