@@ -352,6 +356,62 @@ Payment and fulfillment providers are associated with regions, which are not ass
---
## Customize Admin
As you add marketplace features to your store, you'll most likely need to customize the admin to provide an interface to manage these features.
Medusa's [admin plugin](../admin/quickstart.mdx) can be extended to add widgets or new blocks to existing pages, add UI routes to add new pages, or add setting pages.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/admin/widgets',
label: 'Create Admin Widget',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to add widgets into existing admin pages.',
}
},
{
type: 'link',
href: '/admin/routes',
label: 'Create Admin UI Routes',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to add new pages to your Medusa admin.',
}
},
{
type: 'link',
href: '/admin/setting-pages',
label: 'Create Admin Setting Page',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to add new page to the Medusa admin settings.',
}
},
]} />
---
## Implement Role-Based Access Control
In your marketplace, you may need to implement role-based access control (RBAC) within stores. This will restrict some users' permissions to specified functionalities or endpoints.
If you want to implement this functionality, you can follow the RBAC recipe.
<DocCard item={{
type: 'link',
href: '/recipes/rbac',
label: 'RBAC Recipe',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to implement role-based access control (RBAC) in Medusa.',
}
}} />
---
## Build a Storefront
Medusa provides a Next.js Starter Template that you can use with Medusa. Since you've customized your Medusa project, you'll need to either customize the existing Next.js Starter Template, or create a custom storefront.
import LearningPath from '@site/src/components/LearningPath';
# Role-Based Access Control (RBAC) Recipe
This document guides you through the different documentation resources that will help you build a marketplace with Medusa.
## 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](./marketplace.mdx).
This recipe gives you a high-level approach to implementing RBAC in Medusa. The examples included in this recipe provide a simple implementation to give you an idea of how you can implement this functionality in your Medusa backend.
You may also follow this path that takes you through the different documentation pages that will help you to implement RBAC in Medusa.
<LearningPath pathName="rbac" />
---
## 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 you’ll 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). You’ll 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
This creates the `Role` entity. You’ll see errors in your editors, which you’ll 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 you’re 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, you’ll extend the `User` and `Store` entities. As mentioned earlier, extending the `Store` entity and adding the relation is only useful if you’re implementing RBAC in a marketplace or similar use cases. So, if this doesn’t 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
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:
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"`)
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, you’ll create a middleware that runs on all admin-authenticated routes and checks the logged-in user’s 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"
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 don’t have a role are “super-admin” users who can access all endpoints. You may choose to implement this differently.
If there’s a logged-in user that has a role, you check that the role’s permissions give them access to the current endpoint. You do that by checking if a permission’s metadata has a key with the same request’s path. It may be better here to check for matching using regular expressions, for example, to check routes with path parameters.
Otherwise, if the user’s role doesn’t 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 doesn’t 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 [Express’s 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"
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, you’ll need to create custom endpoints, typically for Create, Read, Update, and Delete (CRUD) operations.
You’ll 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 you’ve 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, you’ll 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.
You’ll 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 {
This extends the core `UserService` to allow updating a user’s 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 {
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:
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 store’s ID. You can retrieve the store’s 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 middleware’s 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 permission’s 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`. You’ll 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.
@@ -113,6 +113,44 @@ Implementing the logic depends on your use case, but you'll mainly need to do tw
---
## Customize Admin
As you add subscription features to your store, you'll most likely need to customize the admin to provide an interface to manage these features.
Medusa's [admin plugin](../admin/quickstart.mdx) can be extended to add widgets or new blocks to existing pages, add UI routes to add new pages, or add setting pages.
<DocCardList colSize={4} items={[
{
type: 'link',
href: '/admin/widgets',
label: 'Create Admin Widget',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to add widgets into existing admin pages.',
}
},
{
type: 'link',
href: '/admin/routes',
label: 'Create Admin UI Routes',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to add new pages to your Medusa admin.',
}
},
{
type: 'link',
href: '/admin/setting-pages',
label: 'Create Admin Setting Page',
customProps: {
icon: Icons['academic-cap-solid'],
description: 'Learn how to add new page to the Medusa admin settings.',
}
},
]} />
---
## Build a Storefront
Medusa provides a Next.js Starter Template that you can use with Medusa. Since you've customized your Medusa project, you'll need to either customize the existing Next.js Starter Template, or create a custom storefront.
"In your marketplace, you may need to implement role-based access control (RBAC) within stores. This will restrict some users' permissions to specified functionalities or endpoints.",
description:"Implement roles and permissions for admin users in Medusa",
steps:[
{
title:"Create Role and Permission Entities",
path:"/development/entities/create",
description:
"When implementing RBAC, you typically require the availability of roles and permissions, both of which would require new entities. 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.",
"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.",
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.