DEV Community

Aaron K Saunders
Aaron K Saunders

Posted on

2

Access Control in Payload CMS - A Quick Reference Guide

Quick overview, Cheat Sheet, for The access control functions following Payload CMS 3 structure, which allows defining rules for read, create, update, and delete operations using dynamic conditions.

Payload is the open-source, fullstack Next.js framework, giving you instant backend superpowers. Get a full TypeScript backend and admin panel instantly. Use Payload as a headless CMS or for building powerful applications.

TLDR

User Collection

import { CollectionConfig } from 'payload/types';

const Users: CollectionConfig = {
  slug: 'users', // The collection slug
  auth: true, // Enable authentication (login functionality)
  fields: [
    {
      name: 'email',
      type: 'email', // User email address
      required: true,
      unique: true, // Ensure that email addresses are unique
    },
    {
      name: 'password',
      type: 'password', // User password field
      required: true,
    },
    {
      name: 'role',
      type: 'select',
      options: ['admin', 'editor', 'author'], // Define the available roles
      defaultValue: 'author', // Default role is 'author'
      required: true,
    },
    {
      name: 'firstName',
      type: 'text', // User's first name
      required: true,
    },
    {
      name: 'lastName',
      type: 'text', // User's last name
      required: true,
    },
  ],
  access: {
    // Access control for reading users (admin only)
    read: ({ req }) => req.user?.role === 'admin',
    // Only admin can create a user
    create: ({ req }) => req.user?.role === 'admin',
    // Admins and the user themselves can update user details
    update: ({ req, doc }) => req.user?.role === 'admin' || req.user?.id === doc?.id,
    // Only admins can delete a user
    delete: ({ req }) => req.user?.role === 'admin',
  },
};

export default Users;
Enter fullscreen mode Exit fullscreen mode

Notes Collection

import { CollectionConfig } from 'payload/types';

const Notes: CollectionConfig = {
  slug: 'notes',
  fields: [
    {
      name: 'owner',
      type: 'relationship', // Links the note to a user (owner)
      relationTo: 'users',  // Relates to the 'users' collection
      required: true,       // Ensures every note has an owner
    },
  ],
  access: {
    /**
     * Read Access:
     * - Admins can read all notes.
     * - Editors can read all notes.
     * - Authors can only read their own notes.
     */
    read: ({ req, doc }) => {
      if (!req.user) return false; // If no user is logged in, deny access
      return (
        req.user.role === 'admin' || 
        req.user.role === 'editor' || 
        req.user.id === doc?.owner // Authors can only read their own notes
      );
    },

    /**
     * Create Access:
     * - Admins, Editors, and Authors can create notes.
     */
    create: ({ req }) => {
      return (
        req.user?.role === 'admin' || 
        req.user?.role === 'editor' || 
        req.user?.role === 'author'
      );
    },

    /**
     * Update Access:
     * - Admins can update all notes.
     * - Editors can update all notes.
     * - Authors can only update their own notes.
     */
    update: ({ req, doc }) => {
      if (!req.user) return false;
      return (
        req.user.role === 'admin' || 
        req.user.role === 'editor' || 
        req.user.id === doc?.owner // Authors can only update their own notes
      );
    },

    /**
     * Delete Access:
     * - Admins can delete all notes.
     * - Authors can delete their own notes.
     * - Editors CANNOT delete any notes.
     */
    delete: ({ req, doc }) => {
      if (!req.user) return false;
      return (
        req.user.role === 'admin' || 
        req.user.id === doc?.owner // Only the author of the note can delete it
      );
    },
  },
};

export default Notes;

Enter fullscreen mode Exit fullscreen mode

Access Control for Notes Collection in Payload CMS 3

Explanation

  • Admins: Have full control over all notes.
  • Editors: Can read and update all notes but cannot delete.
  • Authors: Can only access their own notes (read, create, update, and delete).
  • Guests (not logged in): Have no access.
Role Read Notes Create Notes Update Notes Delete Notes
Admin ✅ Can read all ✅ Can create ✅ Can update all ✅ Can delete all
Editor ✅ Can read all ✅ Can create ✅ Can update all ❌ Cannot delete
Author ✅ Can read own ✅ Can create ✅ Can update own ✅ Can delete own
Guest ❌ Cannot read ❌ Cannot create ❌ Cannot update ❌ Cannot delete

See more Payload CMS content on my Youtube Channel

CLICK HERE

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (2)

Collapse
 
gillesmastropasqua profile image
Gilles Mastropasqua

Hello, thanks for this. Do you think it's possible to manage access control dynamically ? With the conditions stored on a collection ?

Collapse
 
aaronksaunders profile image
Aaron K Saunders

possible, would need to see what other values are passed into the access function.

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay