import type { BasePayload, CollectionConfig, Config } from 'payload' import type { Role } from './types.js' import { hasMinimumRole } from './predicates.js' import { ROLE_HIERARCHY } from './types.js' /** * Who may open the admin panel. * * Payload lets every account of the login collection into the panel; what it sees there is * decided per collection. The lowest role (`user`) is the default for a new account and has * no business in the panel: by default the panel opens for `editor` and above * (`accounts.panelRole`). It is Payload's own `access.admin` on the login collection, so the * API is not touched — a `user` account still logs in over the API and gets what its role allows. * * The rule looks at the role only, not at the second factor: an editor who has typed the * password must still reach the 2FA screens, which are part of the panel. */ export const DEFAULT_PANEL_ROLE: Role = 'editor' /** `access.admin` for a staff collection: the account holds at least `minimum`. */ export const panelAccess = (minimum: Role = DEFAULT_PANEL_ROLE): NonNullable['admin']> => ({ req }) => hasMinimumRole(req.user, minimum, req.payload) /** `accounts.panelRole` → the role to require, or null when the rule is off (`false`, or the lowest role). */ export function resolvePanelRole(option: false | Role | undefined): null | Role { if (option === false) {return null} const role = option ?? DEFAULT_PANEL_ROLE if (!ROLE_HIERARCHY.includes(role)) { throw new Error(`[ipal] accounts.panelRole must be one of ${ROLE_HIERARCHY.join(', ')} or false, got ${JSON.stringify(option)}.`) } return role === ROLE_HIERARCHY[0] ? null : role } /** * Sets `access.admin` on the collection that carries the roles, unless the project wrote its * own (`access.admin` on its collection, or `access.authAccess.admin` for the injected one). */ export function applyPanelRole(config: Config, slug: string, minimum: Role): Config { return { ...config, collections: (config.collections ?? []).map((collection) => collection.slug === slug && !collection.access?.admin ? { ...collection, access: { ...collection.access, admin: panelAccess(minimum) } } : collection, ), } } /** * How many accounts of the collection are below the panel role (no role, or only lower ones), * and how many there are. For the start-up line that tells a site what the rule did to it. */ export async function countBelowPanelRole(payload: BasePayload, slug: string, minimum: Role): Promise<{ all: number; below: number }> { const allowed = ROLE_HIERARCHY.slice(ROLE_HIERARCHY.indexOf(minimum)) const all = (await payload.count({ collection: slug as never, overrideAccess: true })).totalDocs const able = (await payload.count({ collection: slug as never, overrideAccess: true, where: { roles: { in: [...allowed] } } as never })).totalDocs return { all, below: Math.max(0, all - able) } }