payload-auth-rbac
Skill0 starsChanged 13 days agoMITView on GitHub
Multiple admins and role-based access control for Payload CMS 3 - users collection with typed roles saved to the JWT, first user becomes admin, collection and field access helpers, privilege escalation protection, login hardening, CSRF and CORS settings, and an access matrix for content, CRM, bookings, and settings. Use when adding admin users, roles, permissions, restricting who can edit or see data, or when saves fail with "You are not allowed to perform this action".
- Reads credentials
In this repository20 other files it gives its agents.
- AGENTS.mdAGENTS.md
- agent-guardrailsSkill
- creative-frontendSkill
- figma-handoffSkill
- payload-admin-brandingSkill
- payload-bookings-paymentsSkill
- payload-bootstrapSkill
- payload-deploy-vercelSkill
- payload-forms-crmSkill
- payload-integrationsSkill
- payload-legal-trustSkill
- payload-live-previewSkill
- payload-localizationSkill
- payload-mcpSkill
- payload-mediaSkill
- payload-performanceSkill
- payload-project-kickoffSkill
- payload-seo-geoSkill
- payload-testingSkill
- project-architectureSkill
The file
We split this skill into the rules it gives an agent
5 rules. About 0 are common, 1 is distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 13
Default roles. Adjust in PROJECT.md before coding.
- Very specific: line 63
Keep the template's authenticated, authenticatedOrPublished, and anyone helpers.
- Very specific: line 128
Run pnpm generate:types so User['role'] becomes a typed union.
- Very specific: line 132
Every collection and global declares all of create, read, update, delete explicitly.
- Distinctive: line 153
Never share one login between people.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Payload auth and RBAC
Step 1: Define roles
Default roles. Adjust in PROJECT.md before coding.
| Role | Can do |
admin | Everything, including users, settings, and technical collections |
editor | Pages, posts, legal pages, media, header, footer, SEO settings |
sales | Leads and bookings: read and update status and notes; read services |
Access matrix:
| Collection or global | admin | editor | sales | public |
users | CRUD | read and update self | read and update self | none |
pages, posts, legal-pages, categories | CRUD | CRUD | read | read published |
media | CRUD | CRUD | read | read |
services | CRUD | CRUD | read | read published |
leads | CRUD | none | read, update | create (through server action only) |
bookings | CRUD | none | read, update | none (server code creates them) |
payment-events | read | none | none | none |
header, footer, site-settings, consent-settings | update | update | read | read |
booking-settings | update | none | read | read (through server code) |
Step 2: Access helpers
src/access/hasRole.ts:
import type { Access, FieldAccess } from 'payload'
import type { User } from '@/payload-types'
export type Role = User['role']
export const hasRole =
(...roles: Role[]): Access =>
({ req: { user } }) =>
Boolean(user && roles.includes(user.role))
export const hasRoleField =
(...roles: Role[]): FieldAccess =>
({ req: { user } }) =>
Boolean(user && roles.includes(user.role))
export const adminOrSelf: Access = ({ req: { user } }) => {
if (!user) return false
if (user.role === 'admin') return true
return { id: { equals: user.id } }
}Keep the template's authenticated, authenticatedOrPublished, and anyone helpers. Use hasRole for everything role-specific.
Step 3: Users collection
src/collections/Users/index.ts:
import type { CollectionBeforeChangeHook, CollectionConfig } from 'payload'
import { adminOrSelf, hasRole, hasRoleField } from '@/access/hasRole'
import type { User } from '@/payload-types'
const firstUserIsAdmin: CollectionBeforeChangeHook<User> = async ({ data, operation, req }) => {
if (operation !== 'create') return data
const { totalDocs } = await req.payload.count({ collection: 'users', req })
return totalDocs === 0 ? { ...data, role: 'admin' } : data
}
export const Users: CollectionConfig<'users'> = {
slug: 'users',
auth: {
tokenExpiration: 60 * 60 * 8,
maxLoginAttempts: 5,
lockTime: 10 * 60 * 1000,
},
admin: {
group: 'Settings',
useAsTitle: 'name',
defaultColumns: ['name', 'email', 'role', 'updatedAt'],
},
access: {
admin: ({ req: { user } }) => Boolean(user),
create: hasRole('admin'),
read: adminOrSelf,
update: adminOrSelf,
delete: hasRole('admin'),
},
hooks: {
beforeChange: [firstUserIsAdmin],
},
fields: [
{ name: 'name', type: 'text', required: true },
{
name: 'role',
type: 'select',
required: true,
defaultValue: 'editor',
saveToJWT: true,
options: [
{ label: 'Admin', value: 'admin' },
{ label: 'Editor', value: 'editor' },
{ label: 'Sales', value: 'sales' },
],
access: {
create: hasRoleField('admin'),
update: hasRoleField('admin'),
},
},
],
}saveToJWT: trueputs the role in the token, so access checks do not query the database.- Field-level access on
roleprevents editors from promoting themselves. - The first-user registration screen bypasses collection access, and the hook makes that user an admin.
- Run
pnpm generate:typessoUser['role']becomes a typed union.
Step 4: Apply access to every collection
- Every collection and global declares all of
create,read,update,deleteexplicitly. Never rely on defaults. - Public forms never get
create: anyoneon a collection when a server action can create the document with the Local API. Keepcreaterestricted and let the server action write after validation. - Hide technical collections from the sidebar for non-admins:
admin: { hidden: ({ user }) => user?.role !== 'admin' }. - In server code that runs for a visitor or a logged-in user, pass
overrideAccess: falseanduserto the Local API.
Step 5: Request security
In src/payload.config.ts:
serverURL: process.env.NEXT_PUBLIC_SERVER_URL || '',
cors: [process.env.NEXT_PUBLIC_SERVER_URL || ''].filter(Boolean),
csrf: [process.env.NEXT_PUBLIC_SERVER_URL || ''].filter(Boolean),csrf must list every origin that sends authenticated cookie requests. A missing production origin makes admin saves fail with 403 after deploy while working locally.
Step 6: Inviting admins
- An admin creates the user with a temporary password and the right role.
- With an email adapter configured (
payload-integrations), the new user can use "Forgot password" to set their own password. - Never share one login between people; each admin gets a user so changes are traceable.
Diagnosis
| Symptom | Cause | Fix |
| "You are not allowed to perform this action" on save | Collection update access denies the role | Check the matrix and the helper used |
| Field silently not saved | Field-level update access returns false | Check field access |
| Saves work locally, 403 in production | Production origin missing from csrf or wrong serverURL | Step 5 |
| Editor can see other users' emails | read on users not restricted | Use adminOrSelf |
Done when
- Roles and matrix recorded in
PROJECT.md - First registered user is
admin; later users default toeditor - An editor cannot change their own role (verified by trying it in the admin)
- Every collection and global declares all access functions
csrf,cors, andserverURLinclude the production origin
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

