Author
elliot-profile-pic
Elliot Denolf
Published On

Build Your Own Role-Based Access Control in Payload

Author
elliot-profile-pic
Elliot Denolf
Published On
Build Your Own Role-Based Access Control in Payload
Build Your Own Role-Based Access Control in Payload

Payload comes with open-ended access control. You can define whatever type of pattern that you can dream up, and best of all—it's all done with simple JavaScript.

A common pattern is Role-Based Access Control. Here, we'll walk you through how to create your own RBAC pattern on both the collection-level and field-level.

In more detail, here are the pieces that we will be building:

  • Users collection with role field
  • Orders collection

Initialize Project

We'll be using create-payload-app to build out the initial project.

  1. Run npx create-payload-app payload-rbac
  2. Select javascript for language
  3. Select blank for our template
  4. Follow all other prompts

This will give us a simple project with a Payload config and Users collection. The structure of the project will be:

1
├─ payload.config.js
2
└─ collections/
3
└─ Users.js
4
└─ Orders.js

Modify Users Collection

First, we will add the role field to our Users collection with 2 options: admin and user.

1
const Users = {
2
slug: 'users',
3
auth: true,
4
admin: {
5
useAsTitle: 'email',
6
},
7
fields: [
8
{
9
name: 'role',
10
type: 'select',
11
options: [
12
{ label: 'Admin', value: 'admin' },
13
{ label: 'User', value: 'user' },
14
],
15
required: true,
16
defaultValue: 'user',
17
},
18
],
19
};
20
21
export default Users;

Create Orders Collection

Next, we will create a new Orders.js collection in our collections/ directory and scaffold out basic fields and values - including the createdBy relationship to the user.

1
const Orders = {
2
slug: 'orders',
3
fields: [
4
{
5
name: 'items',
6
type: 'array',
7
fields: [
8
{
9
name: 'item',
10
type: 'text',
11
}
12
]
13
},
14
{
15
name: 'createdBy',
16
type: 'relationship',
17
relationTo: 'users',
18
access: {
19
update: () => false,
20
},
21
admin: {
22
readOnly: true,
23
position: 'sidebar',
24
condition: data => Boolean(data?.createdBy)
25
},
26
},
27
]
28
}
29
30
export default Orders;

The Orders collection has an array field for items and a createdBy field which is a relationship to our Users collection. The createdBy field will feature a strict update access control function so that it can never be changed.

Notice we also have a condition function under the createdBy field's access. This will hide createdBy until it has a value.

Set the createdBy Attribute Using a Hook

Next, we'll add a hook that will run before any order is created. This is done by adding a beforeChange hook to our collection definition.

1
const Orders = {
2
slug: 'orders',
3
fields: [
4
// Collapsed
5
],
6
hooks: {
7
beforeChange: [
8
({ req, operation, data }) => {
9
if (operation === 'create') {
10
if (req.user) {
11
data.createdBy = req.user.id;
12
return data;
13
}
14
}
15
},
16
],
17
},
18
}

The logic in this hook sets the createdBy field to be the current user's id value, only if it is on a create operation. This will create a relationship between an order and the user who created it.

Access Control

Next, the access control for the collection can be defined. Payload's access control is based on functions. An access control function returns either a boolean value to allow/disallow access or it returns a query constraint that filters the data.

We want our function to handle a few scenarios:

  1. A user has the 'admin' role - access all orders
  2. A user created the order - allow access to only those orders
  3. Any other user - disallow access
1
const isAdminOrCreatedBy = ({ req: { user } }) => {
2
// Scenario #1 - Check if user has the 'admin' role
3
if (user && user.role === 'admin') {
4
return true;
5
}
6
7
// Scenario #2 - Allow only documents with the current user set to the 'createdBy' field
8
if (user) {
9
10
// Will return access for only documents that were created by the current user
11
return {
12
createdBy: {
13
equals: user.id,
14
},
15
};
16
}
17
18
// Scenario #3 - Disallow all others
19
return false;
20
};

Once defined, this function is added to the access property of the collection definition:

1
const Orders = {
2
slug: 'orders',
3
fields: [
4
// Collapsed
5
],
6
access: {
7
read: isAdminOrCreatedBy,
8
update: isAdminOrCreatedBy,
9
delete: isAdminOrCreatedBy,
10
},
11
hooks: {
12
// Collapsed
13
},
14
}

With this function added to the readupdate, and delete access properties, the function will run whenever these operations are attempted on the collection.

Put It All Together

The last step is to add the collection to our payload.config.js

1
import { buildConfig } from 'payload/config';
2
import Orders from './collections/Orders';
3
import Users from './collections/Users';
4
5
export default buildConfig({
6
serverURL: 'http://localhost:3000',
7
admin: {
8
user: Users.slug,
9
},
10
collections: [
11
Users,
12
Orders,
13
],
14
});

Let's verify the functionality:

Start up the project by running npm run dev or yarn dev and navigate to http://localhost:3000/admin

Create your initial user with the admin role.

Payload CMS Create User Example

Create an Order with the admin user.

Payload CMS Create Order Example
Payload CMS Save order as Admin Example

Create an additional user with the user role by navigating to the Users collection, selecting Create New, entering an email/password, then saving.

Payload CMS Create Normal User Example
Payload CMS Create Normal User Example

Log out of your admin user by selecting the icon in the bottom left, then log in with the second user.

Payload CMS Cr

You'll notice if we go to the Orders collection, no Orders will be shown. This indicates that the access control is working properly.

Payload CMS Create Order Example
Payload CMS No Orders Shown Example

Create another Order. Note that the current user will be saved to Created By in the sidebar.

Payload CMS Create Order as Normal User

Navigate back to Orders list on the dashboard. There will only be the single order created by the current user.

View Single Order as Normal User

Log out, then back in with your admin user. You should be able to see the original Order as well as the Order created by the second user.

View All Orders As Admin

Field Level Access Control

With everything working at the collection level, we can carry the concepts further and see how they can be applied at the field level. Suppose we wanted to add a paymentID field only for Admin users. Create an isAdmin function that checks the role as we did earlier.

1
const isAdmin = ({ req: { user } }) => (user && user.role === 'admin');

Add a new field to Orders and set createread or update access calls to use the isAdmin function.

1
const Orders = {
2
slug: 'orders',
3
fields: [
4
// Collapsed
5
{
6
name: 'paymentId',
7
type: 'text',
8
access: {
9
create: isAdmin,
10
read: isAdmin,
11
update: isAdmin,
12
},
13
}
14
],
15
// Collapsed
16
}

The new paymentID field is not available to the users even on one's own Order. Field level access controls allow for greater granularity over document level access for Collections and Globals. This shows how easy it is to manage exact permissions throughout the admin UI, GraphQL and REST endpoints; it even works when querying relationships to keep data secure.

What Other Improvements Can Be Made?

Now that we have a basic example working. What are some ways that this could be improved?

  • Ideally, we'd want to use both the hook and the access control function across multiple collections in our application. Since it's just JavaScript, we can extract each of these functions into their own file for re-use.
  • Add additional roles, such as an editor role which allows reading and editing, but disallows creating. This all can be customized specifically to your needs.

Questions or Comments? Join us on GitHub Discussions

I hope you enjoyed the introduction to doing role-based access control with Payload!

Come join the Payload discussions on GitHub.

Further Reading