agentleFS
RamezHanyRamezHany/payload-cms-skills/skills/payload-auth-rbac/SKILL.md

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

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
  1. Very specific:

    Default roles. Adjust in PROJECT.md before coding.

    line 13
  2. Very specific:

    Keep the template's authenticated, authenticatedOrPublished, and anyone helpers.

    line 63
  3. Very specific:

    Run pnpm generate:types so User['role'] becomes a typed union.

    line 128
  4. Very specific:

    Every collection and global declares all of create, read, update, delete explicitly.

    line 132
  5. Distinctive:

    Never share one login between people.

    line 153

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Payload auth and RBAC

Step 1: Define roles

Default roles. Adjust in PROJECT.md before coding.

RoleCan do
adminEverything, including users, settings, and technical collections
editorPages, posts, legal pages, media, header, footer, SEO settings
salesLeads and bookings: read and update status and notes; read services

Access matrix:

Collection or globaladmineditorsalespublic
usersCRUDread and update selfread and update selfnone
pages, posts, legal-pages, categoriesCRUDCRUDreadread published
mediaCRUDCRUDreadread
servicesCRUDCRUDreadread published
leadsCRUDnoneread, updatecreate (through server action only)
bookingsCRUDnoneread, updatenone (server code creates them)
payment-eventsreadnonenonenone
header, footer, site-settings, consent-settingsupdateupdatereadread
booking-settingsupdatenonereadread (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: true puts the role in the token, so access checks do not query the database.
  • Field-level access on role prevents editors from promoting themselves.
  • The first-user registration screen bypasses collection access, and the hook makes that user an admin.
  • Run pnpm generate:types so User['role'] becomes a typed union.

Step 4: Apply access to every collection

  1. Every collection and global declares all of create, read, update, delete explicitly. Never rely on defaults.
  2. Public forms never get create: anyone on a collection when a server action can create the document with the Local API. Keep create restricted and let the server action write after validation.
  3. Hide technical collections from the sidebar for non-admins: admin: { hidden: ({ user }) => user?.role !== 'admin' }.
  4. In server code that runs for a visitor or a logged-in user, pass overrideAccess: false and user to 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

  1. An admin creates the user with a temporary password and the right role.
  2. With an email adapter configured (payload-integrations), the new user can use "Forgot password" to set their own password.
  3. Never share one login between people; each admin gets a user so changes are traceable.

Diagnosis

SymptomCauseFix
"You are not allowed to perform this action" on saveCollection update access denies the roleCheck the matrix and the helper used
Field silently not savedField-level update access returns falseCheck field access
Saves work locally, 403 in productionProduction origin missing from csrf or wrong serverURLStep 5
Editor can see other users' emailsread on users not restrictedUse adminOrSelf

Done when

  • Roles and matrix recorded in PROJECT.md
  • First registered user is admin; later users default to editor
  • An editor cannot change their own role (verified by trying it in the admin)
  • Every collection and global declares all access functions
  • csrf, cors, and serverURL include the production origin

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.