Files
ipal-kit/src/modules/access/rolesField.ts
T

53 lines
1.8 KiB
TypeScript

import type { Field } from 'payload'
import type { Role } from './types.js'
import { isAdmin } from './predicates.js'
import { ROLE_HIERARCHY } from './types.js'
/**
* Builds the fixed `roles` field the plugin injects into the auth collection.
*
* Saved to the JWT so role checks avoid a database lookup. Only admins can
* set or change roles, preventing privilege escalation by lower-privilege
* users — including on create, so an open sign-up can't post roles: ['admin'].
* A non-admin's new account gets `defaultRole`. The first-user screen and
* Local API calls (seed scripts) run with overrideAccess, so they can still
* create the first admin.
*
* The very first account of the collection always becomes admin: the
* first-user screen may not show this field, and a site whose only account is
* a plain 'user' has nobody who can manage users, integrations or roles.
*/
export function buildRolesField(defaultRole: Role = 'user'): Field {
return {
name: 'roles',
type: 'select',
access: {
// Only admins may assign or change roles
create: ({ req: { user } }) => isAdmin(user),
update: ({ req: { user } }) => isAdmin(user),
},
admin: {
description: 'Role hierarchy: admin > editor > user.',
},
defaultValue: [defaultRole],
hasMany: true,
hooks: {
beforeChange: [
async ({ collection, operation, req, value }) => {
if (operation !== 'create' || !collection) {return value}
const { totalDocs } = await req.payload.count({ collection: collection.slug, overrideAccess: true, req })
return totalDocs === 0 ? ['admin'] : value
},
],
},
options: ROLE_HIERARCHY.map((role) => ({
label: role.charAt(0).toUpperCase() + role.slice(1),
value: role,
})),
required: true,
saveToJWT: true,
}
}