Co-Authored-By: Claude Fable 5.2 <[email protected]>
360 lines
23 KiB
Markdown
360 lines
23 KiB
Markdown
# access
|
||
|
||
Role-based access control: hierarchy **admin > editor > user**.
|
||
The plugin injects a fixed `roles` field into the client's auth collection and provides
|
||
predicates and ready access functions (collection-level and field-level).
|
||
|
||
## Config (payload.config.ts)
|
||
|
||
```ts
|
||
ipalKit({
|
||
access: {
|
||
authCollection: 'users', // slug of your auth collection (required)
|
||
// defaultRole: 'user', // role of new accounts
|
||
// firstUserAdmin: true, // the account from "Create first user" → admin
|
||
// authAccess: { … }, // access of the injected auth collection (your keys win)
|
||
// staffCollections: ['partners'], // more auth collections whose accounts are staff
|
||
},
|
||
// globalOverrides: { … }, // access / admin / hooks / fields of the plugin's globals
|
||
})
|
||
```
|
||
|
||
| Option | Default | What it does |
|
||
|---|---|---|
|
||
| `access.authCollection` | — (required) | the auth collection that gets the `roles` field |
|
||
| `access.defaultRole` | `'user'` | role of a new account when an admin did not set one |
|
||
| `access.firstUserAdmin` | `true` | the account from the "Create first user" screen (`…/first-register` on an empty collection) gets `['admin']`, even when the form picked `user`; `false` = it gets what was submitted — then mind the panel role, [Account rules](#account-rules-accounts) |
|
||
| `access.authAccess` | see the table below | `access` of the **injected** auth collection, merged over the default (your keys win) |
|
||
| `access.staffCollections` | `[]` | more auth collections whose accounts count as **staff**, besides the one the panel logs in with (`admin.user`); see "Who is staff" |
|
||
| `globalOverrides` | — | changes to the plugin's globals: an object merges `access` / `admin` key by key (your keys win) and appends `hooks` (yours run after the plugin's), other keys (label, fields, …) replace; a function `(global) => global` takes over the whole global |
|
||
|
||
The `roles` field (select hasMany, required, `saveToJWT`): readable without limits; only an admin
|
||
can set and change it — also on account creation, so an open sign-up cannot
|
||
push `roles: ['admin']` through. The first-user screen and the Local API (seed) run with
|
||
`overrideAccess`. An account without roles meets no threshold (not even `'user'`); `authenticated`
|
||
only checks that someone is logged in.
|
||
|
||
**Auth collection when the project has none.** The plugin adds a minimal collection (`auth: true`,
|
||
`admin.useAsTitle: 'email'`) with the slug `access.authCollection` (or `twoFactor.collectionSlug`,
|
||
`admin.user`, `'users'`). The project's own collection with that slug always wins whole.
|
||
|
||
## What the plugin locks down by itself
|
||
|
||
| Resource | Read | Write | How to change |
|
||
|---|---|---|---|
|
||
| auth collection **injected** by the plugin, with roles | admin: everyone; other accounts **of that collection**: only themselves (`adminOrSelfIn`) | `create` / `delete` / `unlock`: admin; `update`: admin or self | `access.authAccess`, or your own collection |
|
||
| Site settings, Cookie banner, Notifications | public | `editor+` | `globalOverrides` |
|
||
| Site integrations | admin | admin | `globalOverrides` |
|
||
| Forms | public (Emails tab only `editor+`) | `editor+` | `forms.formOverrides.access`, the Emails field in `formOverrides.fields` |
|
||
| Form submissions | `editor+` | REST `create`: logged-in users; `delete`: admin | `forms.formSubmissionOverrides.access` |
|
||
|
||
```ts
|
||
import { authenticated } from '@intecion/ipal-kit'
|
||
ipalKit({
|
||
access: { authCollection: 'users', authAccess: { read: authenticated } }, // editors see the account list
|
||
globalOverrides: {
|
||
notifications: { access: { update: authenticated } }, // any logged-in account edits the texts
|
||
'site-settings': (g) => ({ ...g, admin: { ...g.admin, group: 'Configuration' } }),
|
||
},
|
||
})
|
||
```
|
||
|
||
The project's own auth collection keeps its own `access` — the plugin only adds the
|
||
`roles` field. Give it at least `update: adminOrSelfIn('users')`, `delete: adminOnly`, `create: adminOnly`,
|
||
`unlock: adminOnly`: Payload's default lets any logged-in account change the email and password
|
||
of another account and unlock any account. A collection injected **without** `access` (no roles)
|
||
keeps Payload's default rules — without roles all accounts are equal.
|
||
|
||
## Who is staff
|
||
|
||
**Staff collections** are the auth collections whose accounts work in the panel:
|
||
|
||
- the one the admin panel logs in with (`admin.user`; Payload's default is the **first** auth collection in the
|
||
list — set `admin: { user: 'users' }` yourself as soon as the project has two);
|
||
- the one that carries the plugin's roles (`access.authCollection`);
|
||
- the ones named in `access.staffCollections`.
|
||
|
||
An account of **any other auth collection** — `customers`, `members`, a client zone — is a visitor to the
|
||
plugin. **Nothing in the plugin counts a role for it**, also when its own collection has a `roles` field with
|
||
the value `admin`: not `userMeetsRole`, not `isAdmin` / `isEditor` / `hasMinimumRole`, not `adminOnly`,
|
||
`adminOrEditor`, `requireRole`, `adminOrSelf`, `adminOrSelfIn` or the `…Field` variants, not the `roles` field
|
||
itself. The staff-collection check always comes first.
|
||
|
||
The plugin's own staff features — Site integrations, the settings globals, form submissions, consent records,
|
||
stats, the cookie scanner, `/api/ipal/test-email` — check with `userMeetsRole(req, minimum)`, in this order:
|
||
|
||
1. the account belongs to a staff collection;
|
||
2. with 2FA on: the account has set TOTP up and has entered the code in this session
|
||
([security.md](./security.md) → "What the second factor covers", "Setup required");
|
||
3. it holds at least the role `minimum` — **or** its collection has no `roles` field at all. Then every account
|
||
of that staff collection passes, as in Payload's default (without roles all accounts are equal).
|
||
|
||
What follows:
|
||
|
||
- **Without `access`** there is no `roles` field, so `isAdmin` always returns `false` and rule 3 keeps the
|
||
staff features reachable: every account of the panel collection is admin to the plugin. To narrow that
|
||
without roles: `globalOverrides` for the globals, `forms.formSubmissionOverrides` for submissions, or add
|
||
`access` to get roles.
|
||
- **A second staff collection** (e.g. `partners` who edit content): name it in
|
||
`access.staffCollections`. That is the one switch that makes its roles count. Without a `roles` field every
|
||
partner passes every staff check, admin ones included; to tell them apart add the field:
|
||
`fields: [buildRolesField('editor')]` in that collection. **2FA covers one collection** (`twoFactor.collectionSlug`,
|
||
by default the panel's): accounts of a further staff collection are staff with a password alone. ipalKit says
|
||
so in the log at start (`[ipal] 2FA covers "users" only…`); name such a collection only when that is acceptable.
|
||
- **Payload's own default** for a collection or global without `access` is "any logged-in account" — an account
|
||
of a visitor collection included. In a project with a second auth collection give every collection and global
|
||
explicit `access` (`adminOrEditor`, `requireRole(…)`, …).
|
||
- **A visitor collection that should reach one thing** (e.g. customers read their own form submissions):
|
||
do not make it staff. Write that one rule yourself — `forms.formSubmissionOverrides.access.read`,
|
||
`globalOverrides`, `collectionOverrides` of the module — and check `req.user.collection` in it.
|
||
- **A user object you build yourself** (Local API with `overrideAccess: false`, a custom auth strategy) must
|
||
carry `collection`: `{ ...doc, collection: 'users' }`. Payload's own strategies and `payload.auth()` set it. An
|
||
account without it is not staff.
|
||
|
||
> **Changed in 1.16.4.** Before, a role or the "no roles field" rule counted for an account
|
||
> of any auth collection: an account of a second auth collection passed staff checks — every one when its
|
||
> collection had no `roles` field, and the matching ones when it had its own `roles` field. A project with one
|
||
> auth collection sees no difference. A project that relied on a second collection being staff sets
|
||
> `access.staffCollections`.
|
||
|
||
## Predicates (front end / hooks / access)
|
||
|
||
```ts
|
||
import { isAdmin, isEditor, hasMinimumRole, staffCollectionSlugs, userMeetsRole } from '@intecion/ipal-kit'
|
||
|
||
isAdmin(req.user, req.payload) // a staff account with the admin role
|
||
isEditor(req.user, req.payload) // editor or admin (hierarchy)
|
||
hasMinimumRole(req.user, 'editor', req.payload) // at least editor
|
||
userMeetsRole(req, 'admin') // the plugin's staff check: staff collection, second factor, role ("Who is staff")
|
||
staffCollectionSlugs(req.payload) // ['users', …]
|
||
```
|
||
|
||
They take a loosely typed user (like `req.user`) and read `roles` defensively. The last argument tells them
|
||
which collections are staff:
|
||
|
||
| Where you call it | Pass | Without it |
|
||
|---|---|---|
|
||
| access functions, hooks, endpoints (server, the config is loaded) | `req.payload` | works: the staff collections of the config `ipalKit` built in this process. With two different configs in one process, only collections that are staff in **both** count — pass `req.payload` to get that config's own answer |
|
||
| client components — import from **`@intecion/ipal-kit/client`** | the config from `useConfig()` (it has `admin.user`, the panel's login collection), or `{ staffCollections: ['users', …] }` | **always `false`** — the browser bundle has no config |
|
||
| Next middleware / `proxy.ts`, the edge runtime | `{ staffCollections: ['users'] }` | **always `false`** — the config is not loaded there |
|
||
|
||
```tsx
|
||
'use client'
|
||
import { isAdmin } from '@intecion/ipal-kit/client' // not '@intecion/ipal-kit'
|
||
import { useAuth, useConfig } from '@payloadcms/ui'
|
||
|
||
export function AdminOnlyHint() {
|
||
const { config } = useConfig()
|
||
const { user } = useAuth()
|
||
// a hint only — the server decides
|
||
return isAdmin(user, config) ? <p>…</p> : null
|
||
}
|
||
```
|
||
|
||
- **The import in a client component is `/client`** (`hasMinimumRole`, `isAdmin`, `isEditor`, the type `Role`). The main
|
||
entry reaches `server-only` modules: with `next build --webpack` it fails with `'server-only' cannot be imported from
|
||
a Client Component module` (Turbopack builds it, but the import does not belong there either).
|
||
In 1.16.4–1.16.6 `/client` does not have them — upgrade.
|
||
- **On the server** (config, hooks, access functions, endpoints, server components, `proxy.ts`) import from
|
||
`@intecion/ipal-kit`: `/client` is a `'use client'` entry, a server component that calls a function from it fails.
|
||
- `useConfig()` carries `admin.user` only (Payload strips `config.custom` from the client config). Accounts of
|
||
`access.staffCollections` need the list: `isAdmin(user, { staffCollections: ['users', 'partners'] })`.
|
||
|
||
They fail closed: where the staff collections are not known, nobody is staff, and an account without
|
||
`collection` is nobody. `isAdmin` and the others do **not** check the second factor; `userMeetsRole` and every
|
||
`access` function in the config do.
|
||
|
||
## Ready access functions
|
||
|
||
### Collection-level (return boolean | Where)
|
||
|
||
```ts
|
||
import { adminOnly, adminOrEditor, adminOrSelf, adminOrSelfIn, requireRole, authenticated } from '@intecion/ipal-kit'
|
||
|
||
export const Articles = {
|
||
slug: 'articles',
|
||
access: {
|
||
read: authenticated,
|
||
create: adminOrEditor,
|
||
update: adminOrEditor,
|
||
delete: adminOnly,
|
||
},
|
||
// ...
|
||
}
|
||
|
||
// Users: everyone sees themselves, an admin sees everyone.
|
||
// adminOrSelfIn(slug): "self" = an account of THAT collection. Use it for an auth collection whenever
|
||
// the project has more than one: adminOrSelf only compares ids, and with numeric ids (Postgres, SQLite)
|
||
// customer no. 5 would match staff account no. 5.
|
||
access: { read: adminOrSelfIn('users') }
|
||
access: { read: adminOrSelf } // fine with a single auth collection
|
||
|
||
// any minimum threshold
|
||
access: { update: requireRole('editor') }
|
||
```
|
||
|
||
### Field-level (return boolean)
|
||
|
||
```ts
|
||
import { adminOnlyField, adminOrEditorField, requireRoleField } from '@intecion/ipal-kit'
|
||
|
||
{
|
||
name: 'internalNote',
|
||
type: 'textarea',
|
||
access: { read: adminOnlyField, update: adminOnlyField },
|
||
}
|
||
```
|
||
|
||
## Hierarchy
|
||
|
||
```ts
|
||
import { ROLE_HIERARCHY } from '@intecion/ipal-kit'
|
||
// ['user', 'editor', 'admin'] — a higher role meets a lower role's requirement
|
||
```
|
||
|
||
## Building blocks: buildRolesField, injectRoles, applyGlobalOverrides
|
||
|
||
```ts
|
||
import { applyGlobalOverrides, buildRolesField, injectRoles } from '@intecion/ipal-kit'
|
||
|
||
buildRolesField('user', { firstUserAdmin: true }) // just the roles field — for your own collection
|
||
injectRoles(config, { authCollection: 'members' }) // add the field to a collection in a finished config
|
||
applyGlobalOverrides(globals, { notifications: { … } }) // the same logic as the globalOverrides option
|
||
```
|
||
|
||
Types: `AccessOption`, `Role`, `GlobalOverride`, `GlobalOverrides`, `IpalGlobalSlug`.
|
||
|
||
## Account rules (`accounts`)
|
||
|
||
Rules for the accounts of the staff collection. All on by default; each has its own switch, and
|
||
`ipalKit({ accounts: false })` turns them all off.
|
||
|
||
```ts
|
||
ipalKit({
|
||
access: { authCollection: 'users' },
|
||
// accounts: { panelRole: 'user' }, // every account may open the panel (as before)
|
||
// accounts: { adminOnlyCreate: false }, // Payload's default `create` on your own staff collection
|
||
// accounts: { adminOnlyWrite: false }, // Payload's default `update` / `delete` there
|
||
// accounts: { firstUserRoute: 'all' }, // Payload's first-user route for every empty auth collection
|
||
// accounts: { firstUserRoute: ['users', 'partners'] },
|
||
// accounts: { password: { minLength: 16 } }, // or password: false
|
||
// accounts: false, // none of the rules
|
||
})
|
||
```
|
||
|
||
### Who may open the panel (`accounts.panelRole`, default `'editor'`)
|
||
|
||
The lowest role, `user`, is what a new account gets (`access.defaultRole`) and has no business in the panel. The
|
||
panel opens for `editor` and above: it is Payload's `access.admin` on the collection that carries the roles. An
|
||
account that holds only `user` (or no role) logs in and sees Payload's "Unauthorized" screen. **The API is not
|
||
touched** — such an account still gets over REST / GraphQL what its role allows. The rule looks at the role, not
|
||
at the second factor, so the 2FA screens stay reachable.
|
||
|
||
- **What an existing site sees on the first start:** the log line `[ipal] N account(s) of "users" are below the
|
||
role "editor" and cannot open the admin panel` — give those people `editor`, or set `panelRole: 'user'`. When
|
||
**no** account has the role it is an error (`NOBODY can open the admin panel`): give one account the role with
|
||
a script (`payload.update`, Local API) or set `accounts: { panelRole: false }` and redeploy.
|
||
- `'admin'` = admins only; `'user'` or `false` = everyone, as before. Needs `access` (the roles). Your own
|
||
`access.admin` on the collection, or `access.authAccess.admin`, wins. Building blocks: `panelAccess(role)`,
|
||
`applyPanelRole`, `resolvePanelRole`, `countBelowPanelRole`, `DEFAULT_PANEL_ROLE`.
|
||
- **Check:** log in to `/admin` as an account with the role `user` → "Unauthorized"; `GET /api/access` for it →
|
||
`canAccessAdmin: false`; `GET /api/users/me` still answers.
|
||
|
||
### Nobody creates an account for themselves, or takes one over (`accounts.adminOnlyCreate`, `accounts.adminOnlyWrite`, `accounts.firstUserRoute`)
|
||
|
||
By default only the first account of a site can be registered by a visitor, and it becomes admin
|
||
(`access.firstUserAdmin`); every other account is made by an admin, and an account is changed by an admin or by
|
||
its owner.
|
||
|
||
Payload's default for a collection without access rules is "any logged-in user" for `create`, `update` and
|
||
`delete` — an account of **any** auth collection. On a project's own staff collection a visitor account
|
||
(`customers`) could therefore create a staff account, or `PATCH` a staff account's password and roles.
|
||
|
||
| | Before | Now (default) |
|
||
|---|---|---|
|
||
| Anonymous `POST /api/users`, GraphQL `createUser` | refused | refused |
|
||
| The first account: `POST /api/users/first-register` on an empty collection | 200, role `admin` | the same |
|
||
| A signed-in editor or plain user creates an account in the plugin's injected collection | refused | refused |
|
||
| …in **the project's own** staff collection that has no `create` rule | **allowed** (Payload's default) | refused — an admin, fully signed in |
|
||
| A visitor account (`customers`) changes or deletes an account of the project's own staff collection that has no `update` / `delete` rule | **allowed** (Payload's default) | refused |
|
||
| `POST /api/<slug>/first-register` on another empty auth collection (`members`) | **200** | 403 |
|
||
| …on an empty **second staff collection** (`access.staffCollections`) | **200, and that account was staff** | 403 — an admin of the panel's collection creates its first account |
|
||
| A collection that allows sign-up (`customers` with `create: () => true`) | allowed | allowed, its first-user route too |
|
||
|
||
**Which rule a staff collection gets** (the panel's login collection, `access.authCollection`,
|
||
`access.staffCollections`) — only for an operation it has **no** rule for; a rule you wrote always stays:
|
||
|
||
| The collection | `create` | `update` | `delete` |
|
||
|---|---|---|---|
|
||
| carries **the plugin's roles**: it is `access.authCollection`, or has a `roles` select whose values are all `user` / `editor` / `admin` (`hasPluginRoles`) | an admin (`staffCreateAccess`) | an admin, or the account itself (`staffUpdateAccess(slug)`) | an admin |
|
||
| has **roles of its own** (`superadmin`, `writer`, …) or no `roles` field — the plugin cannot tell who its admins are | an account of that same collection, or a plugin admin of another staff collection (`sameStaffCollectionAccess(slug)`) | the same | the same |
|
||
|
||
Always "fully signed in": a session that still owes its second factor passes none of them. In the second row
|
||
your own roles are not enforced by the plugin — what was allowed inside the collection stays allowed; what
|
||
closes is the door for accounts of **other** collections. Write your own rules to say who inside may do what.
|
||
|
||
- `adminOnlyCreate: false` = Payload's default `create`; `adminOnlyWrite: false` = Payload's default `update`
|
||
and `delete`. The rules are put on the collections **before** the 2FA package wraps them, so they hold with
|
||
2FA on and off.
|
||
- `read` is not touched: a staff collection of your own without a `read` rule is readable by any logged-in
|
||
account (Payload's default; the injected collection has "admin or self"). Write a `read` rule
|
||
(`adminOrSelfIn(slug)`).
|
||
- `firstUserRoute`: `'panel'` (default) = the collection the panel logs in with; a list of slugs = those;
|
||
`'all'` = Payload's behaviour. A collection whose own `create` rule lets an anonymous request through keeps
|
||
its route. The plugin puts its own `POST /first-register` endpoint in front of Payload's on every auth
|
||
collection (`buildFirstUserEndpoint`): it refuses, or hands the request to Payload's handler. It does not read
|
||
the request path, so the spelling of the URL (`/First-Register`) changes nothing. A collection with
|
||
`endpoints: false` is left alone.
|
||
- **A fresh site:** whoever opens the panel first becomes the admin — create the first account right after the
|
||
first deploy.
|
||
- **`access.firstUserAdmin: false`** gives the first account the default role. If that role is below the panel
|
||
role, nobody could open the panel on a fresh site: with the default panel role the plugin then does **not**
|
||
apply it and says so at start; with `accounts.panelRole` set by you the config is refused at start. Set
|
||
`access.defaultRole: 'editor'`, or `accounts: { panelRole: false }`.
|
||
- **What an existing site sees:** nothing, unless its own staff collection relied on Payload's defaults
|
||
(non-admins creating accounts in a collection with the plugin's roles; accounts of another collection writing
|
||
to it) — then write the rule you want, or set `adminOnlyCreate: false` / `adminOnlyWrite: false`.
|
||
- `ipal-doctor --url`: `open-signup` (info) lists auth collections with open sign-up; `staff-accounts-open`
|
||
(error) names a staff collection an account of another collection may create in, update or delete from
|
||
(the rules are off, or your own rule is wider).
|
||
- Building blocks: `staffCreateAccess`, `staffUpdateAccess`, `sameStaffCollectionAccess`, `hasPluginRoles`,
|
||
`applyStaffAccountAccess`, `buildFirstUserEndpoint`, `applyFirstUserRoute`, `openSignUpCollections`,
|
||
`staffCollectionsOpenToOthers`.
|
||
- **Check:** `curl -X POST <site>/api/members/first-register -H 'content-type: application/json' -d
|
||
'{"email":"x@example.com","password":"a-long-password-1"}'` → `403`, also as `/First-Register`; the same for
|
||
`/api/users` → `403`. Logged in as a visitor account: `PATCH /api/users/<id>` → `403`.
|
||
|
||
### Passwords (`accounts.password`, default 12 characters)
|
||
|
||
When a password is **set** on a staff collection — a new account, the first-user screen, a change, a reset by
|
||
e-mail; in the panel, over the API and through the Local API — it must have at least 12 characters and must not
|
||
be the account's own e-mail address (Payload's own rule is 3 characters). **Existing passwords are never
|
||
checked:** an account with a shorter one keeps logging in, and meets the rule the next time its password is
|
||
changed. The message is in the panel's language, English or Polish ("The password must have at least 12
|
||
characters."; texts `passwordTooShort`, `passwordIsEmail` in `i18n.translations.<lang>.ipal`).
|
||
|
||
- `password: { minLength: 16 }`; `password: false` = Payload's rule. Visitor collections are not touched.
|
||
- Checked against the account's address also where the request carries none: a change by id, a reset by e-mail
|
||
(the account is found by its token), a bulk update (every account it matches). A password that is not text
|
||
(a number, a list) is refused with the same message.
|
||
- No breached-password lookup (it would send part of a hash of every new password to an outside service);
|
||
build one on `checkPassword` / `buildPasswordRuleHook` if a project needs it.
|
||
- A script or seed that creates a staff account with a shorter password now fails with a validation error.
|
||
- Building blocks: `checkPassword`, `buildPasswordRuleHook`, `applyPasswordRule`, `resolvePasswordRule`,
|
||
`DEFAULT_PASSWORD_MIN_LENGTH`.
|
||
- **Check:** create an account with an 11-character password → "The password must have at least 12 characters.".
|
||
|
||
## Turn off, override, extend
|
||
|
||
- **Account rules:** `accounts: false`, or one by one — `panelRole`, `adminOnlyCreate`, `adminOnlyWrite`,
|
||
`firstUserRoute`, `password` (above).
|
||
- **Turn off:** leave out `access` — no `roles` field, the auth collection keeps Payload's rules
|
||
(or yours). `access.firstUserAdmin: false` stops giving admin to the first account.
|
||
- **Override:** `access.staffCollections` (who is staff), `access.authAccess` (injected collection), your own auth collection (wins whole),
|
||
`globalOverrides` (globals), `forms.formOverrides` / `formSubmissionOverrides` (forms),
|
||
`defaultRole`. The role hierarchy (`ROLE_HIERARCHY`) is fixed.
|
||
- **Extend:** `requireRole` / `requireRoleField`, `adminOrSelfIn`, predicates (`userMeetsRole`, `staffCollectionSlugs`), `buildRolesField`, `injectRoles`,
|
||
`applyGlobalOverrides` in your own collections and globals.
|
||
- **Check:** log in with a `user` account → `PATCH /api/globals/site-settings` = 403,
|
||
`DELETE /api/users/<admin id>` = 403; the account from "Create first user" has the `admin` role.
|