docs: update endpoints to use file-routing approach (#5397)

- Move the original guides for creating endpoints and middlewares to sub-sections in the Endpoints category.
- Replace existing guides for endpoints and middlewares with the new approach.
- Update all endpoints-related snippets across docs to use this new approach.
This commit is contained in:
Shahed Nasser
2023-10-19 15:56:26 +00:00
committed by GitHub
parent b38f73726d
commit c28935b4e8
170 changed files with 3658 additions and 3344 deletions
@@ -46,7 +46,7 @@ If you follow the Medusa React code blocks, it's assumed you already have [Medus
### 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.
Except for the Accept Invite API Route, 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).
@@ -54,7 +54,7 @@ You can learn more about [authenticating as an admin user in the API reference](
## List Invites
You can list invites by sending a request to the [List Invite endpoint](https://docs.medusajs.com/api/admin#invites_getinvites):
You can list invites by sending a request to the [List Invite API Route](https://docs.medusajs.com/api/admin#invites_getinvites):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
@@ -117,15 +117,15 @@ curl -L -X GET '<BACKEND_URL>/admin/invites' \
</TabItem>
</Tabs>
This endpoint does not accept any parameters.
This API Route doesn't accept any parameters.
The request returns an array of invite endpoints.
The request returns an array of invite objects.
---
## Create Invite
You can create an invite by sending a request to the [Create Invite endpoint](https://docs.medusajs.com/api/admin#invites_postinvites):
You can create an invite by sending a request to the [Create Invite API Route](https://docs.medusajs.com/api/admin#invites_postinvites):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
@@ -200,7 +200,7 @@ curl -L -X POST '<BACKEND_URL>/admin/invites' \
</TabItem>
</Tabs>
This endpoint requires the following body parameters:
This API Route 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`.
@@ -213,7 +213,7 @@ The request does not return any data. If the invite was created successfully, th
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):
You can accept an invite by sending a request to the [Accept Invite API Route](https://docs.medusajs.com/api/admin#invites_postinvitesinviteaccept):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
@@ -303,7 +303,7 @@ curl -L -X POST '<BACKEND_URL>/admin/invites/accept' \
</TabItem>
</Tabs>
This endpoint requires the following request body parameters:
This API Route requires the following request body parameters:
- `token`: a string indicating the invitations token.
- `user`: an object that has the following properties:
@@ -317,7 +317,7 @@ The request does not return any data. If the invite was accepted successfully, t
## 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):
You can resend an invite if its not accepted yet. To resend an invite, send a request to the [Resend Invite API Route](https://docs.medusajs.com/api/admin#invites_postinvitesinviteresend):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
@@ -374,15 +374,15 @@ curl -L -X POST '<BACKEND_URL>/admin/invites/<INVITE_ID>/resend' \
</TabItem>
</Tabs>
This endpoint requires the invite ID as a path parameter.
This API Route 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`.
The request doesn't 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):
You can delete an invite by sending a request to the [Delete Invite API Route](https://docs.medusajs.com/api/admin#invites_deleteinvitesinvite):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
@@ -439,7 +439,7 @@ curl -L -X DELETE '<BACKEND_URL>/admin/invites/<INVITE_ID>' \
</TabItem>
</Tabs>
This endpoint requires the invite ID as a path parameter.
This API Route requires the invite ID as a path parameter.
It deletes the invite and returns the following fields:
@@ -42,7 +42,7 @@ If you follow the Medusa React code blocks, it's assumed you already have [Medus
### Authenticated Admin User
Aside from the User Login and Reset Password steps, other endpoints require you to be an authenticated admin user.
Aside from the User Login and Reset Password steps, other API Routes 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).
@@ -52,7 +52,7 @@ You can learn more about [authenticating as an admin user in the API reference](
### 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):
You can log in a user by sending a request to the [User Login API Route](https://docs.medusajs.com/api/admin#auth_postauth):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
@@ -126,7 +126,7 @@ curl -L -X POST '<BACKEND_URL>/admin/auth' \
</TabItem>
</Tabs>
This endpoint requires the following request body parameters:
This API Route requires the following request body parameters:
- `email`: a string indicating the users email.
- `password`: a string indicating the users password.
@@ -135,7 +135,7 @@ 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):
You can log out a user by sending a request to the [User Logout API Route](https://docs.medusajs.com/api/admin#auth_deleteauth):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
@@ -192,15 +192,15 @@ curl -L -X DELETE '<BACKEND_URL>/admin/auth' \
</TabItem>
</Tabs>
The endpoint does not require any path or query parameters.
The API Route doesn't require any path or query parameters.
The request does not return any data. The response code will be `200` for successful log out.
The request doesn't 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):
You can retrieve the current users details for their profile by sending a request to the [Get Current User API Route](https://docs.medusajs.com/api/admin#auth_getauth):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
@@ -256,7 +256,7 @@ curl -L -X GET '<BACKEND_URL>/admin/auth' \
</TabItem>
</Tabs>
This endpoint does not require any parameters.
This API Route doesn't require any parameters.
The request returns the current user as an object.
@@ -264,7 +264,7 @@ 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):
You can update a users details in their profile by sending a request to the [Update User API Route](https://docs.medusajs.com/api/admin#users_postusersuser):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
@@ -338,7 +338,7 @@ curl -L -X POST '<BACKEND_URL>/admin/users/<USER_ID>' \
</TabItem>
</Tabs>
This endpoint requires the ID of the user as a path parameter.
This API Route 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.
@@ -360,7 +360,7 @@ Sending the password reset email is not handled by default in the Medusa backend
:::
You can request a password reset by sending a request to the [Request Password Reset endpoint](https://docs.medusajs.com/api/admin#users_postusersuserpasswordtoken):
You can request a password reset by sending a request to the [Request Password Reset API Route](https://docs.medusajs.com/api/admin#users_postusersuserpasswordtoken):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
@@ -430,7 +430,7 @@ curl -L -X POST '<BACKEND_URL>/admin/users/password-token' \
</TabItem>
</Tabs>
This endpoint requires the `email` parameter in the request body, which is the email of the user requesting to reset their password.
This API Route 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.
@@ -438,7 +438,7 @@ The request does not return any data. The response code will be `204` if the req
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):
You can reset the password by sending a request to the [Reset Password API Route](https://docs.medusajs.com/api/admin#users_postusersuserpassword):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
@@ -512,7 +512,7 @@ curl -L -X POST '<BACKEND_URL>/admin/users/reset-password' \
</TabItem>
</Tabs>
This endpoint requires the following request body parameters:
This API Route requires the following request body parameters:
- `token`: a string indicating the password reset token.
- `password`: a string indicating the new password for the user.
@@ -53,7 +53,7 @@ You can learn more about [authenticating as an admin user in the API reference](
## 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):
You can retrieve users in a store by sending a request to the [List Users API Route](https://docs.medusajs.com/api/admin#users_getusers):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
@@ -116,7 +116,7 @@ curl -L -X GET '<BACKEND_URL>/admin/users' \
</TabItem>
</Tabs>
This endpoint does not require any parameters.
This API Route doesn't require any parameters.
The request returns an array of user objects.
@@ -124,7 +124,7 @@ 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):
You can create a user by sending a request to the [Create User API Route](https://docs.medusajs.com/api/admin#users_postusers):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
@@ -199,12 +199,12 @@ curl -L -X POST '<BACKEND_URL>/admin/users' \
</TabItem>
</Tabs>
This endpoint requires the following request body parameters:
This API Route 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 API Route 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.
@@ -212,7 +212,7 @@ 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):
You can update a users details by sending a request to the [Update User API Route](https://docs.medusajs.com/api/admin#users_postusersuser):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
@@ -283,7 +283,7 @@ curl -L -X POST '<BACKEND_URL>/admin/users/<USER_ID>' \
</TabItem>
</Tabs>
This endpoint requires the ID of the user as a path parameter.
This API Route 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.
@@ -293,7 +293,7 @@ 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):
You can delete a user by sending a request to the [Delete User API Route](https://docs.medusajs.com/api/admin#users_deleteusersuser):
<Tabs groupId="request-type" isCodeTabs={true}>
<TabItem value="client" label="Medusa JS Client" default>
@@ -350,7 +350,7 @@ curl -L -X DELETE '<BACKEND_URL>/admin/users/<USER_ID>' \
</TabItem>
</Tabs>
This endpoint requires the user ID as a path parameter.
This API Route requires the user ID as a path parameter.
It deletes the user and returns the following fields:
@@ -333,13 +333,13 @@ This will reflect the entity changes in your database.
## 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.
To ensure that users who have the privilege can access an API Route, 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 API Route.
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',
href: '/development/api-routes/add-middleware',
label: 'Create a Middleware',
customProps: {
icon: Icons['academic-cap-solid'],
@@ -350,18 +350,26 @@ Since the Medusa backend uses Express, you can create a middleware and attach it
<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.
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 API Route.
Create the file `src/api/middlewares/permission.ts` with the following content:
Create the file `src/api/middlewares.ts` with the following content:
```ts title=src/api/middlewares/permission.ts
import { UserService } from "@medusajs/medusa"
import { NextFunction, Request, Response } from "express"
```ts title=src/api/middlewares.ts
import type {
MiddlewaresConfig,
UserService,
} from "@medusajs/medusa"
import express from "express"
import type {
MedusaRequest,
MedusaResponse,
MedusaNextFunction,
} from "@medusajs/medusa"
export default async (
req: Request,
res: Response,
next: NextFunction
export const permissions = async (
req: MedusaRequest,
res: MedusaResponse,
next: MedusaNextFunction
) => {
if (!req.user || !req.user.userId) {
next()
@@ -406,48 +414,38 @@ export default async (
// deny access
res.sendStatus(401)
}
export const config: MiddlewaresConfig = {
routes: [
{
matcher: "/admin/*",
middlewares: [permissions],
},
],
}
```
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.
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 API Route. Here, you presume that logged-in users who dont have a role are “super-admin” users who can access all API Routes. 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.
If theres a logged-in user that has a role, you check that the roles permissions give them access to the current API Route. 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).
Notice that you use `req.path` here to get the current API Route path. However, in middlewares, this doesnt include the mount point which is `/admin`. So, for example, if the API Route 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.
After defining the middleware, you apply it on all API Routes starting with `/admin/`.
</details>
---
## Create Endpoints and Services
## Create API Routes and Services
To manage the roles and permissions, youll need to create custom endpoints, typically for Create, Read, Update, and Delete (CRUD) operations.
To manage the roles and permissions, youll need to create custom API Routes, 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.
@@ -456,11 +454,11 @@ Furthermore, you may need to extend core services if you need to perform actions
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/development/endpoints/create',
label: 'Create Endpoint',
href: '/development/api-routes/create',
label: 'Create API Route',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to create an endpoint in Medusa.',
description: 'Learn how to create an API Route in Medusa.',
}
},
{
@@ -488,9 +486,9 @@ Furthermore, you may need to extend core services if you need to perform actions
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.
In this example, youll only implement two API Routes for simplicity: create role API Route that create a new role with permissions, and associate user API Route 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.
Youll also create basic services for `Role` and `Permission` to perform the functionalities of each of these API Routes and extend the core `UserService` to allow associating roles with users.
Start by creating the file `src/services/permission.ts` with the following content:
@@ -663,15 +661,21 @@ This creates the `RoleService` with three methods:
- `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.
Now, you can create the API Routes.
Start by creating the file `src/api/routes/admin/role/create-role.ts` with the following content:
Start by creating the file `src/api/admin/roles/route.ts` with the following content:
```ts title=src/api/routes/admin/role/create-role.ts
import { Request, Response } from "express"
```ts title=src/api/admin/roles/route.ts
import type {
MedusaRequest,
MedusaResponse,
} from "@medusajs/medusa"
import RoleService from "../../../../services/role"
export default async (req: Request, res: Response) => {
export const POST = async (
req: MedusaRequest,
res: MedusaResponse
) => {
// omitting validation for simplicity
const {
name,
@@ -693,15 +697,21 @@ export default async (req: Request, res: Response) => {
}
```
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.
This creates the Create Role API Route at `/admin/roles` 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:
Next, create the file `src/api/routes/admin/roles/[id]/user/[user_id]/route.ts` with the following content:
```ts title=src/api/routes/admin/role/associate-user.ts
import { Request, Response } from "express"
```ts title=src/api/routes/admin/roles/[id]/user/[user_id]/route.ts
import type {
MedusaRequest,
MedusaResponse,
} from "@medusajs/medusa"
import RoleService from "../../../../services/role"
export default async (req: Request, res: Response) => {
export const POST = async (
req: MedusaRequest,
res: MedusaResponse
) => {
// omitting validation for simplicity purposes
const {
id,
@@ -717,44 +727,9 @@ export default async (req: Request, res: Response) => {
}
```
This creates the Associate User endpoint that uses the `RoleService` to associate a role with a user.
This creates the Associate User API Route at `/admin/roles/[id]/user/[user_id]` 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:
To test the API Routes out, run the `build` command in the root directory of your Medusa backend project:
```bash npm2yarn
npm run build
@@ -766,30 +741,30 @@ Then, start the backend with the following command:
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:
Try first to log in using the [Admin User Login API Route](https://docs.medusajs.com/api/admin#auth_postauth) with an existing admin user. Then, send a `POST` request to the `localhost:9000/admin/roles` API Route with the following request body parameters:
```json
{
"store_id": "store_01H8XPDY8WA1Z650MZSEY4Y0V0",
"name": "Product Manager",
"permissions": [
{
"name": "Allow Products",
"metadata": {
"/products": true
}
}
]
"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).
Make sure to replace the `store_id`'s value with your stores ID. You can retrieve the stores ID using the [Get Store Details API Route](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.
This will create a new role with a permission that allows users of this role to access the `/admin/products` API Route. 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.
Next, create a new user using the [Create User API Route](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.
Finally, login with the user you created, then try to access any API Route other than `/admin/products`. Youll receive a `401` unauthorized response. Then, try to access the [List Products API Route](https://docs.medusajs.com/api/admin#products_getproducts), and the user should be able to access it as expected.
</details>
+4 -4
View File
@@ -26,7 +26,7 @@ Some of the `User` entity attributes include:
- `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.
- `api_token`: a string that holds the users API token. The API token can be used to send authenticated requests to admin API Routes, 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
@@ -61,11 +61,11 @@ You have full freedom in how you choose to implement the invite flow. This secti
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.
1. A user creates an invite either using the [Create Invite API Route](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 API Route](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.
If an invitation is expired, an existing user can resend the invite either using the Resend Invite API Route or using the `InviteService`'s resend method. This would generate a new token and reset the expiry date.
---