Co-Authored-By: Claude Fable 5.2 <[email protected]>
26 KiB
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)
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 |
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 |
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 — setadmin: { 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:
- the account belongs to a staff collection;
- with 2FA on: the account has set TOTP up and has entered the code in this session (security.md → "What the second factor covers", "Setup required");
- it holds at least the role
minimum— or its collection has norolesfield at all. Then every account of that staff collection passes, as in Payload's default (without roles all accounts are equal).
What follows:
- Without
accessthere is norolesfield, soisAdminalways returnsfalseand rule 3 keeps the staff features reachable: every account of the panel collection is admin to the plugin. To narrow that without roles:globalOverridesfor the globals,forms.formSubmissionOverridesfor submissions, or addaccessto get roles. - A second staff collection (e.g.
partnerswho edit content): name it inaccess.staffCollections. That is the one switch that makes its roles count. Without arolesfield 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
accessis "any logged-in account" — an account of a visitor collection included. In a project with a second auth collection give every collection and global explicitaccess(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,collectionOverridesof the module — and checkreq.user.collectionin it. - A user object you build yourself (Local API with
overrideAccess: false, a custom auth strategy) must carrycollection:{ ...doc, collection: 'users' }. Payload's own strategies andpayload.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
rolesfield, and the matching ones when it had its ownrolesfield. A project with one auth collection sees no difference. A project that relied on a second collection being staff setsaccess.staffCollections.
Predicates (front end / hooks / access)
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 |
'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 typeRole). The main entry reachesserver-onlymodules: withnext build --webpackit 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/clientdoes not have them — upgrade. - On the server (config, hooks, access functions, endpoints, server components,
proxy.ts) import from@intecion/ipal-kit:/clientis a'use client'entry, a server component that calls a function from it fails. useConfig()carriesadmin.useronly (Payload stripsconfig.customfrom the client config). Accounts ofaccess.staffCollectionsneed 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)
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)
import { adminOnlyField, adminOrEditorField, requireRoleField } from '@intecion/ipal-kit'
{
name: 'internalNote',
type: 'textarea',
access: { read: adminOnlyField, update: adminOnlyField },
}
Hierarchy
import { ROLE_HIERARCHY } from '@intecion/ipal-kit'
// ['user', 'editor', 'admin'] — a higher role meets a lower role's requirement
Building blocks: buildRolesField, injectRoles, applyGlobalOverrides
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.
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` / `unlock` there, roles field left alone
// accounts: { staffOnlyRead: false }, // Payload's default `read` 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 peopleeditor, or setpanelRole: '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 setaccounts: { panelRole: false }and redeploy. 'admin'= admins only;'user'orfalse= everyone, as before. Needsaccess(the roles). Your ownaccess.adminon the collection, oraccess.authAccess.admin, wins. Building blocks:panelAccess(role),applyPanelRole,resolvePanelRole,countBelowPanelRole,DEFAULT_PANEL_ROLE.- Check: log in to
/adminas an account with the roleuser→ "Unauthorized";GET /api/accessfor it →canAccessAdmin: false;GET /api/users/mestill answers.
Nobody creates an account for themselves, or takes one over (accounts.adminOnlyCreate, accounts.adminOnlyWrite, accounts.staffOnlyRead, 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, read, update,
delete and unlock — an account of any auth collection. On a project's own staff collection a visitor
account (customers) could therefore create a staff account, PATCH a staff account's password and roles,
list the staff accounts, and lift the lock after failed logins.
| 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 |
| A visitor account lists the accounts of such a collection, or unlocks one | allowed (Payload's default) | refused |
An account of such a collection changes its own roles (the field has no access of its own) |
allowed | refused — with the plugin's roles only an admin changes roles |
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, delete, unlock |
update |
the roles field (when it has no access.update) |
read |
|---|---|---|---|---|
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)) |
only an admin changes it (rolesByAdminOnly) |
a staff account (staffReadAccess) |
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 | an account never changes its own (rolesNotOwn(slug)) |
a staff account |
Always "fully signed in": a session that still owes its second factor passes none of them.
Roles of your own — what the plugin does and does not hold. It cannot rank superadmin against writer,
so inside such a collection it enforces one thing only: an account does not change its own roles. Everything
else that was allowed inside the collection stays allowed — every account of it may still create an account
with any role, and change or delete another account. That is a hole only you can close: write the
collection's create / update / delete rules and the field access of its roles field from your roles.
ipal-doctor --url names such a collection (staff-own-roles, warning). What the plugin closes for you is the
door for accounts of other collections.
A staff collection without a roles field: every account of it is an admin to the plugin (unchanged), so
it may also manage the accounts of the other staff collections. Give it the plugin's roles
(buildRolesField), or write its rules.
A staff collection that a plugin listed after ipalKit adds gets the same rules, the password rule and the
first-user endpoint when the site starts (and on a dev reload); the log says [ipal] Account rules also put on auth collections added after ipalKit: …. There the plugin tells "no rule" from "your rule" by Payload's own
default function, so a rule you wrote stays. A slug in access.staffCollections or access.authCollection
that is not an auth collection of the config stops the start with the slug and the list of auth
collections (unknownStaffCollections).
adminOnlyCreate: false= Payload's defaultcreate;adminOnlyWrite: false= Payload's defaultupdate,deleteandunlock, and therolesfield is left alone;staffOnlyRead: false= Payload's defaultread. The rules are put on the collections before the 2FA package wraps them, so they hold with 2FA on and off.read= "a fully signed-in account of a staff collection": staff sees staff (the panel needs it for relationship fields and the account list), a visitor account sees nothing. The injected collection keeps its stricter "admin or self". A front end that shows staff accounts to logged-in visitors needs its ownreadrule on that collection (a rule you wrote wins), orstaffOnlyRead: false.firstUserRoute:'panel'(default) = the collection the panel logs in with; a list of slugs = those;'all'= Payload's behaviour. A collection whose owncreaterule lets an anonymous request through keeps its route. The plugin puts its ownPOST /first-registerendpoint 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 withendpoints: falseis left alone.- A fresh site: whoever opens the panel first becomes the admin — create the first account right after the first deploy.
access.firstUserAdmin: falsegives 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; withaccounts.panelRoleset by you the config is refused at start. Setaccess.defaultRole: 'editor', oraccounts: { 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-own-roles(warning) a staff collection with role values of its own on the default rules;staff-accounts-open(error) names a staff collection an account of another collection may create in, read (a warning), update, delete from or unlock (the rules are off, or your own rule is wider).- Building blocks:
staffCreateAccess,staffUpdateAccess,staffReadAccess,sameStaffCollectionAccess,rolesByAdminOnly,rolesNotOwn,hasPluginRoles,applyStaffAccountAccess,adoptLateAuthCollections,unknownStaffCollections,buildFirstUserEndpoint,applyFirstUserRoute,openSignUpCollections,staffCollectionsOpenToOthers,staffCollectionsOnOwnRoles. - Check:
curl -X POST <site>/api/members/first-register -H 'content-type: application/json' -d '{"email":"[email protected]","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>andGET /api/users→403. As a non-admin of a staff collection:PATCHyour own account withroles→ the roles do not change.
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/buildPasswordRuleHookif 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,staffOnlyRead,firstUserRoute,password(above). - Turn off: leave out
access— norolesfield, the auth collection keeps Payload's rules (or yours).access.firstUserAdmin: falsestops 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,applyGlobalOverridesin your own collections and globals. - Check: log in with a
useraccount →PATCH /api/globals/site-settings= 403,DELETE /api/users/<admin id>= 403; the account from "Create first user" has theadminrole.