docs: create docs workspace (#5174)

* docs: migrate ui docs to docs universe

* created yarn workspace

* added eslint and tsconfig configurations

* fix eslint configurations

* fixed eslint configurations

* shared tailwind configurations

* added shared ui package

* added more shared components

* migrating more components

* made details components shared

* move InlineCode component

* moved InputText

* moved Loading component

* Moved Modal component

* moved Select components

* Moved Tooltip component

* moved Search components

* moved ColorMode provider

* Moved Notification components and providers

* used icons package

* use UI colors in api-reference

* moved Navbar component

* used Navbar and Search in UI docs

* added Feedback to UI docs

* general enhancements

* fix color mode

* added copy colors file from ui-preset

* added features and enhancements to UI docs

* move Sidebar component and provider

* general fixes and preparations for deployment

* update docusaurus version

* adjusted versions

* fix output directory

* remove rootDirectory property

* fix yarn.lock

* moved code component

* added vale for all docs MD and MDX

* fix tests

* fix vale error

* fix deployment errors

* change ignore commands

* add output directory

* fix docs test

* general fixes

* content fixes

* fix announcement script

* added changeset

* fix vale checks

* added nofilter option

* fix vale error
This commit is contained in:
Shahed Nasser
2023-09-21 20:57:15 +03:00
committed by GitHub
parent 19c5d5ba36
commit fa7c94b4cc
3209 changed files with 32188 additions and 31018 deletions

View File

@@ -0,0 +1,455 @@
---
description: 'Learn how to manage invites using the admin API. This includes listing, creating, accepting, resending, and deleting invites.'
addHowToData: true
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
# How to Manage Invites
In this document, youll learn how to manage invites using the admin API.
## Overview
You can use the invites admin API to manage and perform functionalities related to invites.
### Scenario
You want to add or use the following admin functionalities:
- List invites
- Create an invite
- Accept an invite
- Resend an invite
- Delete an invite
---
## Prerequisites
### Medusa Components
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, among other methods.
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
Except for the Accept Invite endpoint, you must be an authenticated admin user before following along with the steps in the tutorial.
You can learn more about [authenticating as an admin user in the API reference](https://docs.medusajs.com/api/admin#authentication).
---
## List Invites
You can list invites by sending a request to the [List Invite endpoint](https://docs.medusajs.com/api/admin#invites_getinvites):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.invites.list()
.then(({ invites }) => {
console.log(invites.length)
})
```
</TabItem>
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminInvites } from "medusa-react"
const Invites = () => {
const { invites, isLoading } = useAdminInvites()
return (
<div>
{isLoading && <span>Loading...</span>}
{invites && !invites.length && <span>No Invites</span>}
{invites && invites.length > 0 && (
<ul>
{invites.map((invite) => (
<li key={invite.id}>{invite.user_email}</li>
))}
</ul>
)}
</div>
)
}
export default Invites
```
</TabItem>
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<BACKEND_URL>/admin/invites`, {
credentials: "include",
})
.then((response) => response.json())
.then(({ invites }) => {
console.log(invites.length)
})
```
</TabItem>
<TabItem value="curl" label="cURL">
```bash
curl -L -X GET '<BACKEND_URL>/admin/invites' \
-H 'Authorization: Bearer <API_TOKEN>'
```
</TabItem>
</Tabs>
This endpoint does not accept any parameters.
The request returns an array of invite endpoints.
---
## Create Invite
You can create an invite by sending a request to the [Create Invite endpoint](https://docs.medusajs.com/api/admin#invites_postinvites):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.invites.create({
user: "user@example.com",
role: "admin",
})
.then(() => {
// successful
})
```
</TabItem>
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminCreateInvite } from "medusa-react"
const CreateInvite = () => {
const createInvite = useAdminCreateInvite()
// ...
const handleCreate = () => {
createInvite.mutate({
user: "user@example.com",
role: "admin",
})
}
// ...
}
export default CreateInvite
```
</TabItem>
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<BACKEND_URL>/admin/invites`, {
credentials: "include",
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
user: "user@example.com",
role: "admin",
}),
})
.then((response) => response.json())
.then(() => {
// successful
})
```
</TabItem>
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<BACKEND_URL>/admin/invites' \
-H 'Authorization: Bearer <API_TOKEN>' \
-H 'Content-Type: application/json' \
--data-raw '{
"user": "user@example.com",
"role": "admin"
}'
```
</TabItem>
</Tabs>
This endpoint requires the following body parameters:
- `user`: a string indicating the email of the user.
- `role`: a string indicating the role of the user. Its values can be `admin`, `member`, and `developer`.
The request does not return any data. If the invite was created successfully, the status code of the response will be `200`.
---
## Accept an Invite
A logged-out user can accept an invite, which would create a user for that user.
You can accept an invite by sending a request to the [Accept Invite endpoint](https://docs.medusajs.com/api/admin#invites_postinvitesinviteaccept):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.invites.accept({
token,
user: {
first_name: "Brigitte",
last_name: "Collier",
password: "supersecret",
},
})
.then(() => {
// successful
})
```
</TabItem>
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminAcceptInvite } from "medusa-react"
const AcceptInvite = () => {
const acceptInvite = useAdminAcceptInvite()
// ...
const handleAccept = () => {
acceptInvite.mutate({
token,
user: {
first_name: "Brigitte",
last_name: "Collier",
password: "supersecret",
},
})
}
// ...
}
export default AcceptInvite
```
</TabItem>
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<BACKEND_URL>/admin/invites/accept`, {
credentials: "include",
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
token,
user: {
first_name: "Brigitte",
last_name: "Collier",
password: "supersecret",
},
}),
})
.then((response) => response.json())
.then(() => {
// successful
})
```
</TabItem>
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<BACKEND_URL>/admin/invites/accept' \
-H 'Content-Type: application/json' \
--data-raw '{
"token": "<TOKEN>",
"user": {
"first_name": "Brigitte",
"last_name": "Collier",
"password": "supersecret"
}
}'
```
</TabItem>
</Tabs>
This endpoint requires the following request body parameters:
- `token`: a string indicating the invitations token.
- `user`: an object that has the following properties:
- `first_name`: a string indicating the first name of the user.
- `last_name`: a string indicating the last name of the user.
- `password`: a string indicating the users password.
The request does not return any data. If the invite was accepted successfully, the status code of the response will be `200`.
---
## Resend an Invite
You can resend an invite if its not accepted yet. To resend an invite, send a request to the [Resend Invite endpoint](https://docs.medusajs.com/api/admin#invites_postinvitesinviteresend):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.invites.resend(inviteId)
.then(() => {
// successful
})
```
</TabItem>
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminResendInvite } from "medusa-react"
const ResendInvite = () => {
const resendInvite = useAdminResendInvite(inviteId)
// ...
const handleResend = () => {
resendInvite.mutate()
}
// ...
}
export default ResendInvite
```
</TabItem>
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<BACKEND_URL>/admin/invites/${inviteId}/resend`, {
credentials: "include",
method: "POST",
})
.then((response) => response.json())
.then(() => {
// successful
})
```
</TabItem>
<TabItem value="curl" label="cURL">
```bash
curl -L -X POST '<BACKEND_URL>/admin/invites/<INVITE_ID>/resend' \
-H 'Authorization: Bearer <API_TOKEN>'
```
</TabItem>
</Tabs>
This endpoint requires the invite ID as a path parameter.
The request does not return any data. If the invite was resent successfully, the status code of the response will be `200`.
---
## Delete an Invite
You can delete an invite by sending a request to the [Delete Invite endpoint](https://docs.medusajs.com/api/admin#invites_deleteinvitesinvite):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.invites.delete(inviteId)
.then(({ id, object, deleted }) => {
console.log(id)
})
```
</TabItem>
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminDeleteInvite } from "medusa-react"
const DeleteInvite = () => {
const deleteInvite = useAdminDeleteInvite(inviteId)
// ...
const handleDelete = () => {
deleteInvite.mutate()
}
// ...
}
export default DeleteInvite
```
</TabItem>
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<BACKEND_URL>/admin/invites/${inviteId}`, {
credentials: "include",
method: "DELETE",
})
.then((response) => response.json())
.then(({ id, object, deleted }) => {
console.log(id)
})
```
</TabItem>
<TabItem value="curl" label="cURL">
```bash
curl -L -X DELETE '<BACKEND_URL>/admin/invites/<INVITE_ID>' \
-H 'Authorization: Bearer <API_TOKEN>'
```
</TabItem>
</Tabs>
This endpoint requires the invite ID as a path parameter.
It deletes the invite and returns the following fields:
- `id`: The ID of the deleted invite.
- `object`: The type of object that was deleted. In this case, the value will be `invite`.
- `deleted`: A boolean value indicating whether the invite was deleted.
---
## See Also
- [How to implement user profiles](./manage-profile.mdx)
- [How to manage users](./manage-users.mdx)

View File

@@ -0,0 +1,528 @@
---
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)

View File

@@ -0,0 +1,365 @@
---
description: 'Learn how to manage users using the admin APIs. This includes listing, creating, updating, and deleting users.'
addHowToData: true
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
# How to Manage Users
In this document, youll learn how to manage users using the admin APIs.
## Overview
You can use the user admin API to manage users and teams in the store.
### Scenario
You want to add or use the following admin functionalities:
- List users
- Create a user
- Update a user
- Delete a user
---
## Prerequisites
### Medusa Components
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, among other methods.
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
You must be an authenticated admin user before following along with the steps in the tutorial.
You can learn more about [authenticating as an admin user in the API reference](https://docs.medusajs.com/api/admin#authentication).
---
## List Users
You can retrieve users in a store by sending a request to the [List Users endpoint](https://docs.medusajs.com/api/admin#users_getusers):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.users.list()
.then(({ users }) => {
console.log(users.length)
})
```
</TabItem>
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminUsers } from "medusa-react"
const Users = () => {
const { users, isLoading } = useAdminUsers()
return (
<div>
{isLoading && <span>Loading...</span>}
{users && !users.length && <span>No Users</span>}
{users && users.length > 0 && (
<ul>
{users.map((user) => (
<li key={user.id}>{user.email}</li>
))}
</ul>
)}
</div>
)
}
export default Users
```
</TabItem>
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<BACKEND_URL>/admin/users`, {
credentials: "include",
})
.then((response) => response.json())
.then(({ users }) => {
console.log(users.length)
})
```
</TabItem>
<TabItem value="curl" label="cURL">
```bash
curl -L -X GET '<BACKEND_URL>/admin/users' \
-H 'Authorization: Bearer <API_TOKEN>'
```
</TabItem>
</Tabs>
This endpoint does not require any parameters.
The request returns an array of user objects.
---
## Create a User
You can create a user by sending a request to the [Create User endpoint](https://docs.medusajs.com/api/admin#users_postusers):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.users.create({
email: "user@example.com",
password: "supersecret",
})
.then(({ user }) => {
console.log(user.id)
})
```
</TabItem>
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminCreateUser } from "medusa-react"
const CreateUser = () => {
const createUser = useAdminCreateUser()
// ...
const handleCreateUser = () => {
createUser.mutate({
email: "user@example.com",
password: "supersecret",
})
}
// ...
}
export default CreateUser
```
</TabItem>
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<BACKEND_URL>/admin/users`, {
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/users' \
-H 'Authorization: Bearer <API_TOKEN>' \
-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 email of the user.
- `password`: a string indicating the password of the user.
The endpoint accepts other optional body parameters, such as first name or last name. Check the [API reference](https://docs.medusajs.com/api/admin#users_postusers) for details on optional body parameters.
The request returns the created user as an object.
---
## Update User
You can update a users details 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 { useAdminUpdateUser } from "medusa-react"
const UpdateUser = () => {
const updateUser = useAdminUpdateUser(userId)
// ...
const handleUpdateUser = () => {
updateUser.mutate({
first_name: "Marcellus",
})
}
// ...
}
export default UpdateUser
```
</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 parameters. In the example above, you update the users `first_name`. Check the [API reference](https://docs.medusajs.com/api/admin#users_postusersuser) for all the optional parameters.
The request returns the updated user as an object.
---
## Delete a User
You can delete a user by sending a request to the [Delete User endpoint](https://docs.medusajs.com/api/admin#users_deleteusersuser):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
```ts
medusa.admin.users.delete(userId)
.then(({ id, object, deleted }) => {
console.log(id)
})
```
</TabItem>
<TabItem value="medusa-react" label="Medusa React">
```tsx
import { useAdminDeleteUser } from "medusa-react"
const DeleteUser = () => {
const deleteUser = useAdminDeleteUser(userId)
// ...
const handleDeleteUser = () => {
deleteUser.mutate()
}
// ...
}
export default DeleteUser
```
</TabItem>
<TabItem value="fetch" label="Fetch API">
```ts
fetch(`<BACKEND_URL>/admin/users/${userId}`, {
credentials: "include",
method: "DELETE",
})
.then((response) => response.json())
.then(({ id, object, deleted }) => {
console.log(id)
})
```
</TabItem>
<TabItem value="curl" label="cURL">
```bash
curl -L -X DELETE '<BACKEND_URL>/admin/users/<USER_ID>' \
-H 'Authorization: Bearer <API_TOKEN>'
```
</TabItem>
</Tabs>
This endpoint requires the user ID as a path parameter.
It deletes the user and returns the following fields:
- `id`: The ID of the deleted user.
- `object`: The type of object that was deleted. In this case, the value will be `user`.
- `deleted`: A boolean value indicating whether the user was deleted.
---
## See Also
- [How to manage a users profile](./manage-profile.mdx)

View File

@@ -0,0 +1,800 @@
---
addHowToData: true
---
import DocCardList from '@theme/DocCardList';
import DocCard from '@theme/DocCard';
import Icons from '@theme/Icon';
# Implement Role-Based Access Control (RBAC)
In this document, you'll get a high-level overview of how you can implement role-based access control (RBAC) in your Medusa backend.
## Overview
Role-Based Access Control (RBAC) refers to the level of access a user has. Typically, in e-commerce, you may require RBAC if you want users to only be able to perform certain actions.
For example, you may want a content-manager user who can only access CMS functionalities and another manager user who can only access order functionalities. RBAC is also useful in [marketplace use cases](../../../recipes/marketplace.mdx).
This guide gives you a high-level approach to implementing RBAC in Medusa. The examples included in this guide provide a simple implementation to give you an idea of how you can implement this functionality in your Medusa backend.
---
## Create Role and Permission Entities
When implementing RBAC, you typically require the availability of roles and permissions. A role would include different permissions, such as the ability to access the products route, and it can be assigned to one or more users.
So, the first step would be to create the `Role` and `Permission` entities to represent this data. Also, since youll be creating relations to other entities, such as the `User` entity, you need to extend the core entities to implement these relations.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/development/entities/create',
label: 'Create Entities',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create an entity.',
}
},
{
type: 'link',
href: '/development/entities/extend-entity',
label: 'Extend Entities',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to extend a core entity.',
}
},
]} />
<details>
<summary>
Example Implementation
</summary>
This is an example implementation of how you can create the Role and Permission entities, and extend the `User` and `Store` entities.
Creating an entity requires creating an entity class, a repository, and a migration. You can learn more [here](../../../development/entities/create.mdx). Youll be creating the migration at the end of this example section.
Create the file `src/models/role.ts` with the following content:
```ts title=src/models/role.ts
import {
BeforeInsert,
Column,
Entity,
Index,
JoinColumn,
JoinTable,
ManyToMany,
ManyToOne,
OneToMany,
} from "typeorm"
import { BaseEntity } from "@medusajs/medusa"
import { generateEntityId } from "@medusajs/medusa/dist/utils"
import { Permission } from "./permission"
import { User } from "./user"
import { Store } from "./store"
@Entity()
export class Role extends BaseEntity {
@Column({ type: "varchar" })
name: string
// only helpful if you're integrating in a marketplace
@Index()
@Column({ nullable: true })
store_id: string
@ManyToMany(() => Permission)
@JoinTable({
name: "role_permissions",
joinColumn: {
name: "role_id",
referencedColumnName: "id",
},
inverseJoinColumn: {
name: "permission_id",
referencedColumnName: "id",
},
})
permissions: Permission[]
@OneToMany(() => User, (user) => user.teamRole)
@JoinColumn({ name: "id", referencedColumnName: "role_id" })
users: User[]
@ManyToOne(() => Store, (store) => store.roles)
@JoinColumn({ name: "store_id" })
store: Store
@BeforeInsert()
private beforeInsert(): void {
this.id = generateEntityId(this.id, "role")
}
}
```
This creates the `Role` entity. Youll see errors in your editors, which youll resolve by following along the example.
The `Role` entity has the following attributes:
- `id`: the ID of the role, which is available implicitly by extending `BaseEntity`
- `name`: the name of the role
- `store_id`: the ID of the store this role belongs to. This is only useful if youre implementing RBAC in a marketplace. Otherwise, you may omit this relation.
It also has the following relations:
- `permissions`: an array of permissions included in this role.
- `store`: the Store this role belongs to.
- `users`: the users associated with this role.
Then, create the file `src/repositories/role.ts` with the following content:
```ts title=src/repositories/role.ts
import { Role } from "../models/role"
import {
dataSource,
} from "@medusajs/medusa/dist/loaders/database"
export const RoleRepository = dataSource
.getRepository(Role)
export default RoleRepository
```
Next, create the file `src/models/permission.ts` with the following content:
```ts title=src/models/permission.ts
import {
BeforeInsert,
Column,
Entity,
JoinTable,
ManyToMany,
} from "typeorm"
import { BaseEntity } from "@medusajs/medusa"
import {
DbAwareColumn,
generateEntityId,
} from "@medusajs/medusa/dist/utils"
import { Role } from "./role"
@Entity()
export class Permission extends BaseEntity {
@Column({ type: "varchar" })
name: string
// holds the permissions
@DbAwareColumn({ type: "jsonb", nullable: true })
metadata: Record<string, boolean>
@BeforeInsert()
private beforeInsert(): void {
this.id = generateEntityId(this.id, "perm")
}
}
```
This creates a `Permission` entity that has the following attributes:
- `id`: the ID of the permission, which is implicitly available through extending `BaseEntity`.
- `name`: the name of the permission.
- `metadata`: an object that will include the permissions. The object keys will be an admin path in the backend, and the value will be a boolean indicating whether the user has access to that path or not.
Then, create the file `src/repositories/permission.ts` with the following content:
```ts title=src/repositories/permission.ts
import { Permission } from "../models/permission"
import {
dataSource,
} from "@medusajs/medusa/dist/loaders/database"
export const PermissionRepository = dataSource
.getRepository(Permission)
export default PermissionRepository
```
Next, youll extend the `User` and `Store` entities. As mentioned earlier, extending the `Store` entity and adding the relation is only useful if youre implementing RBAC in a marketplace or similar use cases. So, if this doesnt apply to you, you may skip it.
Create the file `src/models/user.ts` with the following content:
```ts title=src/models/user.ts
import {
Column,
Entity,
Index,
JoinColumn,
ManyToOne,
} from "typeorm"
import {
// alias the core entity to not cause a naming conflict
User as MedusaUser,
} from "@medusajs/medusa"
import { Role } from "./role"
@Entity()
export class User extends MedusaUser {
@Index()
@Column({ nullable: true })
role_id: string | null
@ManyToOne(() => Role, (role) => role.users)
@JoinColumn({ name: "role_id" })
teamRole: Role | null
}
```
This adds a new attribute `role_id` to the core `User` entity and a `teamRole` relation that optionally associates the user with a role.
Next, create the file `src/models/store.ts` with the following content:
```ts title=src/models/store.ts
import { Entity, JoinColumn, OneToMany } from "typeorm"
import {
// alias the core entity to not cause a naming conflict
Store as MedusaStore,
} from "@medusajs/medusa"
import { Role } from "./role"
@Entity()
export class Store extends MedusaStore {
@OneToMany(() => Role, (role) => role.store)
@JoinColumn({ name: "id", referencedColumnName: "store_id" })
roles: Role[]
}
```
This adds a `roles` relation to the core `Store` entity.
Optionally, if youre using TypeScript, create the file `src/index.d.ts` with the following content:
```ts title=src/index.d.ts
import { Role } from "./models/role"
export declare module "@medusajs/medusa/dist/models/user" {
declare interface User {
role_id: string | null;
teamRole: Role | null
}
declare interface Store {
roles: Role[]
}
}
```
This ensures that your TypeScript validation and editor autocomplete recognize the new attributes and relations you added on the core entities.
Finally, you need to create a migration to reflect these changes in the database.
You can learn about creating migrations [here](../../../development/entities/migrations/create.md). An example of a migration file based on the entities created above:
<!-- eslint-disable max-len -->
```ts title=src/migrations/1693225851284-AddRolesAndPermissions.ts
import { MigrationInterface, QueryRunner, Table, TableIndex } from "typeorm"
export class AddRolesAndPermissions1693225851284 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "user" ADD "role_id" character varying`)
await queryRunner.query(`CREATE TABLE "permission" ("id" character varying NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "name" character varying NOT NULL, "metadata" jsonb, CONSTRAINT "PK_3b8b97af9d9d8807e41e6f48362" PRIMARY KEY ("id"))`)
await queryRunner.query(`CREATE TABLE "role" ("id" character varying NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "name" character varying NOT NULL, "store_id" character varying, CONSTRAINT "PK_b36bcfe02fc8de3c57a8b2391c2" PRIMARY KEY ("id"))`)
await queryRunner.query(`CREATE INDEX "IDX_29259dd58b1052aef9be56941d" ON "role" ("store_id") `)
await queryRunner.query(`CREATE TABLE "role_permissions" ("role_id" character varying NOT NULL, "permission_id" character varying NOT NULL, CONSTRAINT "PK_25d24010f53bb80b78e412c9656" PRIMARY KEY ("role_id", "permission_id"))`)
await queryRunner.query(`CREATE INDEX "IDX_178199805b901ccd220ab7740e" ON "role_permissions" ("role_id") `)
await queryRunner.query(`CREATE INDEX "IDX_17022daf3f885f7d35423e9971" ON "role_permissions" ("permission_id") `)
await queryRunner.query(`ALTER TABLE "role_permissions" ADD CONSTRAINT "FK_178199805b901ccd220ab7740ec" FOREIGN KEY ("role_id") REFERENCES "role"("id") ON DELETE CASCADE ON UPDATE CASCADE`)
await queryRunner.query(`ALTER TABLE "role_permissions" ADD CONSTRAINT "FK_17022daf3f885f7d35423e9971e" FOREIGN KEY ("permission_id") REFERENCES "permission"("id") ON DELETE CASCADE ON UPDATE CASCADE`)
await queryRunner.query(`ALTER TABLE "user" ADD CONSTRAINT "FK_fb2e442d14add3cefbdf33c4561" FOREIGN KEY ("role_id") REFERENCES "role"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`)
await queryRunner.query(`ALTER TABLE "role" ADD CONSTRAINT "FK_29259dd58b1052aef9be56941d4" FOREIGN KEY ("store_id") REFERENCES "store"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`)
await queryRunner.query(`CREATE INDEX "IDX_fb2e442d14add3cefbdf33c456" ON "user" ("role_id") `)
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "role_permissions" DROP CONSTRAINT "FK_17022daf3f885f7d35423e9971e"`)
await queryRunner.query(`ALTER TABLE "role_permissions" DROP CONSTRAINT "FK_178199805b901ccd220ab7740ec"`)
await queryRunner.query(`ALTER TABLE "role" DROP CONSTRAINT "FK_29259dd58b1052aef9be56941d4"`)
await queryRunner.query(`DROP INDEX "public"."IDX_fb2e442d14add3cefbdf33c456"`)
await queryRunner.query(`ALTER TABLE "user" DROP CONSTRAINT "FK_fb2e442d14add3cefbdf33c4561"`)
await queryRunner.query(`ALTER TABLE "user" DROP COLUMN "role_id"`)
await queryRunner.query(`DROP INDEX "public"."IDX_17022daf3f885f7d35423e9971"`)
await queryRunner.query(`DROP INDEX "public"."IDX_178199805b901ccd220ab7740e"`)
await queryRunner.query(`DROP TABLE "role_permissions"`)
await queryRunner.query(`DROP INDEX "public"."IDX_29259dd58b1052aef9be56941d"`)
await queryRunner.query(`DROP TABLE "role"`)
await queryRunner.query(`DROP TABLE "permission"`)
}
}
```
Finally, to reflect these changes, run the `build` command in the root directory of your medusa backend:
```bash npm2yarn
npm run build
```
Then, run the migrations:
```bash
npx medusa migrations run
```
This will reflect the entity changes in your database.
</details>
---
## Create Guard Middleware
To ensure that users who have the privilege can access an endpoint, you must create a middleware that guards admin routes. This middleware will run on all authenticated admin requests to ensure that only allowed users can access an endpoint.
Since the Medusa backend uses Express, you can create a middleware and attach it to all admin routes.
<DocCard item={{
type: 'link',
href: '/development/endpoints/add-middleware',
label: 'Create a Middleware',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create a middleware in Medusa.',
}
}} />
<details>
<summary>Example Implementation</summary>
In this example, youll create a middleware that runs on all admin-authenticated routes and checks the logged-in users permissions before giving them access to an endpoint.
Create the file `src/api/middlewares/permission.ts` with the following content:
```ts title=src/api/middlewares/permission.ts
import { UserService } from "@medusajs/medusa"
import { NextFunction, Request, Response } from "express"
export default async (
req: Request,
res: Response,
next: NextFunction
) => {
if (!req.user || !req.user.userId) {
next()
return
}
// retrieve currently logged-in user
const userService = req.scope.resolve(
"userService"
) as UserService
const loggedInUser = await userService.retrieve(
req.user.userId,
{
select: ["id"],
relations: ["teamRole", "teamRole.permissions"],
})
if (!loggedInUser.teamRole) {
// considered as super user
next()
return
}
const isAllowed = loggedInUser.teamRole?.permissions.some(
(permission) => {
const metadataKey = Object.keys(permission.metadata).find(
(key) => key === req.path
)
if (!metadataKey) {
return false
}
// boolean value
return permission.metadata[metadataKey]
}
)
if (isAllowed) {
next()
return
}
// deny access
res.sendStatus(401)
}
```
In this middleware, you ensure that there is a logged-in user and the logged-in user has a role. If not, the user is admitted to access the endpoint. Here, you presume that logged-in users who dont have a role are “super-admin” users who can access all endpoints. You may choose to implement this differently.
If theres a logged-in user that has a role, you check that the roles permissions give them access to the current endpoint. You do that by checking if a permissions metadata has a key with the same requests path. It may be better here to check for matching using regular expressions, for example, to check routes with path parameters.
Otherwise, if the users role doesnt provide them with enough permissions, you return a `401` response code.
:::tip
Notice that you use `req.path` here to get the current endpoint path. However, in middlewares, this doesnt include the mount point which is `/admin`. So, for example, if the endpoint path is `/admin/products`, `req.path` will be `/products`. You can alternatively use `req.originalUrl`. Learn more in [Expresss documentation](https://expressjs.com/en/api.html#req.originalUrl).
:::
Next, to ensure that this middleware is used, import it in `src/api/index.ts` and apply it on admin routes:
```ts title=src/api/index.ts
import permissionMiddleware from "./middlewares/permission"
export default (rootDirectory: string): Router | Router[] => {
// ...
const router = Router()
// ...
// use middleware on admin routes
router.use("/admin", permissionMiddleware)
return router
}
```
This assumes you already have a router with all necessary CORS configurations and body parsing middlewares. If not, you can refer to the [Create Endpoint documentation](../../../development/endpoints/create.mdx) for more details.
Make sure to use the permission middleware after all router configurations if you want the middleware to work on your custom admin routes.
</details>
---
## Create Endpoints and Services
To manage the roles and permissions, youll need to create custom endpoints, typically for Create, Read, Update, and Delete (CRUD) operations.
Youll also need to create a service for each of `Role` and `Permission` entities to perform these operations on them. The entity uses the service within its code.
Furthermore, you may need to extend core services if you need to perform actions on core entities that youve extended, such as the `User` entity.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/development/endpoints/create',
label: 'Create Endpoint',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create an endpoint in Medusa.',
}
},
{
type: 'link',
href: '/development/services/create-service',
label: 'Create Service',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create a service in Medusa',
}
},
{
type: 'link',
href: '/development/services/extend-service',
label: 'Extend Service',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to extend a core service in Medusa',
}
},
]} />
<details>
<summary>
Example Implementation
</summary>
In this example, youll only implement two endpoints for simplicity: create role endpoint that create a new role with permissions, and associate user endpoint that associates a user with a role.
Youll also create basic services for `Role` and `Permission` to perform the functionalities of each of these endpoints and extend the core `UserService` to allow associating roles with users.
Start by creating the file `src/services/permission.ts` with the following content:
```ts title=src/services/permission.ts
import { TransactionBaseService } from "@medusajs/medusa"
import { Permission } from "../models/permission"
import PermissionRepository from "../repositories/permission"
export type CreatePayload = Pick<
Permission,
"name" | "metadata"
>
type InjectedDependencies = {
permissionRepository: typeof PermissionRepository
}
class PermissionService extends TransactionBaseService {
protected readonly permissionRepository_:
typeof PermissionRepository
constructor(container: InjectedDependencies) {
super(container)
this.permissionRepository_ = container.permissionRepository
}
async create(data: CreatePayload) {
// omitting validation for simplicity
return this.atomicPhase_(async (manager) => {
const permissionRepo = manager.withRepository(
this.permissionRepository_
)
const permission = permissionRepo.create(data)
const result = await permissionRepo.save(permission)
return result
})
}
}
export default PermissionService
```
This creates the `PermissionService` with only a `create` method that can be used to create a permission.
Next, create the file `src/services/user.ts` with the following content:
```ts title=src/services/user.ts
import {
UserService as MedusaUserService, User,
} from "@medusajs/medusa"
import {
UpdateUserInput,
} from "@medusajs/medusa/dist/types/user"
class UserService extends MedusaUserService {
async update(userId: string, update: UpdateUserInput & {
role_id?: string
}): Promise<User> {
return super.update(userId, update)
}
}
export default UserService
```
This extends the core `UserService` to allow updating a users role. You may also want to extend the `create` method to allow specifying the role on creation.
Then, create the file `src/services/role.ts` with the following content:
```ts title=src/services/role.ts
import { TransactionBaseService } from "@medusajs/medusa"
import { Role } from "../models/role"
import RoleRepository from "../repositories/role"
import PermissionService, {
CreatePayload as PermissionCreatePayload,
} from "./permission"
import UserService from "./user"
type CreatePayload = Pick<Role, "name" | "store_id"> & {
permissions?: PermissionCreatePayload[]
}
type InjectedDependencies = {
roleRepository: typeof RoleRepository
permissionService: PermissionService
userService: UserService
}
class RoleService extends TransactionBaseService {
protected readonly roleRpository_: typeof RoleRepository
protected readonly permissionService_: PermissionService
protected readonly userService_: UserService
constructor(container: InjectedDependencies) {
super(container)
this.roleRpository_ = container.roleRepository
this.permissionService_ = container.permissionService
this.userService_ = container.userService
}
async retrieve(id: string): Promise<Role> {
// for simplicity, we retrieve all relations
// however, it's best to supply the relations
// as an optional method parameter
const roleRepo = this.manager_.withRepository(
this.roleRpository_
)
return await roleRepo.findOne({
where: {
id,
},
relations: [
"permissions",
"store",
"users",
],
})
}
async create(data: CreatePayload): Promise<Role> {
return this.atomicPhase_(async (manager) => {
// omitting validation for simplicity
const { permissions: permissionsData = [] } = data
delete data.permissions
const roleRepo = manager.withRepository(
this.roleRpository_
)
const role = roleRepo.create(data)
role.permissions = []
for (const permissionData of permissionsData) {
role.permissions.push(
await this.permissionService_.create(
permissionData
)
)
}
const result = await roleRepo.save(role)
return await this.retrieve(result.id)
})
}
async associateUser(
role_id: string,
user_id: string
): Promise<Role> {
return this.atomicPhase_(async () => {
// omitting validation for simplicity
await this.userService_.update(user_id, {
role_id,
})
return await this.retrieve(role_id)
})
}
}
export default RoleService
```
This creates the `RoleService` with three methods:
- `retrieve`: Retrieves a role with its relations.
- `create`: Creates a new role and, if provided, its permissions as well.
- `associateUser`: associates a user with a role.
Now, you can create the endpoints.
Start by creating the file `src/api/routes/admin/role/create-role.ts` with the following content:
```ts title=src/api/routes/admin/role/create-role.ts
import { Request, Response } from "express"
import RoleService from "../../../../services/role"
export default async (req: Request, res: Response) => {
// omitting validation for simplicity
const {
name,
store_id,
permissions = [],
} = req.body
const roleService = req.scope.resolve(
"roleService"
) as RoleService
const role = await roleService.create({
name,
store_id,
permissions,
})
res.json(role)
}
```
This creates the Create Role endpoint that uses the `RoleService` to create a new role. Notice that validation of received body parameters is omitted for simplicity.
Next, create the file `src/api/routes/admin/role/associate-user.ts` with the following content:
```ts title=src/api/routes/admin/role/associate-user.ts
import { Request, Response } from "express"
import RoleService from "../../../../services/role"
export default async (req: Request, res: Response) => {
// omitting validation for simplicity purposes
const {
id,
user_id,
} = req.params
const roleService = req.scope.resolve(
"roleService"
) as RoleService
const role = await roleService.associateUser(id, user_id)
res.json(role)
}
```
This creates the Associate User endpoint that uses the `RoleService` to associate a role with a user.
You now have to register and export these endpoints.
To do that, create the file `src/api/routes/admin/role/index.ts` with the following content:
```ts title=src/api/routes/admin/role/index.ts
import { wrapHandler } from "@medusajs/utils"
import { Router } from "express"
import createRole from "./create-role"
import associateUser from "./associate-user"
const router = Router()
export default (adminRouter: Router) => {
adminRouter.use("/roles", router)
router.post("/", wrapHandler(createRole))
router.post("/:id/user/:user_id", wrapHandler(associateUser))
}
```
This adds the create role endpoint under the path `/admin/roles`, and the associate user endpoint under the path `/admin/roles/:id/user/:user_id`, where `:id` is the ID of the role and `:user_id` is the ID of the user to associate with the role.
Finally, you can either export these routes in `src/api/routes/admin/index.ts` or, if the file is not available in your project, in `src/api/index.ts`:
```ts title=src/api/routes/admin/index.ts
import roleRouter from "./role"
const router = Router()
export function attachAdminRoutes(adminRouter: Router) {
roleRouter(adminRouter)
// ....
}
```
To test it out, run the `build` command in the root directory of your Medusa backend project:
```bash npm2yarn
npm run build
```
Then, start the backend with the following command:
```bash
npx medusa develop
```
Try first to log in using the [Admin User Login endpoint](https://docs.medusajs.com/api/admin#auth_postauth) with an existing admin user. Then, send a `POST` request to the `localhost:9000/admin/roles` endpoint with the following request body parameters:
```json
{
"store_id": "store_01H8XPDY8WA1Z650MZSEY4Y0V0",
"name": "Product Manager",
"permissions": [
{
"name": "Allow Products",
"metadata": {
"/products": true
}
}
]
}
```
Make sure to replace the `store_id`'s value with your stores ID. You can retrieve the stores ID using the [Get Store Details endpoint](https://docs.medusajs.com/api/admin#store_getstore).
This will create a new role with a permission that allows users of this role to access the `/admin/products` endpoint. As mentioned before, because of the middlewares implementation, you must specify the path without the `/admin` prefix. If you chose to implement this differently, such as with regular expressions, then change the permissions metadata accordingly.
Next, create a new user using the [Create User endpoint](https://docs.medusajs.com/api/admin#users_postusers). Then, send a `POST` request to `localhost:9000/admin/roles/<role_id>/user/<user_id>`, where `<role_id>` is the ID of the role you created, and `<user_id>` is the ID of the user you created. This will associate the user with the role you created.
Finally, login with the user you created, then try to access any endpoint other than `/admin/products`. Youll receive a `401` unauthorized response. Then, try to access the [List Products endpoint](https://docs.medusajs.com/api/admin#products_getproducts), and the user should be able to access it as expected.
</details>
---
## Additional Development
If your use case requires other changes or functionality implementations, check out the [Medusa Development section](../../../development/overview.mdx) of the documentation for all available development guides.

View File

@@ -0,0 +1,195 @@
---
description: "Learn how to send an invitation email to an invited user. This guide uses SendGrid as an example."
addHowToData: true
---
# How to Send an Invitation Email
In this document, youll learn how to send an invitation email to an invited user.
## Overview
Users can be invited to join a store by other users. When a new invite is created, the `invite.created` event is triggered. This event is also triggered when an invite is resent.
This guide explains how to subscribe to that event and send an email to the new user with the invitation link. The guide uses SendGrid as an example of illustration, but you can use any other notification service.
---
## Prerequisites
### Event Bus Module
The event bus module trigger the event to the listening subscribers. So, its required to have an event bus module installed and configured on your Medusa backend.
The [Local Event Bus module](../../../development/events/modules/local.md) works in a development environment. For production, its recommended to use the [Redis Event Bus module](../../../development/events/modules/redis.md).
### Notification Provider
As mentioned in the overview, this guide illustrates how to send the email using SendGrid. If you intend to follow along, you must have the [SendGrid plugin](../../../plugins/notifications/sendgrid.mdx) installed and configured.
You can also find other available Notification provider plugins in the [Plugins directory](https://medusajs.com/plugins/), or [create your own](../../../development/notification/create-notification-provider.md).
---
## Step 1: Create the Subscriber
To subscribe to and handle an event, you must create a subscriber.
:::tip
You can learn more about subscribers in the [Subscribers documentation](../../../development/events/subscribers.mdx).
:::
Create the file `src/subscribers/invite.ts` with the following content:
```ts title=src/subscribers/invite.ts
type InjectedDependencies = {
// TODO add necessary dependencies
}
class InviteSubscriber {
constructor(container: InjectedDependencies) {
// TODO subscribe to event
}
}
export default InviteSubscriber
```
Youll be adding in the next step the necessary dependencies to the subscriber.
:::tip
You can learn more about dependency injection in [this documentation](../../../development/fundamentals/dependency-injection.md).
:::
---
## Step 2: Subscribe to the Event
In this step, youll subscribe to the `invite.created` event to send the user the invitation email.
There are two ways to do this:
### Method 1: Using the NotificationService
If the notification provider youre using already implements the logic to handle this event, you can subscribe to the event using the `NotificationService`:
```ts title=src/subscribers/invite.ts
import { NotificationService } from "@medusajs/medusa"
type InjectedDependencies = {
notificationService: NotificationService
}
class InviteSubscriber {
constructor({ notificationService }: InjectedDependencies) {
notificationService.subscribe(
"invite.created",
"<NOTIFICATION_PROVIDER_IDENTIFIER>"
)
}
}
export default InviteSubscriber
```
Where `<NOTIFICATION_PROVIDER_IDENTIFIER>` is the identifier for your notification provider.
:::tip
You can learn more about handling events with the Notification Service using [this documentation](../../../development/notification/create-notification-provider.md).
:::
### Method 2: Using the EventBusService
If the notification provider youre using isnt configured to handle this event, or you want to implement some other custom logic, you can subscribe to the event using the `EventBusService`:
```ts title=src/subscribers/invite.ts
import { EventBusService } from "@medusajs/medusa"
type InjectedDependencies = {
eventBusService: EventBusService
}
class InviteSubscriber {
constructor({ eventBusService }: InjectedDependencies) {
eventBusService.subscribe(
"invite.created",
this.handleInvite
)
}
handleInvite = async (data: Record<string, any>) => {
// TODO: handle event
}
}
export default InviteSubscriber
```
When using this method, youll have to handle the logic of sending the invitation email inside the handler function, which in this case is `handleInvite`.
---
## Step 3: Handle the Event
The `handleInvite` method receives a `data` object as a parameter which is a payload emitted when the event was triggered. This object has the following properties:
- `id`: a string indicating the ID of the invite.
- `token`: a string indicating the token of the invite. This token is useful to pass along to a frontend link that can be used to accept the invite.
- `user_email`: a string indicating the email of the invited user.
In this method, you should typically send an email to the invited user. You can place any content in the email, but typically you would include a link to your frontend that allows the invited user to enter their details and accept the invite.
### Example: Using SendGrid
For example, you can implement this subscriber to send emails using SendGrid:
```ts title=src/subscribers/invite.ts
import { EventBusService } from "@medusajs/medusa"
type InjectedDependencies = {
eventBusService: EventBusService
sendgridService: any
}
class InviteSubscriber {
protected sendGridService: any
constructor({
eventBusService,
sendgridService,
}: InjectedDependencies) {
this.sendGridService = sendgridService
eventBusService.subscribe(
"invite.created",
this.handleInvite
)
}
handleInvite = async (data: Record<string, any>) => {
this.sendGridService.sendEmail({
templateId: "send-invite",
from: "hello@medusajs.com",
to: data.user_email,
dynamic_template_data: {
// any data necessary for your template...
token: data.token,
},
})
}
}
export default InviteSubscriber
```
Notice that you should replace the values in the object passed to the `sendEmail` method:
- `templateId`: Should be the ID of your invitation email template in SendGrid.
- `from`: Should be the from email.
- `to`: Should be the invited users email.
- `data`: Should be an object holding any data that should be passed to your SendGrid email template. In the example above, you pass the token, which you can use in the SendGrid template to format the frontend link (for example, `<FRONTEND_LINK>/invite?token={{token}}`, where `<FRONTEND_LINK>` is your frontends hostname.)

View File

@@ -0,0 +1,118 @@
---
description: "Users are admins that can manage the ecommerce stores data and operations. Learn about the available features and guides."
---
import DocCardList from '@theme/DocCardList';
import DocCard from '@theme/DocCard';
import Icons from '@theme/Icon';
# Users
Users are admins that can manage the ecommerce stores data and operations. This overview introduces the available features related to users.
:::note
Not a developer? Check out the [Users user guide](../../user-guide/users/index.md).
:::
## Features
### Team Management
There can be more than one admin in the team managing the ecommerce store. Admins can manage other users in that team.
Admins can also manage their profile details.
<DocCardList colSize={6} items={[
{
type: 'link',
href: '/modules/users/admin/manage-users',
label: 'Admin: Manage Users',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to manage users using Admin APIs.',
}
},
{
type: 'link',
href: '/user-guide/users/team',
label: 'User Guide: Manage Team',
customProps: {
icon: Icons['users-solid'],
description: 'Learn how to manage the team in Medusa Admin.'
}
},
{
type: 'link',
href: '/modules/users/admin/manage-profile',
label: 'Admin: Implement Profiles',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to implement user profiles using Admin APIs.',
}
},
{
type: 'link',
href: '/user-guide/users/profile',
label: 'User Guide: Manage Profile',
customProps: {
icon: Icons['users-solid'],
description: 'Learn how to manage the user\'s profile in Medusa Admin.'
}
},
]} />
### User Invites
Admins can invite users to join their team. Invites can be resent, accepted, or removed.
- Admin: Manage Invites
- User Guide: Manage Invites
- Backend: Send Invite
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/modules/users/admin/manage-invites',
label: 'Admin: Manage Invites',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to manage invites using Admin APIs.',
}
},
{
type: 'link',
href: '/user-guide/users/team#manage-invites',
label: 'User Guide: Manage Invites',
customProps: {
icon: Icons['users-solid'],
description: 'Learn how to manage invites using Medusa Admin.',
}
},
{
type: 'link',
href: '/modules/users/backend/send-invite',
label: 'Backend: Send Invite',
customProps: {
icon: Icons['users-solid'],
description: 'Learn how to send invites in the backend.',
}
},
]} />
---
## Understand the Architecture
Learn how user-related entities and concepts are built, their relation to other modules, and more.
<DocCard item={{
type: 'link',
href: '/modules/users',
label: 'Architecture: User',
customProps: {
icon: Icons['circle-stack-solid'],
description: 'Learn about the User Architecture.',
}
}} />

