docs: revise main docs outline (#10502)

This commit is contained in:
Shahed Nasser
2024-12-09 13:54:42 +02:00
committed by GitHub
parent c8cb9b5c1a
commit 0ae98c51eb
141 changed files with 814 additions and 1181 deletions
@@ -0,0 +1,183 @@
export const metadata = {
title: `${pageNumber} Protected Routes`,
}
# {metadata.title}
In this chapter, youll learn how to create protected routes.
## What is a Protected Route?
A protected route is a route that requires requests to be user-authenticated before performing the route's functionality. Otherwise, the request fails, and the user is prevented access.
---
## Default Protected Routes
Medusa applies an authentication guard on routes starting with `/admin`, including custom API routes.
Requests to `/admin` must be user-authenticated to access the route.
<Note title="Tip">
Refer to the API Reference for [Admin](!api!/admin#authentication) and [Store](!api!/store#authentication) authentication methods.
</Note>
---
## Protect Custom API Routes
To protect custom API Routes to only allow authenticated customer or admin users, use the `authenticate` middleware imported from `@medusajs/medusa`.
For example:
export const highlights = [
[
"10",
"authenticate",
"Only authenticated admin users can access routes starting with `/custom/admin`",
],
[
"14",
"authenticate",
"Only authenticated customers can access routes starting with `/custom/customers`",
],
]
```ts title="src/api/middlewares.ts" highlights={highlights}
import {
defineMiddlewares,
authenticate,
} from "@medusajs/medusa"
export default defineMiddlewares({
routes: [
{
matcher: "/custom/admin*",
middlewares: [authenticate("user", ["session", "bearer", "api-key"])],
},
{
matcher: "/custom/customer*",
middlewares: [authenticate("customer", ["session", "bearer"])],
},
],
})
```
The `authenticate` middleware function accepts three parameters:
1. The type of user authenticating. Use `user` for authenticating admin users, and `customer` for authenticating customers. You can also pass `*` to allow all types of users.
2. An array of types of authentication methods allowed. Both `user` and `customer` scopes support `session` and `bearer`. The `admin` scope also supports the `api-key` authentication method.
3. An optional object of configurations accepting the following properties:
- `allowUnauthenticated`: (default: `false`) A boolean indicating whether authentication is required. For example, you may have an API route where you want to access the logged-in customer if available, but guest customers can still access it too.
- `allowUnregistered` (default: `false`): A boolean indicating if unregistered users should be allowed access. This is useful when you want to allow users who arent registered to access certain routes.
---
## Authentication Opt-Out
To disable the authentication guard on custom routes under the `/admin` path prefix, export an `AUTHENTICATE` variable in the route file with its value set to `false`.
For example:
```ts title="src/api/admin/custom/route.ts" highlights={[["15"]]}
import type {
AuthenticatedMedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
export const GET = async (
req: AuthenticatedMedusaRequest,
res: MedusaResponse
) => {
res.json({
message: "Hello",
})
}
export const AUTHENTICATE = false
```
Now, any request sent to the `/admin/custom` API route is allowed, regardless if the admin user is authenticated.
---
## Authenticated Request Type
To access the authentication details in an API route, such as the logged-in user's ID, set the type of the first request parameter to `AuthenticatedMedusaRequest`. It extends `MedusaRequest`.
The `auth_context.actor_id` property of `AuthenticatedMedusaRequest` holds the ID of the authenticated user or customer. If there isn't any authenticated user or customer, `auth_context` is `undefined`.
<Note>
If you opt-out of authentication in a route as mentioned in the [previous section](#authentication-opt-out), you can't access the authenticated user or customer anymore. Use the [authenticate middleware](#protect-custom-api-routes) instead.
</Note>
### Retrieve Logged-In Customer's Details
You can access the logged-in customers ID in all API routes starting with `/store` using the `auth_context.actor_id` property of the `AuthenticatedMedusaRequest` object.
For example:
```ts title="src/api/store/custom/route.ts" highlights={[["19", "req.auth_context.actor_id", "Access the logged-in customer's ID."]]} collapsibleLines="1-7" expandButtonLabel="Show Imports"
import type {
AuthenticatedMedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
import { Modules } from "@medusajs/framework/utils"
import { ICustomerModuleService } from "@medusajs/framework/types"
export const GET = async (
req: AuthenticatedMedusaRequest,
res: MedusaResponse
) => {
if (req.auth_context?.actor_id) {
// retrieve customer
const customerModuleService: ICustomerModuleService = req.scope.resolve(
Modules.CUSTOMER
)
const customer = await customerModuleService.retrieveCustomer(
req.auth_context.actor_id
)
}
// ...
}
```
In this example, you resolve the Customer Module's main service, then use it to retrieve the logged-in customer, if available.
### Retrieve Logged-In Admin User's Details
You can access the logged-in admin users ID in all API Routes starting with `/admin` using the `auth_context.actor_id` property of the `AuthenticatedMedusaRequest` object.
For example:
```ts title="src/api/admin/custom/route.ts" highlights={[["17", "req.auth_context.actor_id", "Access the logged-in admin user's ID."]]} collapsibleLines="1-7" expandButtonLabel="Show Imports"
import type {
AuthenticatedMedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
import { Modules } from "@medusajs/framework/utils"
import { IUserModuleService } from "@medusajs/framework/types"
export const GET = async (
req: AuthenticatedMedusaRequest,
res: MedusaResponse
) => {
const userModuleService: IUserModuleService = req.scope.resolve(
Modules.USER
)
const user = await userModuleService.retrieveUser(
req.auth_context.actor_id
)
// ...
}
```
In the route handler, you resolve the User Module's main service, then use it to retrieve the logged-in admin user.