docs: added B2B recipe (#4901)
* added b2b recipe * added redirect rule * fix build errors * fix broken links
This commit is contained in:
@@ -0,0 +1,457 @@
|
||||
---
|
||||
addHowToData: true
|
||||
---
|
||||
|
||||
import DocCardList from '@theme/DocCardList';
|
||||
import DocCard from '@theme/DocCard';
|
||||
import Icons from '@theme/Icon';
|
||||
import LearningPath from '@site/src/components/LearningPath';
|
||||
|
||||
# B2B / Wholesale Recipe
|
||||
|
||||
This document guides you through the different documentation resources that will help you build a B2B store with Medusa.
|
||||
|
||||
## Overview
|
||||
|
||||
In a B2B store, the seller provides other businesses with wholesale products and prices. Medusa allows you to build a B2B store in different ways:
|
||||
|
||||
1. **Fully B2B:** You can use Medusa as-is and cater to businesses only. You can also specify different pricing for different businesses using [Customer Groups](../user-guide/customers/groups.mdx) and [Price Lists](../user-guide/price-lists/index.md).
|
||||
2. **B2B and B2C:** You can serve both businesses and customers within the same store, supplying different products or prices for each.
|
||||
|
||||
This recipe covers the high-level steps to implement the second case, a B2B and B2C store.
|
||||
|
||||
<LearningPath pathName="b2b" />
|
||||
|
||||
---
|
||||
|
||||
## Create B2B Sales Channel
|
||||
|
||||
In Medusa, a sales channel allows you to set product availability per channel. In this case, you can create a B2B sales channel that will include only your wholesale products.
|
||||
|
||||
You can create a sales channel either through the Medusa admin or through the Admin REST APIs.
|
||||
|
||||
<DocCardList colSize={6} items={[
|
||||
{
|
||||
type: 'link',
|
||||
href: '/user-guide/sales-channels/manage',
|
||||
label: 'Option 1: Use Medusa Admin',
|
||||
customProps: {
|
||||
icon: Icons['users-solid'],
|
||||
description: 'Create the sales channel using the Medusa admin.',
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/modules/sales-channels/admin/manage',
|
||||
label: 'Option 2: Using the REST APIs',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Create the sales channel using the REST APIs.',
|
||||
}
|
||||
},
|
||||
]} />
|
||||
|
||||
---
|
||||
|
||||
## Create a Publishable API Key
|
||||
|
||||
Publishable API keys can be associated with one or more sales channels. Then, in a client such as a storefront, you can pass the publishable API key in the header of your requests to ensure all products retrieved belong to the associated sales channel(s).
|
||||
|
||||
You can create a publishable API key either through the Medusa admin or through the Admin REST APIs.
|
||||
|
||||
<DocCardList colSize={6} items={[
|
||||
{
|
||||
type: 'link',
|
||||
href: '/user-guide/settings/publishable-api-keys',
|
||||
label: 'Option 1: Use Medusa Admin',
|
||||
customProps: {
|
||||
icon: Icons['users-solid'],
|
||||
description: 'Create the publishable API key using the Medusa admin.',
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/development/publishable-api-keys/admin/manage-publishable-api-keys',
|
||||
label: 'Option 2: Using the REST APIs',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Create the publishable API key using the REST APIs.',
|
||||
}
|
||||
},
|
||||
]} />
|
||||
|
||||
---
|
||||
|
||||
## Add Wholesale Products
|
||||
|
||||
Using the Medusa admin or the Admin REST APIs, you can add your wholesale products to your store. You can also use the Product Import feature to import your products from an existing CSV file.
|
||||
|
||||
After or while you add your products, make sure to set the products’ availability to the B2B sales channel you’ve created.
|
||||
|
||||
<DocCardList colSize={6} items={[
|
||||
{
|
||||
type: 'link',
|
||||
href: '/user-guide/products/manage',
|
||||
label: 'Add Products Using Medusa Admin',
|
||||
customProps: {
|
||||
icon: Icons['users-solid'],
|
||||
description: 'Create the product using the Medusa admin.',
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/modules/products/admin/manage-products',
|
||||
label: 'Add Products Using REST APIs',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Create the product using the REST APIs.',
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/user-guide/products/import',
|
||||
label: 'Import Products Using Medusa Admin',
|
||||
customProps: {
|
||||
icon: Icons['users-solid'],
|
||||
description: 'Import the products using the Medusa admin.',
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/modules/products/admin/import-products',
|
||||
label: 'Import Products Using REST APIs',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Import the product using the REST APIs.',
|
||||
}
|
||||
},
|
||||
]} />
|
||||
|
||||
---
|
||||
|
||||
## Create B2B Customer Groups
|
||||
|
||||
To apply different prices for your B2B customers, you need to create a customer group that indicates this customer is a B2B customer.
|
||||
|
||||
You can either create a single B2B customer group that all your B2B customers will fall into, or you can create different B2B customer groups for every B2B customer. The second approach is useful if you want to apply different prices for different businesses.
|
||||
|
||||
While you’re creating the customer groups, make sure to add the `metadata` of the customer group a key `is_b2b` that acts as a flag to indicate that this is a B2B customer group. This is useful for later steps.
|
||||
|
||||
Alternatively, you may choose to create custom entities or a different mechanism that indicates a customer is a B2B customer. This is covered in the [Create Custom Entities section](#create-custom-entities).
|
||||
|
||||
<DocCardList colSize={6} items={[
|
||||
{
|
||||
type: 'link',
|
||||
href: '/user-guide/customers/groups',
|
||||
label: 'Option 1: Use Medusa Admin',
|
||||
customProps: {
|
||||
icon: Icons['users-solid'],
|
||||
description: 'Create the customer group using the Medusa admin.',
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/modules/customers/admin/manage-customer-groups',
|
||||
label: 'Option 2: Using the REST APIs',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Create the customer group using the REST APIs.',
|
||||
}
|
||||
},
|
||||
]} />
|
||||
|
||||
---
|
||||
|
||||
## Add B2B Customers
|
||||
|
||||
After adding your B2B customer group, you can add B2B customers and assign them to the B2B customer group. Alternatively, if you want to allow B2B customers to register themselves, you can implement that logic within your storefront.
|
||||
|
||||
You can create a customer either through the Medusa admin or Admin REST APIs.
|
||||
|
||||
<DocCardList colSize={6} items={[
|
||||
{
|
||||
type: 'link',
|
||||
href: '/user-guide/customers/manage',
|
||||
label: 'Option 1: Use Medusa Admin',
|
||||
customProps: {
|
||||
icon: Icons['users-solid'],
|
||||
description: 'Create the customers using the Medusa admin.',
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/modules/customers/admin/manage-customers',
|
||||
label: 'Option 2: Using the REST APIs',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Create the customers using the REST APIs.',
|
||||
}
|
||||
},
|
||||
]} />
|
||||
|
||||
---
|
||||
|
||||
## Create B2B Price List
|
||||
|
||||
A price list allows you to set different prices on a set of products for different conditions. You can use this when building a B2B store to assign different prices for B2B customer groups.
|
||||
|
||||
You can use price lists to either set the same price for all B2B customers, or different prices for different B2B customers if you’ve created them in different customer groups.
|
||||
|
||||
You can create a price list either through the Medusa admin or Admin REST APIs. You can also import prices into your price list after creating it.
|
||||
|
||||
<DocCardList colSize={6} items={[
|
||||
{
|
||||
type: 'link',
|
||||
href: '/user-guide/price-lists/manage',
|
||||
label: 'Add Price List Using Medusa Admin',
|
||||
customProps: {
|
||||
icon: Icons['users-solid'],
|
||||
description: 'Create the price list using the Medusa admin.',
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/modules/price-lists/admin/manage-price-lists',
|
||||
label: 'Add Price List Using REST APIs',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Create the price list using the REST APIs.',
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/user-guide/price-lists/import',
|
||||
label: 'Import Prices Using Medusa Admin',
|
||||
customProps: {
|
||||
icon: Icons['users-solid'],
|
||||
description: 'Import the prices using the Medusa admin.',
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/modules/price-lists/admin/import-prices',
|
||||
label: 'Import Prices Using REST APIs',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Import the prices using the REST APIs.',
|
||||
}
|
||||
},
|
||||
]} />
|
||||
|
||||
---
|
||||
|
||||
## Create Custom Entities
|
||||
|
||||
Your use case may be more elaborate than what is shown in this recipe. For example, you may need to have a Company entity that allows a business to register its employees as users with different privileges and configurations.
|
||||
|
||||
Medusa can be customized to add custom entities, endpoints, services, and more. If you require some additional entities or a different logic in how you choose to implement a B2B store, you can customize Medusa as you see fit.
|
||||
|
||||
<DocCardList colSize={6} items={[
|
||||
{
|
||||
type: 'link',
|
||||
href: '/development/entities/create',
|
||||
label: 'Create Entity',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Learn how to create a custom entity.',
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/development/overview',
|
||||
label: 'Medusa Development',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Find all the development resources to customize Medusa.',
|
||||
}
|
||||
},
|
||||
]} />
|
||||
|
||||
---
|
||||
|
||||
## Create an Endpoint to Check Customers
|
||||
|
||||
On the clients communicating with your store, such as the storefront, you’ll need to check if the currently logged-in customer is a normal customer or a B2B customer.
|
||||
|
||||
The endpoint’s logic is different based on how you’ve implemented the B2B logic. For example, if you’ve used the `is_b2b` flag in the customer group, your endpoint can check whether that flag is enabled for the logged-in customer.
|
||||
|
||||
Medusa allows you to create custom endpoints exposed as REST APIs.
|
||||
|
||||
<DocCard item={{
|
||||
type: 'link',
|
||||
href: '/development/endpoints/create',
|
||||
label: 'Create an Endpoint',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Learn how to create an endpoint in Medusa.',
|
||||
}
|
||||
}} />
|
||||
|
||||
<details>
|
||||
<summary>
|
||||
Example Implementation
|
||||
</summary>
|
||||
|
||||
Here’s an example of an endpoint that allows you to check the customer’s group and whether it has the `is_b2b` flag enabled:
|
||||
|
||||
```ts title=src/api/index.ts
|
||||
import { CustomerService } from "@medusajs/medusa"
|
||||
import { Router } from "express"
|
||||
import { requireCustomerAuthentication } from "@medusajs/medusa"
|
||||
import cors from "cors"
|
||||
import { ConfigModule } from "@medusajs/medusa"
|
||||
import { getConfigFile } from "medusa-core-utils"
|
||||
|
||||
export default (rootDirectory) => {
|
||||
const router = Router()
|
||||
const { configModule } = getConfigFile<ConfigModule>(
|
||||
rootDirectory,
|
||||
"medusa-config"
|
||||
)
|
||||
|
||||
const corsOptions = {
|
||||
origin: configModule.projectConfig.store_cors.split(","),
|
||||
credentials: true,
|
||||
}
|
||||
|
||||
router.options("/store/customers/is-b2b", cors(corsOptions))
|
||||
router.get(
|
||||
"/store/customers/is-b2b",
|
||||
cors(corsOptions),
|
||||
requireCustomerAuthentication(),
|
||||
async (req, res) => {
|
||||
const customerService: CustomerService = req.scope.resolve(
|
||||
"customerService"
|
||||
)
|
||||
|
||||
const customer = await customerService
|
||||
.retrieve(req.user.customer_id, {
|
||||
relations: ["groups"],
|
||||
})
|
||||
|
||||
const is_b2b = customer.groups.some(
|
||||
(group) => group.metadata.is_b2b === "true"
|
||||
)
|
||||
|
||||
return res.json({
|
||||
is_b2b,
|
||||
})
|
||||
})
|
||||
|
||||
return router
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
## Customize Admin
|
||||
|
||||
Based on your use case, you may need to customize the Medusa admin to add new widgets or pages.
|
||||
|
||||
The Medusa admin plugin can be extended to add widgets, UI routes, and 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.',
|
||||
}
|
||||
},
|
||||
]} />
|
||||
|
||||
---
|
||||
|
||||
## Customize Storefront
|
||||
|
||||
On the storefront, you may want different login or registration interfaces for B2B and regular customers. You may also want to display products differently for each type of customer.
|
||||
|
||||
Medusa provides a Next.js starter that you can use and customize. You can also build your own storefront with any front-end technology. Medusa provides you with different client libraries and its REST APIs to use.
|
||||
|
||||
In the storefront, make sure to use the publishable API key you associated with your B2B sales channel to ensure only B2B products are retrieved.
|
||||
|
||||
<DocCardList colSize={6} items={[
|
||||
{
|
||||
type: 'link',
|
||||
href: '/starters/nextjs-medusa-starter',
|
||||
label: 'Option 1: Use Next.js Starter',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Learn how to install and use the Next.js starter template.',
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/storefront/roadmap',
|
||||
label: 'Options 2: Build Custom Storefront',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Learn how to build a custom storefront with your preferred technology.',
|
||||
}
|
||||
},
|
||||
]} />
|
||||
|
||||
<DocCard item={{
|
||||
type: 'link',
|
||||
href: '/development/publishable-api-keys/storefront/use-in-requests',
|
||||
label: 'Use Publishable API Keys',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Learn how to use the publishable API key in client requests.',
|
||||
}
|
||||
}} />
|
||||
|
||||
---
|
||||
|
||||
## Deploy B2B Store
|
||||
|
||||
Once you finish your development, you can deploy your B2B backend and storefront to your preferred hosting providers.
|
||||
|
||||
<DocCardList colSize={6} items={[
|
||||
{
|
||||
type: 'link',
|
||||
href: '/deployments/server',
|
||||
label: 'Deploy Medusa Backend',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Learn how to deploy your Medusa backend to your preferred hosting provider.',
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'link',
|
||||
href: '/deployments/storefront',
|
||||
label: 'Deploy Storefront',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Learn how to deploy your storefront to your preferred hosting provider.',
|
||||
}
|
||||
},
|
||||
]} />
|
||||
|
||||
---
|
||||
|
||||
## Additional Development
|
||||
|
||||
You can find other resources for your B2B development in the [Medusa Development section](../development/overview.mdx) of this documentation.
|
||||
@@ -63,17 +63,17 @@ Follow this guide if you want to implement subscription-based purhcases with Med
|
||||
|
||||
---
|
||||
|
||||
## Recipe: Role-Based Access Control
|
||||
## Recipe: Build B2B Store
|
||||
|
||||
Follow this guide if you want to implement role-based access control (RBAC) in Medusa.
|
||||
Follow this guide if you want to build a B2B/Wholesale store.
|
||||
|
||||
<DocCard item={{
|
||||
type: 'link',
|
||||
href: '/recipes/rbac',
|
||||
label: 'Build RBAC',
|
||||
href: '/recipes/b2b',
|
||||
label: 'Build B2B Store',
|
||||
customProps: {
|
||||
icon: Icons['credit-card-solid'],
|
||||
description: 'Learn how you can implement role-based access control in Medusa.'
|
||||
description: 'Learn how you can build a B2B store in Medusa.'
|
||||
}
|
||||
}} />
|
||||
|
||||
|
||||
@@ -42,102 +42,102 @@ To associate these entities with the `Store` entity, you need to extend and cust
|
||||
}} />
|
||||
|
||||
<details>
|
||||
<summary>Example: Associate User with Store</summary>
|
||||
<summary>Example: Associate User with Store</summary>
|
||||
|
||||
For example, to associate the `User` entity with the `Store` entity, create the file `src/models/user.ts` with the following content:
|
||||
For example, to associate the `User` entity with the `Store` entity, 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 {
|
||||
User as MedusaUser,
|
||||
} from "@medusajs/medusa"
|
||||
import { Store } from "./store"
|
||||
|
||||
@Entity()
|
||||
export class User extends MedusaUser {
|
||||
@Index("UserStoreId")
|
||||
@Column({ nullable: true })
|
||||
store_id?: string
|
||||
|
||||
@ManyToOne(() => Store, (store) => store.members)
|
||||
@JoinColumn({ name: "store_id", referencedColumnName: "id" })
|
||||
store?: Store
|
||||
}
|
||||
```
|
||||
```ts title=src/models/user.ts
|
||||
import {
|
||||
Column,
|
||||
Entity,
|
||||
Index,
|
||||
JoinColumn,
|
||||
ManyToOne,
|
||||
} from "typeorm"
|
||||
import {
|
||||
User as MedusaUser,
|
||||
} from "@medusajs/medusa"
|
||||
import { Store } from "./store"
|
||||
|
||||
Then, you need to extend the `UserRepository` to point to your extended entity. To do that, create the file `src/repositories/user.ts` with the following content:
|
||||
@Entity()
|
||||
export class User extends MedusaUser {
|
||||
@Index("UserStoreId")
|
||||
@Column({ nullable: true })
|
||||
store_id?: string
|
||||
|
||||
```ts title=src/repositories/user.ts
|
||||
import { User } from "../models/user"
|
||||
import {
|
||||
dataSource,
|
||||
} from "@medusajs/medusa/dist/loaders/database"
|
||||
import {
|
||||
UserRepository as MedusaUserRepository,
|
||||
} from "@medusajs/medusa/dist/repositories/user"
|
||||
@ManyToOne(() => Store, (store) => store.members)
|
||||
@JoinColumn({ name: "store_id", referencedColumnName: "id" })
|
||||
store?: Store
|
||||
}
|
||||
```
|
||||
|
||||
export const UserRepository = dataSource
|
||||
.getRepository(User)
|
||||
.extend({
|
||||
...Object.assign(
|
||||
MedusaUserRepository,
|
||||
{ target: User }
|
||||
),
|
||||
})
|
||||
Then, you need to extend the `UserRepository` to point to your extended entity. To do that, create the file `src/repositories/user.ts` with the following content:
|
||||
|
||||
export default UserRepository
|
||||
```
|
||||
```ts title=src/repositories/user.ts
|
||||
import { User } from "../models/user"
|
||||
import {
|
||||
dataSource,
|
||||
} from "@medusajs/medusa/dist/loaders/database"
|
||||
import {
|
||||
UserRepository as MedusaUserRepository,
|
||||
} from "@medusajs/medusa/dist/repositories/user"
|
||||
|
||||
Next, you need to create a migration that reflects the changes on the `User` entity in your database. To do that, run the following command to create a migration file:
|
||||
export const UserRepository = dataSource
|
||||
.getRepository(User)
|
||||
.extend({
|
||||
...Object.assign(
|
||||
MedusaUserRepository,
|
||||
{ target: User }
|
||||
),
|
||||
})
|
||||
|
||||
```bash
|
||||
npx typeorm migration:create src/migrations/add-user-store-id
|
||||
```
|
||||
export default UserRepository
|
||||
```
|
||||
|
||||
This creates a file in the `src/migrations` directory of the format `<TIMESTAMP>_add-user-store-id.ts`. Replace the `up` and `down` methods in that file with the methods here:
|
||||
Next, you need to create a migration that reflects the changes on the `User` entity in your database. To do that, run the following command to create a migration file:
|
||||
|
||||
```ts title=src/migrations/<TIMESTAMP>_add-user-store-id.ts
|
||||
// ...
|
||||
```bash
|
||||
npx typeorm migration:create src/migrations/add-user-store-id
|
||||
```
|
||||
|
||||
export class AddUserStoreId1681287255173
|
||||
implements MigrationInterface {
|
||||
// ...
|
||||
This creates a file in the `src/migrations` directory of the format `<TIMESTAMP>_add-user-store-id.ts`. Replace the `up` and `down` methods in that file with the methods here:
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "user" ADD "store_id" character varying`
|
||||
)
|
||||
await queryRunner.query(
|
||||
`CREATE INDEX "UserStoreId" ON "user" ("store_id")`
|
||||
)
|
||||
}
|
||||
```ts title=src/migrations/<TIMESTAMP>_add-user-store-id.ts
|
||||
// ...
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`DROP INDEX "public"."UserStoreId"`
|
||||
)
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "user" DROP COLUMN "store_id"`
|
||||
)
|
||||
}
|
||||
export class AddUserStoreId1681287255173
|
||||
implements MigrationInterface {
|
||||
// ...
|
||||
|
||||
}
|
||||
```
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "user" ADD "store_id" character varying`
|
||||
)
|
||||
await queryRunner.query(
|
||||
`CREATE INDEX "UserStoreId" ON "user" ("store_id")`
|
||||
)
|
||||
}
|
||||
|
||||
Finally, to reflect these changes and start using them, `build` your changes and run migrations with the following commands:
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`DROP INDEX "public"."UserStoreId"`
|
||||
)
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE "user" DROP COLUMN "store_id"`
|
||||
)
|
||||
}
|
||||
|
||||
```bash npm2yarn
|
||||
npm run build
|
||||
npx medusa migrations run
|
||||
```
|
||||
}
|
||||
```
|
||||
|
||||
You can extend other entities in a similar manner to associate them with a store.
|
||||
Finally, to reflect these changes and start using them, `build` your changes and run migrations with the following commands:
|
||||
|
||||
```bash npm2yarn
|
||||
npm run build
|
||||
npx medusa migrations run
|
||||
```
|
||||
|
||||
You can extend other entities in a similar manner to associate them with a store.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -180,73 +180,73 @@ You can also extend services if you need to customize a functionality implemente
|
||||
}} />
|
||||
|
||||
<details>
|
||||
<summary>Example: Extend User Service</summary>
|
||||
<summary>Example: Extend User Service</summary>
|
||||
|
||||
You can extend the user service to change how the `create` method is implemented.
|
||||
You can extend the user service to change how the `create` method is implemented.
|
||||
|
||||
To extend the user service, create the file `src/services/user.ts` with the following content:
|
||||
To extend the user service, create the file `src/services/user.ts` with the following content:
|
||||
|
||||
<!-- eslint-disable prefer-rest-params -->
|
||||
|
||||
```ts
|
||||
import { Lifetime } from "awilix"
|
||||
import {
|
||||
UserService as MedusaUserService,
|
||||
} from "@medusajs/medusa"
|
||||
import { User } from "../models/user"
|
||||
import {
|
||||
CreateUserInput as MedusaCreateUserInput,
|
||||
} from "@medusajs/medusa/dist/types/user"
|
||||
import StoreRepository from "../repositories/store"
|
||||
```ts
|
||||
import { Lifetime } from "awilix"
|
||||
import {
|
||||
UserService as MedusaUserService,
|
||||
} from "@medusajs/medusa"
|
||||
import { User } from "../models/user"
|
||||
import {
|
||||
CreateUserInput as MedusaCreateUserInput,
|
||||
} from "@medusajs/medusa/dist/types/user"
|
||||
import StoreRepository from "../repositories/store"
|
||||
|
||||
type CreateUserInput = {
|
||||
store_id?: string
|
||||
} & MedusaCreateUserInput
|
||||
type CreateUserInput = {
|
||||
store_id?: string
|
||||
} & MedusaCreateUserInput
|
||||
|
||||
class UserService extends MedusaUserService {
|
||||
static LIFE_TIME = Lifetime.SCOPED
|
||||
protected readonly loggedInUser_: User | null
|
||||
protected readonly storeRepository_: typeof StoreRepository
|
||||
|
||||
constructor(container, options) {
|
||||
super(...arguments)
|
||||
this.storeRepository_ = container.storeRepository
|
||||
class UserService extends MedusaUserService {
|
||||
static LIFE_TIME = Lifetime.SCOPED
|
||||
protected readonly loggedInUser_: User | null
|
||||
protected readonly storeRepository_: typeof StoreRepository
|
||||
|
||||
try {
|
||||
this.loggedInUser_ = container.loggedInUser
|
||||
} catch (e) {
|
||||
// avoid errors when backend first runs
|
||||
}
|
||||
}
|
||||
constructor(container, options) {
|
||||
super(...arguments)
|
||||
this.storeRepository_ = container.storeRepository
|
||||
|
||||
async create(
|
||||
user: CreateUserInput,
|
||||
password: string
|
||||
): Promise<User> {
|
||||
if (!user.store_id) {
|
||||
const storeRepo = this.manager_.withRepository(
|
||||
this.storeRepository_
|
||||
)
|
||||
let newStore = storeRepo.create()
|
||||
newStore = await storeRepo.save(newStore)
|
||||
user.store_id = newStore.id
|
||||
}
|
||||
|
||||
return await super.create(user, password)
|
||||
try {
|
||||
this.loggedInUser_ = container.loggedInUser
|
||||
} catch (e) {
|
||||
// avoid errors when backend first runs
|
||||
}
|
||||
}
|
||||
|
||||
export default UserService
|
||||
```
|
||||
async create(
|
||||
user: CreateUserInput,
|
||||
password: string
|
||||
): Promise<User> {
|
||||
if (!user.store_id) {
|
||||
const storeRepo = this.manager_.withRepository(
|
||||
this.storeRepository_
|
||||
)
|
||||
let newStore = storeRepo.create()
|
||||
newStore = await storeRepo.save(newStore)
|
||||
user.store_id = newStore.id
|
||||
}
|
||||
|
||||
In the `create` method of this extended service, you create a new store if the user being created doesn't have a store associated with it.
|
||||
return await super.create(user, password)
|
||||
}
|
||||
}
|
||||
|
||||
You can then test out your customization by running the `build` command and starting the backend:
|
||||
export default UserService
|
||||
```
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
npx medusa develop
|
||||
```
|
||||
In the `create` method of this extended service, you create a new store if the user being created doesn't have a store associated with it.
|
||||
|
||||
You can then test out your customization by running the `build` command and starting the backend:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
npx medusa develop
|
||||
```
|
||||
</details>
|
||||
|
||||
---
|
||||
@@ -268,32 +268,32 @@ To listen to events, you need to create Subscribers that subscribe a handler met
|
||||
}} />
|
||||
|
||||
<details>
|
||||
<summary>Example: Listen to Order Created Event</summary>
|
||||
<summary>Example: Listen to Order Created Event</summary>
|
||||
|
||||
To listen to the `order.placed` event, create the file `src/subscribers/orderNotifier.ts` with the following content:
|
||||
To listen to the `order.placed` event, create the file `src/subscribers/orderNotifier.ts` with the following content:
|
||||
|
||||
```ts
|
||||
class OrderNotifierSubscriber {
|
||||
constructor({ eventBusService }) {
|
||||
eventBusService.subscribe("order.placed", this.handleOrder)
|
||||
}
|
||||
|
||||
handleOrder = async (data) => {
|
||||
// TODO perform functionality
|
||||
}
|
||||
```ts
|
||||
class OrderNotifierSubscriber {
|
||||
constructor({ eventBusService }) {
|
||||
eventBusService.subscribe("order.placed", this.handleOrder)
|
||||
}
|
||||
|
||||
export default OrderNotifierSubscriber
|
||||
```
|
||||
handleOrder = async (data) => {
|
||||
// TODO perform functionality
|
||||
}
|
||||
}
|
||||
|
||||
This subscribes the `handleOrder` method to be executed whenever the `order.placed` event is emitted.
|
||||
export default OrderNotifierSubscriber
|
||||
```
|
||||
|
||||
You can then test out your subscriber by running the `build` command and starting the backend:
|
||||
This subscribes the `handleOrder` method to be executed whenever the `order.placed` event is emitted.
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
npx medusa develop
|
||||
```
|
||||
You can then test out your subscriber by running the `build` command and starting the backend:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
npx medusa develop
|
||||
```
|
||||
</details>
|
||||
|
||||
---
|
||||
@@ -402,8 +402,8 @@ If you want to implement this functionality, you can follow the RBAC recipe.
|
||||
|
||||
<DocCard item={{
|
||||
type: 'link',
|
||||
href: '/recipes/rbac',
|
||||
label: 'RBAC Recipe',
|
||||
href: '/modules/users/backend/rbac',
|
||||
label: 'Implement Role-Based Access Control',
|
||||
customProps: {
|
||||
icon: Icons['academic-cap-solid'],
|
||||
description: 'Learn how to implement role-based access control (RBAC) in Medusa.',
|
||||
|
||||
@@ -1,805 +0,0 @@
|
||||
---
|
||||
addHowToData: true
|
||||
---
|
||||
|
||||
import DocCardList from '@theme/DocCardList';
|
||||
import DocCard from '@theme/DocCard';
|
||||
import Icons from '@theme/Icon';
|
||||
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
|
||||
@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. 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
|
||||
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 you’re 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, 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"
|
||||
|
||||
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 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"
|
||||
|
||||
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, 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 {
|
||||
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 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 {
|
||||
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 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.
|
||||
Reference in New Issue
Block a user