View File

@@ -0,0 +1,75 @@
---
description: "Users are admins that can manage the ecommerce stores data and operations. Learn about the available features and guides."
---
# Users Architecture Overview
In this document, youll learn about the users architecture and invites in Medusa.
## Overview
A user is an admin that can view and process sensitive and private information in the commerce store. A store in Medusa can have more than one user. Users can create or invite other users to manage the store.
:::tip
A user is typically referred to as “admin” throughout the documentation and user guide.
:::
---
## User Entity Overview
Some of the `User` entity attributes include:
- `email`: a unique string indicating the email of the user.
- `password_hash`: a string indicating the encrypted password of the user. Passwords are encrypted using the [scrypt-kdf NPM package](https://www.npmjs.com/package/scrypt-kdf). The password hash is nullable, which can be useful if you want to integrate a third-party authentication service that does not require a password.
- `first_name`: a string indicating the users first name.
- `last_name`: a string indicating the users last name.
- `api_token`: a string that holds the users API token. The API token can be used to send authenticated requests to admin endpoints, instead of using cookie session authentication. Check out the [API reference](https://docs.medusajs.com/api/admin#authentication) to learn how to use it.
- `role`: a string that indicates the role of the user. Its value can be either `admin`, `member`, or `developer`.
:::note
The `role` attribute does not actually provide permission or Access Control List (ACL) features within Medusa.
:::
---
## Invites Overview
A user can create other users where they specify the users details and credentials, and the new user can immediately authenticate using their credentials.
Alternatively, a user can invite another user to join by just supplying the new users email. Then, the new user can accept the invite and provide their credentials.
### Invite Entity Overview
An invitation is represented by the `Invite` entity. Some of its attributes include:
- `user_email`: a string indicating the email of the user.
- `role`: a string indicating the role of the user. Similar to the `User` entitys `role` attribute, its value can be either `admin`, `member`, or `developer`.
- `accepted`: a boolean value indicating whether the invite has been accepted.
- `token`: a string that is automatically generated when the invite is created. Its a hash that is used to later accept the invitation.
- `expires_at`: a date indicating when the invitation expires.
### Invite Process Overview
You have full freedom in how you choose to implement the invite flow. This section explains how its implemented within the Medusa backend.
![User Invitation Flow](https://res.cloudinary.com/dza7lstvk/image/upload/v1683100772/Medusa%20Docs/Diagrams/invite-flow_gm4hkb.jpg)
The invitation process typically follows these steps in the Medusa backend:
1. A user creates an invite either using the [Create Invite endpoint](https://docs.medusajs.com/api/admin#invites_postinvites) or the `InviteService`'s `create` method. Part of creating an invite includes generating the token and setting the expiry date. By default, the expiry date is set to a week after the date of invitation creation.
2. The new user receives the invite, typically through their email (although this is not implemented by default within the Medusa backend). The new user has to provide their details and password. The invite can be accepted either using the [Accept Invite endpoint](https://docs.medusajs.com/api/admin#invites_postinvitesinviteaccept) or using the `InviteService`'s `accept` method.
3. When the new user accepts the invite, the invitation is validated first to ensure its not expired. If its not expired, a new user is created using the `UserService`'s [create method](../../references/services/classes/UserService.md#create).
If an invitation is expired, an existing user can resend the invite either using the Resend Invite endpoint or using the `InviteService`'s resend method. This would generate a new token and reset the expiry date.
---
## See Also
- [How to send an invitation email](./backend/send-invite.md)
- [How to implement user profiles](./admin/manage-profile.mdx)