docs: docs for next release (#14110)
This commit is contained in:
1 parent
e4513fab88
commit
223ccb4add
24 files changed
+1196
-27
No files matched your search
@@ -1,3 +1,5 @@
|
||||
import { Table } from "docs-ui"
|
||||
|
||||
export const metadata = {
|
||||
title: `${pageNumber} Environment Variables in Admin Customizations`,
|
||||
}
|
||||
@@ -88,6 +90,70 @@ Learn more about other Vite environment variables in the [Vite documentation](ht
|
||||
|
||||
---
|
||||
|
||||
## Predefined Environment Variables
|
||||
|
||||
You can further customize the Medusa Admin behavior using the following predefined environment variables. You can set the environment variables in your `.env` file or in your deployment platform.
|
||||
|
||||
<Note>
|
||||
|
||||
The following pre-defined environment variables are available starting [Medusa v2.12.0](https://github.com/medusajs/medusa/releases/tag/v2.12.0).
|
||||
|
||||
</Note>
|
||||
|
||||
<Table>
|
||||
<Table.Header>
|
||||
<Table.Row>
|
||||
<Table.HeaderCell>
|
||||
Environment Variable
|
||||
</Table.HeaderCell>
|
||||
<Table.HeaderCell>
|
||||
Description
|
||||
</Table.HeaderCell>
|
||||
<Table.HeaderCell>
|
||||
Default
|
||||
</Table.HeaderCell>
|
||||
</Table.Row>
|
||||
</Table.Header>
|
||||
<Table.Body>
|
||||
<Table.Row>
|
||||
<Table.Cell>
|
||||
|
||||
`ADMIN_AUTH_TYPE`
|
||||
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
|
||||
A string indicating the authentication method that the JS SDK instance uses in the Medusa Admin. Possible values are `session` and `jwt`. Learn more in the [JS SDK Authentication guide](!resources!/js-sdk/auth/overview).
|
||||
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
|
||||
`session`
|
||||
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
<Table.Row>
|
||||
<Table.Cell>
|
||||
|
||||
`ADMIN_JWT_TOKEN_STORAGE_KEY`
|
||||
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
|
||||
A string indicating the key used to store the authentication JWT token in the browser's local storage. Only applicable if `ADMIN_AUTH_TYPE` is set to `jwt`.
|
||||
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
|
||||
`medusa_auth_token`
|
||||
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
</Table.Body>
|
||||
</Table>
|
||||
|
||||
---
|
||||
|
||||
## Environment Variables in Production
|
||||
|
||||
When you build the Medusa application, including the Medusa Admin, with the `build` command, the environment variables are inlined into the build. This means that you can't change the environment variables without rebuilding the application.
|
||||
|
||||
@@ -37,7 +37,7 @@ The next chapters will cover these two topics in detail.
|
||||
|
||||
### What You Can't Customize in the Medusa Admin
|
||||
|
||||
You can't customize the admin dashboard's layout, design, or the content of the existing pages (aside from injecting widgets). You also can't customize the login page, the authentication flow, or change the Medusa logo used in the admin dashboard.
|
||||
You can't customize the admin dashboard's layout, design, or the content of the existing pages (aside from injecting widgets). You also can't change the Medusa logo used in the admin dashboard.
|
||||
|
||||
If your use case requires heavy customization of the admin dashboard, you can build a custom admin dashboard using Medusa's [Admin API routes](!api!/admin).
|
||||
|
||||
@@ -51,6 +51,8 @@ Refer to the [Medusa UI documentation](https://docs.medusajs.com/ui) to learn ho
|
||||
|
||||
---
|
||||
|
||||
## Admin Components List
|
||||
## Admin How-to Guides
|
||||
|
||||
To build admin customizations that match the Medusa Admin's designs and layouts, refer to [this guide](!resources!/admin-components) to find common components.
|
||||
The [Admin How-to Guides](!resources!/how-to-tutorials#admin) provides guides that walk you through common admin customizations, such as [building common admin components](!resources!/admin-components), or [adding third-party authentication to the admin](!resources!/how-to-tutorials/how-to/admin/auth).
|
||||
|
||||
Refer to these guides for practical examples of customizing the Medusa Admin dashboard.
|
||||
@@ -113,7 +113,7 @@ Learn more in the [Admin Environment Variables](../admin/environment-variables/p
|
||||
|
||||
## Predefined Medusa Environment Variables
|
||||
|
||||
The Medusa application uses the following predefined environment variables that you can set:
|
||||
You can further customize the Medusa application behavior using the following predefined environment variables. You can set the environment variables in your `.env` file or in your deployment platform.
|
||||
|
||||
<Note title="Tip">
|
||||
|
||||
@@ -306,5 +306,39 @@ You should opt for setting configurations in `medusa-config.ts` where possible.
|
||||
\-
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
<Table.Row>
|
||||
<Table.Cell>
|
||||
|
||||
`ADMIN_AUTH_TYPE` ([v2.12.0+](https://github.com/medusajs/medusa/releases/tag/v2.12.0))
|
||||
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
|
||||
A string indicating the authentication method that the JS SDK instance uses in the Medusa Admin. Possible values are `session` and `jwt`. Learn more in the [JS SDK Authentication guide](!resources!/js-sdk/auth/overview).
|
||||
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
|
||||
`session`
|
||||
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
<Table.Row>
|
||||
<Table.Cell>
|
||||
|
||||
`ADMIN_JWT_TOKEN_STORAGE_KEY` ([v2.12.0+](https://github.com/medusajs/medusa/releases/tag/v2.12.0))
|
||||
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
|
||||
A string indicating the key used to store the authentication JWT token in the browser's local storage. Only applicable if `ADMIN_AUTH_TYPE` is set to `jwt`.
|
||||
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
|
||||
`medusa_auth_token`
|
||||
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
</Table.Body>
|
||||
</Table>
|
||||
@@ -29,7 +29,7 @@ export const generatedEditDates = {
|
||||
"app/learn/fundamentals/events-and-subscribers/emit-event/page.mdx": "2025-11-26T13:00:24.625Z",
|
||||
"app/learn/fundamentals/workflows/conditions/page.mdx": "2025-09-04T15:57:00.934Z",
|
||||
"app/learn/fundamentals/modules/module-link-directions/page.mdx": "2024-07-24T09:16:01+02:00",
|
||||
"app/learn/fundamentals/admin/page.mdx": "2025-07-25T12:46:15.466Z",
|
||||
"app/learn/fundamentals/admin/page.mdx": "2025-11-26T10:47:12.412Z",
|
||||
"app/learn/fundamentals/workflows/long-running-workflow/page.mdx": "2025-08-01T07:16:21.736Z",
|
||||
"app/learn/fundamentals/workflows/constructor-constraints/page.mdx": "2025-08-01T13:11:18.823Z",
|
||||
"app/learn/fundamentals/data-models/write-migration/page.mdx": "2025-10-28T16:01:36.609Z",
|
||||
@@ -92,7 +92,7 @@ export const generatedEditDates = {
|
||||
"app/learn/introduction/architecture/page.mdx": "2025-07-18T15:52:35.513Z",
|
||||
"app/learn/fundamentals/data-models/infer-type/page.mdx": "2025-03-18T07:41:01.936Z",
|
||||
"app/learn/fundamentals/custom-cli-scripts/seed-data/page.mdx": "2025-09-15T16:02:51.362Z",
|
||||
"app/learn/fundamentals/environment-variables/page.mdx": "2025-05-26T15:06:07.800Z",
|
||||
"app/learn/fundamentals/environment-variables/page.mdx": "2025-11-26T11:05:38.863Z",
|
||||
"app/learn/build/page.mdx": "2025-10-27T09:30:26.957Z",
|
||||
"app/learn/deployment/general/page.mdx": "2025-10-21T07:39:08.998Z",
|
||||
"app/learn/fundamentals/workflows/multiple-step-usage/page.mdx": "2025-08-01T14:59:59.501Z",
|
||||
@@ -105,7 +105,7 @@ export const generatedEditDates = {
|
||||
"app/learn/customization/reuse-customizations/page.mdx": "2025-09-04T15:45:52.047Z",
|
||||
"app/learn/update/page.mdx": "2025-01-27T08:45:19.030Z",
|
||||
"app/learn/fundamentals/module-links/query-context/page.mdx": "2025-09-15T16:09:58.104Z",
|
||||
"app/learn/fundamentals/admin/environment-variables/page.mdx": "2025-08-01T13:16:25.172Z",
|
||||
"app/learn/fundamentals/admin/environment-variables/page.mdx": "2025-11-26T08:24:17.689Z",
|
||||
"app/learn/fundamentals/api-routes/parse-body/page.mdx": "2025-08-20T09:58:37.704Z",
|
||||
"app/learn/fundamentals/admin/routing/page.mdx": "2025-07-25T07:35:18.038Z",
|
||||
"app/learn/resources/contribution-guidelines/admin-translations/page.mdx": "2025-02-11T16:57:46.726Z",
|
||||
|
||||
@@ -7451,6 +7451,19 @@ Learn more about other Vite environment variables in the [Vite documentation](ht
|
||||
|
||||
***
|
||||
|
||||
## Predefined Environment Variables
|
||||
|
||||
You can further customize the Medusa Admin behavior using the following predefined environment variables. You can set the environment variables in your `.env` file or in your deployment platform.
|
||||
|
||||
The following pre-defined environment variables are available starting [Medusa v2.12.0](https://github.com/medusajs/medusa/releases/tag/v2.12.0).
|
||||
|
||||
|Environment Variable|Description|Default|
|
||||
|---|---|---|
|
||||
|\`ADMIN\_AUTH\_TYPE\`|A string indicating the authentication method that the JS SDK instance uses in the Medusa Admin. Possible values are |\`session\`|
|
||||
|\`ADMIN\_JWT\_TOKEN\_STORAGE\_KEY\`|A string indicating the key used to store the authentication JWT token in the browser's local storage. Only applicable if |\`medusa\_auth\_token\`|
|
||||
|
||||
***
|
||||
|
||||
## Environment Variables in Production
|
||||
|
||||
When you build the Medusa application, including the Medusa Admin, with the `build` command, the environment variables are inlined into the build. This means that you can't change the environment variables without rebuilding the application.
|
||||
@@ -7573,7 +7586,7 @@ The next chapters will cover these two topics in detail.
|
||||
|
||||
### What You Can't Customize in the Medusa Admin
|
||||
|
||||
You can't customize the admin dashboard's layout, design, or the content of the existing pages (aside from injecting widgets). You also can't customize the login page, the authentication flow, or change the Medusa logo used in the admin dashboard.
|
||||
You can't customize the admin dashboard's layout, design, or the content of the existing pages (aside from injecting widgets). You also can't change the Medusa logo used in the admin dashboard.
|
||||
|
||||
If your use case requires heavy customization of the admin dashboard, you can build a custom admin dashboard using Medusa's [Admin API routes](https://docs.medusajs.com/api/admin).
|
||||
|
||||
@@ -7587,9 +7600,11 @@ Refer to the [Medusa UI documentation](https://docs.medusajs.com/ui/index.html.m
|
||||
|
||||
***
|
||||
|
||||
## Admin Components List
|
||||
## Admin How-to Guides
|
||||
|
||||
To build admin customizations that match the Medusa Admin's designs and layouts, refer to [this guide](https://docs.medusajs.com/resources/admin-components/index.html.md) to find common components.
|
||||
The [Admin How-to Guides](https://docs.medusajs.com/resources/how-to-tutorials#admin/index.html.md) provides guides that walk you through common admin customizations, such as [building common admin components](https://docs.medusajs.com/resources/admin-components/index.html.md), or [adding third-party authentication to the admin](https://docs.medusajs.com/resources/how-to-tutorials/how-to/admin/auth/index.html.md).
|
||||
|
||||
Refer to these guides for practical examples of customizing the Medusa Admin dashboard.
|
||||
|
||||
|
||||
# Admin Routing Customizations
|
||||
@@ -13039,7 +13054,7 @@ Learn more in the [Admin Environment Variables](https://docs.medusajs.com/learn/
|
||||
|
||||
## Predefined Medusa Environment Variables
|
||||
|
||||
The Medusa application uses the following predefined environment variables that you can set:
|
||||
You can further customize the Medusa application behavior using the following predefined environment variables. You can set the environment variables in your `.env` file or in your deployment platform.
|
||||
|
||||
You should opt for setting configurations in `medusa-config.ts` where possible. For a full list of Medusa configurations, refer to the [Medusa Configurations chapter](https://docs.medusajs.com/learn/configurations/medusa-config/index.html.md).
|
||||
|
||||
@@ -13061,6 +13076,8 @@ You should opt for setting configurations in `medusa-config.ts` where possible.
|
||||
|\`LOG\_LEVEL\`|The allowed levels to log. Learn more in the |\`silly\`|
|
||||
|\`LOG\_FILE\`|The file to save logs in. By default, logs aren't saved in any file. Learn more in the |-|
|
||||
|\`MEDUSA\_DISABLE\_TELEMETRY\`|Whether to disable analytics data collection. Learn more in the |-|
|
||||
|\`ADMIN\_AUTH\_TYPE\`|A string indicating the authentication method that the JS SDK instance uses in the Medusa Admin. Possible values are |\`session\`|
|
||||
|\`ADMIN\_JWT\_TOKEN\_STORAGE\_KEY\`|A string indicating the key used to store the authentication JWT token in the browser's local storage. Only applicable if |\`medusa\_auth\_token\`|
|
||||
|
||||
|
||||
# Event Data Payload
|
||||
@@ -35408,6 +35425,7 @@ STRIPE_API_KEY=<YOUR_STRIPE_API_KEY>
|
||||
|\`capture\`|Whether to automatically capture payment after authorization.|No|\`false\`|
|
||||
|\`automatic\_payment\_methods\`|A boolean value indicating whether to enable Stripe's automatic payment methods. This is useful if you integrate services like Apple pay or Google pay.|No|\`false\`|
|
||||
|\`payment\_description\`|A string used as the default description of a payment if none is available in cart.context.payment\_description.|No|-|
|
||||
|\`oxxoExpiresDays\`|The number of days before an OXXO payment expires. Only applicable if you plan to use OXXO as a payment method.|No|\`3\`|
|
||||
|
||||
***
|
||||
|
||||
@@ -35439,6 +35457,7 @@ Assuming you set the ID of the Stripe Module Provider to `stripe` in `medusa-con
|
||||
|iDEAL Payments|\`pp\_stripe-ideal\_stripe\`|
|
||||
|Przelewy24 Payments|\`pp\_stripe-przelewy24\_stripe\`|
|
||||
|PromptPay Payments|\`pp\_stripe-promptpay\_stripe\`|
|
||||
|OXXO Payments (Available since |\`pp\_stripe-oxxo\_stripe\`|
|
||||
|
||||
***
|
||||
|
||||
@@ -35464,6 +35483,7 @@ The Stripe Module Provider supports the following payment types, and the webhook
|
||||
|iDEAL Payments|\`\{server\_url}/hooks/payment/stripe-ideal\_stripe\`|
|
||||
|Przelewy24 Payments|\`\{server\_url}/hooks/payment/stripe-przelewy24\_stripe\`|
|
||||
|PromptPay Payments|\`\{server\_url}/hooks/payment/stripe-promptpay\_stripe\`|
|
||||
|OXXO Payments (Available since |\`\{server\_url}/hooks/payment/stripe-oxxo\_stripe\`|
|
||||
|
||||
### Webhook Events
|
||||
|
||||
@@ -59069,6 +59089,380 @@ const user = await userModuleService.createUsers({
|
||||
```
|
||||
|
||||
|
||||
# How to Add Custom Authentication in Medusa Admin
|
||||
|
||||
In this guide, you'll learn how to add custom authentication provider to the Medusa Admin.
|
||||
|
||||
Authenticating into the Medusa Admin with third-party providers is supported from [Medusa v2.12.0](https://github.com/medusajs/medusa/releases/tag/v2.12.0).
|
||||
|
||||
## Overview
|
||||
|
||||
By default, the Medusa Admin allows users to authenticate using their email and password. Medusa uses the [Emailpass Authentication Provider](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/auth-providers/emailpass/index.html.md) to handle this authentication method.
|
||||
|
||||
You can also integrate a custom or third-party authentication provider to allow users registered with that provider to log in to the Medusa Admin. This delegates the authentication process to the third-party provider, which is useful if your organization uses a centralized authentication system.
|
||||
|
||||
Ensure the third-party authentication provider allows **only** your organization's users to log in to the Medusa Admin. For example, integrating a social login provider like Google or Facebook without restrictions will allow any user with an account on those platforms to access your Medusa Admin.
|
||||
|
||||
### Summary of Custom Medusa Admin Authentication
|
||||
|
||||
To authenticate admin users through a third-party provider, you need to:
|
||||
|
||||
1. Create a [custom Authentication Module Provider](https://docs.medusajs.com/references/auth/provider/index.html.md) that integrates the third-party provider. For example, you can create a provider that integrates with Okta.
|
||||
2. Change the authentication type in the Medusa Admin dashboard to use JWT authentication.
|
||||
3. Add an API route with a workflow that handles creating the admin user after they authenticate through the third-party provider.
|
||||
4. Add a widget on the login page that provides the option to log in through the third-party provider.
|
||||
|
||||

|
||||
|
||||
***
|
||||
|
||||
## Step 1: Create a Custom Authentication Module Provider
|
||||
|
||||
The first step is to create a custom Authentication Module Provider that integrates with the third-party authentication provider you want to use.
|
||||
|
||||
For example, if your organization uses Okta for authentication, you can create an Okta Authentication Provider that uses the Okta SDK to authenticate users.
|
||||
|
||||
Refer to the [Create Custom Authentication Module Provider](https://docs.medusajs.com/references/auth/provider/index.html.md) guide to learn how to create a custom Authentication Module Provider.
|
||||
|
||||
### Enable Custom Authentication Provider for Admin Users
|
||||
|
||||
By default, registered Authentication Module Providers can be used for all [actor types](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/auth-identity-and-actor-types/index.html.md). This means both admin users and customers can authenticate through the provider.
|
||||
|
||||
It's recommended to restrict the custom authentication provider to admin users only. To do this, set the `http.authMethodsPerActor` configuration in `medusa-config.ts` to enable the custom authentication provider only for the `user` actor type:
|
||||
|
||||
```ts title="medusa-config.ts"
|
||||
module.exports = defineConfig({
|
||||
projectConfig: {
|
||||
http: {
|
||||
// ...
|
||||
authMethodsPerActor: {
|
||||
user: ["emailpass", "custom"],
|
||||
customer: ["emailpass"],
|
||||
},
|
||||
},
|
||||
// ...
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
Where `emailpass` is the identifier of the Emailpass Authentication Provider, and `custom` is the identifier of your custom Authentication Module Provider.
|
||||
|
||||
Refer to the [Authentication Module Providers](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/auth-providers#configure-allowed-auth-providers-of-actor-types/index.html.md) guide to learn more about configuring allowed authentication providers for actor types.
|
||||
|
||||
***
|
||||
|
||||
## Step 2: Change Authentication Type in Medusa Admin
|
||||
|
||||
Next, you need to change the authentication type in the Medusa Admin dashboard to use JWT authentication.
|
||||
|
||||
To do this, set the `ADMIN_AUTH_TYPE` environment variable to `jwt` in your Medusa application's environment variables:
|
||||
|
||||
```bash
|
||||
ADMIN_AUTH_TYPE=jwt
|
||||
```
|
||||
|
||||
Make sure to also create a JS SDK instance in your Medusa Admin customizations with the `auth.type` option set to `jwt`. For example, create the file `src/lib/sdk.ts` with the following content:
|
||||
|
||||
```ts title="src/lib/sdk.ts"
|
||||
import Medusa from "@medusajs/js-sdk"
|
||||
|
||||
export const sdk = new Medusa({
|
||||
baseUrl: import.meta.env.VITE_BACKEND_URL || "/",
|
||||
debug: import.meta.env.DEV,
|
||||
auth: {
|
||||
type: "jwt",
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
Refer to the [JS SDK Authentication guide](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/js-sdk/auth/overview/index.html.md) to learn more about configuring authentication in the Medusa JS SDK.
|
||||
|
||||
***
|
||||
|
||||
## Step 3: Create User API Route
|
||||
|
||||
Next, you need to create an [API route](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/index.html.md) with a [workflow](https://docs.medusajs.com/docs/learn/fundamentals/workflows/index.html.md) that handles creating the admin user after they authenticate through the third-party provider.
|
||||
|
||||
Note that this API route will allow any user with a valid authentication token to create an admin user. Therefore, ensure that only authorized users can obtain an authentication token from the third-party provider.
|
||||
|
||||
### Create User Workflow
|
||||
|
||||
First, you need to create the workflow that creates a user and associates it with the authenticated identity.
|
||||
|
||||
Create the file `src/workflows/create-user.ts` with the following content:
|
||||
|
||||
```ts title="src/workflows/create-user.ts"
|
||||
import { createWorkflow, transform, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
|
||||
import { createUsersWorkflow, setAuthAppMetadataStep } from "@medusajs/medusa/core-flows"
|
||||
|
||||
type WorkflowInput = {
|
||||
email: string
|
||||
auth_identity_id: string
|
||||
}
|
||||
|
||||
export const createUserWorkflow = createWorkflow(
|
||||
"create-user",
|
||||
(input: WorkflowInput) => {
|
||||
const users = createUsersWorkflow.runAsStep({
|
||||
input: {
|
||||
users: [
|
||||
{
|
||||
email: input.email,
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
const authUserInput = transform({ input, users }, ({ input, users }) => {
|
||||
const createdUser = users[0]
|
||||
|
||||
return {
|
||||
authIdentityId: input.auth_identity_id,
|
||||
actorType: "user",
|
||||
value: createdUser.id,
|
||||
}
|
||||
})
|
||||
|
||||
setAuthAppMetadataStep(authUserInput)
|
||||
|
||||
return new WorkflowResponse({
|
||||
user: users[0],
|
||||
})
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
The workflow receives an object with the following properties:
|
||||
|
||||
- `email`: The email of the user being authenticated. You can modify this based on your third-party provider's identification method.
|
||||
- `auth_identity_id`: The ID of the auth identity created by the custom Authentication Module Provider. Refer to the [Auth Identities](https://docs.medusajs.com/Users/shahednasser/medusa/www/apps/resources/app/commerce-modules/auth/auth-identity-and-actor-types/index.html.md) guide to learn more.
|
||||
|
||||
In the workflow, you:
|
||||
|
||||
1. Create a user with the provided email using `createUsersWorkflow`.
|
||||
2. Associate the created user with the authenticated identity using `setAuthAppMetadataStep`.
|
||||
|
||||
### Create User API Route
|
||||
|
||||
Next, you need to create the API route that calls the workflow to create the user.
|
||||
|
||||
Create the file `src/api/custom-auth/admin/users/route.ts` with the following content:
|
||||
|
||||
```ts title="src/api/custom-auth/admin/users/route.ts"
|
||||
import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework"
|
||||
import { z } from "zod"
|
||||
import { createUserWorkflow } from "../../../../workflows/create-user"
|
||||
|
||||
export const CreateUserSchema = z.object({
|
||||
email: z.string(),
|
||||
})
|
||||
|
||||
type CreateUserBody = z.infer<typeof CreateUserSchema>
|
||||
|
||||
export const POST = async (req: AuthenticatedMedusaRequest<CreateUserBody>, res: MedusaResponse) => {
|
||||
const user = await createUserWorkflow(req.scope)
|
||||
.run({
|
||||
input: {
|
||||
email: req.body.email,
|
||||
auth_identity_id: req.auth_context!.auth_identity_id!,
|
||||
},
|
||||
})
|
||||
|
||||
return res.status(201).json({ user })
|
||||
}
|
||||
```
|
||||
|
||||
You expose a `POST` API route at `/custom-auth/admin/users` that receives the user's email in the request body. It executes `createUserWorkflow` to create the user and returns the created user in the response.
|
||||
|
||||
### Apply Authentication Middleware
|
||||
|
||||
Finally, you need to apply the authentication [middleware](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/middlewares/index.html.md) to the API route to ensure that only authenticated users can access it.
|
||||
|
||||
To do this, create the file `src/api/middlewares.ts` with the following content:
|
||||
|
||||
```ts title="src/api/middlewares.ts"
|
||||
import { authenticate, defineMiddlewares } from "@medusajs/framework/http"
|
||||
|
||||
export default defineMiddlewares({
|
||||
routes: [
|
||||
{
|
||||
matcher: "/custom-auth/admin/users",
|
||||
methods: ["POST"],
|
||||
middlewares: [
|
||||
authenticate("user", "bearer", {
|
||||
allowUnregistered: true,
|
||||
}),
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
This middleware applies the `authenticate` middleware to the `/custom-auth/admin/users` `POST` route, allowing only authenticated users to access it. By enabling the `allowUnregistered` option, users who are authenticated through the third-party provider but don't yet have an associated Medusa user can still access the route to create their user.
|
||||
|
||||
Refer to the [Protected Routes](https://docs.medusajs.com/docs/learn/fundamentals/api-routes/protected-routes/index.html.md) guide to learn more about protecting API routes with the `authentication` middleware.
|
||||
|
||||
***
|
||||
|
||||
## Step 4: Add a Widget on the Login Page
|
||||
|
||||
Finally, you need to add a [widget](https://docs.medusajs.com/docs/learn/fundamentals/admin/widgets/index.html.md) to the Medusa Admin login page that provides the option to log in through the third-party provider.
|
||||
|
||||
The widget should display a button that authenticates or redirects the user to the third-party provider. The widget should also handle the redirection back to the Medusa Admin after successful authentication.
|
||||
|
||||
For example, the widget may look like this:
|
||||
|
||||
```tsx
|
||||
import { defineWidgetConfig } from "@medusajs/admin-sdk"
|
||||
import { Button, toast } from "@medusajs/ui"
|
||||
import { decodeToken } from "react-jwt"
|
||||
import { useSearchParams, useNavigate } from "react-router-dom"
|
||||
import { useMutation } from "@tanstack/react-query"
|
||||
import { sdk } from "../lib/sdk"
|
||||
import { useEffect } from "react"
|
||||
|
||||
// Replace with the identifier of your custom authentication provider
|
||||
const CUSTOM_AUTH_PROVIDER = "custom"
|
||||
|
||||
const CustomLogin = () => {
|
||||
// The third-party provider redirects back with query parameters
|
||||
// used to validate the authentication
|
||||
const [searchParams] = useSearchParams()
|
||||
const navigate = useNavigate()
|
||||
const { mutateAsync, isPending } = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (isPending) {
|
||||
return
|
||||
}
|
||||
return await validateCallback()
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error("Custom authentication error:", error)
|
||||
},
|
||||
})
|
||||
|
||||
const sendCallback = async () => {
|
||||
try {
|
||||
return await sdk.auth.callback(
|
||||
"user",
|
||||
CUSTOM_AUTH_PROVIDER,
|
||||
Object.fromEntries(searchParams)
|
||||
)
|
||||
} catch (error) {
|
||||
toast.error("Authentication failed")
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// Validate the authentication callback
|
||||
const validateCallback = async () => {
|
||||
const token = await sendCallback()
|
||||
|
||||
const decodedToken = decodeToken(token) as { actor_id: string, user_metadata: Record<string, unknown> }
|
||||
|
||||
const userExists = decodedToken.actor_id !== ""
|
||||
|
||||
if (!userExists) {
|
||||
// Create user
|
||||
await sdk.client.fetch("/custom-auth/admin/users", {
|
||||
method: "POST",
|
||||
body: {
|
||||
email: decodedToken.user_metadata?.email as string,
|
||||
},
|
||||
})
|
||||
|
||||
const newToken = await sdk.auth.refresh()
|
||||
|
||||
if (!newToken) {
|
||||
toast.error("Authentication failed")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// User is authenticated
|
||||
navigate("/orders")
|
||||
}
|
||||
|
||||
// Handle custom login button click
|
||||
const customLogin = async () => {
|
||||
const result = await sdk.auth.login("user", CUSTOM_AUTH_PROVIDER, {})
|
||||
|
||||
if (typeof result === "object" && result.location) {
|
||||
// Redirect to custom provider for authentication
|
||||
window.location.href = result.location
|
||||
return
|
||||
}
|
||||
|
||||
if (typeof result !== "string") {
|
||||
// Result failed, show an error
|
||||
toast.error("Authentication failed")
|
||||
return
|
||||
}
|
||||
|
||||
navigate("/app")
|
||||
}
|
||||
|
||||
// Handle the redirection back from the third-party provider
|
||||
useEffect(() => {
|
||||
// Check for provider-specific query parameters
|
||||
if (searchParams.get("code")) {
|
||||
mutateAsync()
|
||||
}
|
||||
}, [searchParams, mutateAsync])
|
||||
|
||||
return (
|
||||
<>
|
||||
<hr className="bg-ui-border-base my-4" />
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={customLogin}
|
||||
className="w-full"
|
||||
>
|
||||
Login with Custom Provider
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export const config = defineWidgetConfig({
|
||||
zone: "login.after",
|
||||
})
|
||||
|
||||
export default CustomLogin
|
||||
```
|
||||
|
||||
You inject the widget into the `login.after` zone. This displays it below the default email and password login form.
|
||||
|
||||
You can't remove the default email and password login form from the Medusa Admin. You can only add additional login options through widgets.
|
||||
|
||||
In the widget, you:
|
||||
|
||||
1. Display a button that initiates login through the third-party provider using the `sdk.auth.login` method.
|
||||
- If the login method returns a `location` property, redirect the user to that location to authenticate through the third-party provider.
|
||||
- Otherwise, if the login method returns a token, the user is authenticated and you navigate to the Orders page of the admin dashboard.
|
||||
2. Add a `useEffect` hook that checks for provider-specific query parameters in the URL, such as `code`, to handle the redirection back from the third-party provider after successful authentication.
|
||||
3. Upon redirection back, you:
|
||||
- Call the `sdk.auth.callback` method to validate the authentication with the third-party provider.
|
||||
- If the user doesn't exist in Medusa, call the [custom API route you created](#step-3-create-user-api-route) to create the user, then refresh the authentication token.
|
||||
- Finally, if authentication is successful, navigate to the Orders page of the admin dashboard.
|
||||
|
||||
***
|
||||
|
||||
## Test Custom Authentication in Medusa Admin
|
||||
|
||||
To test the custom authentication in the Medusa Admin, run the following command to start your Medusa application:
|
||||
|
||||
```bash npm2yarn
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Then, open the Medusa Admin at `http://localhost:9000/app`, which will redirect you to the login page.
|
||||
|
||||
On the login page, you should see the option to log in through the third-party provider you integrated. Click the button to log in through the provider and follow the authentication flow.
|
||||
|
||||
If authentication is successful, you'll have access to the Medusa Admin dashboard. Otherwise, you can troubleshoot the issue by checking your Medusa application's logs or the browser's console for errors.
|
||||
|
||||
|
||||
# How-to & Tutorials
|
||||
|
||||
In this section of the documentation, you'll find how-to guides and tutorials that will help you customize the Medusa server and admin. These guides are useful after you've learned Medusa's main concepts in the [Get Started](https://docs.medusajs.com/docs/learn/index.html.md) section of the documentation.
|
||||
|
||||
Reference in new issue
Block a user