Skip to content

defineRoles

defineRoles<Name>(definitions, options?): object

Defined in: packages/schema/src/access/roles.ts:48

Defines roles as bundles of capability strings. Pass the resource and area names as the type parameter to reject unknown names at compile time: defineRoles<'orders' | 'costs'>({ sales: ['orders.read.own'] }).

An entry may limit capabilities to fields (an allowlist) and rows (an AIP-160 filter): { 'products.read': ['sku', 'price'] }, { 'products.read': { fields: ['name'], filter: 'published = true' } }. The role anonymous, when defined, is what requests without a token act as; it may only read listed fields, and create listed fields through a public form. See Access.

Name extends string = string

Record<string, readonly RoleEntry<Name>[]>

RolesOptions = {}

can: (capability) => Rule

A rule that allows when the user’s roles grant the capability: true for an unscoped grant, a row filter for .own, .team and a limit’s filter, false otherwise. Refuses a wildcard. On a resource with .explicitGrants(), a role’s wildcard over resources such as *.read grants nothing.

ExactCapability<Name>

Rule

definitions: Record<string, readonly RoleEntry<Name>[]>

The roles as defined, by name.

fields: (user, capability, model?) => readonly string[] | undefined

The fields the user’s roles allow for a capability: the union of their lists, or undefined when a role grants it without a list (every field) or none grants it. With the resource’s model, as can has it, wildcards over resources count only where the resource takes them.

AccessUser

string

ResourceModel

readonly string[] | undefined

grants: (user, capability) => Set<Grant>

Scopes granted by the user’s roles for a capability, without applying them.

AccessUser

string

Set<Grant>

has: (user, capability) => boolean

Whether the user holds the capability at all, in any scope. For areas and field rules. Refuses a wildcard.

AccessUser

ExactCapability<Name>

boolean

holds: (user, capability, model?) => boolean

Whether one of the user’s roles grants all of the capability, wildcards included, in every row and field: * and vms.* hold vms.*, while vms.read, vms.update.own or a limited vms.update do not. For gates such as API functions. With a resource’s model, a wildcard over resources counts only where the resource takes it.

AccessUser

Capability<Name>

Pick<ResourceModel, "explicitGrants">

boolean

is: (…roles) => Rule

A rule that allows when the user has any of the roles.

…string[]

Rule

limits: RoleLimit[]

The capabilities limited to fields or rows, by role.

const roles = defineRoles<'orders' | 'products'>({
admin: ['*'],
sales: ['orders.read.own', 'orders.create', 'products.read'],
reseller: [{ 'products.read': { fields: ['sku', 'name', 'price'], filter: 'published = true' } }],
})