Skip to main content
zerotal

Documentation


Documentation / zerotal / auth / Roles

Function: Roles()

Roles<TBase>(Base): {(...args): (Anonymous class); withRoles: boolean; prototype: (Anonymous class)<any>; } & TBase

Defined in: packages/auth/src/rbac/Roles.ts:79

Model mixin adding DB-backed roles (and the permissions those roles carry).

Roles are a polymorphic many-to-many (model_roles); each role owns permissions (role_permissions). roles.permissions is eager-loaded on every query via the rolesEagerLoad global scope, so the read checks (hasRole, can) are synchronous and hit no database. Writes (assignRole, removeRole, syncRoles) are async and refresh the per-instance memo.

Type Parameters

TBase

TBase extends Constructor<object>

The model constructor being extended.

Parameters

Base

TBase

The base model (or another mixin) to compose onto.

Returns

A subclass of Base with the roles API mixed in.

Remarks

Compose Permissions alongside to also grant permissions directly to a model; can() then answers over the union of role-derived and direct permissions. Disable eager-loading with static withRoles = false (then call await user.loadAuthorization() before a synchronous check).

Example

import { BaseModelWith, Authenticatable } from "@zerotal/orm";
import { Roles } from "@zerotal/auth";

export class User extends BaseModelWith(Authenticatable, Roles) {}

const user = await User.find(1);
await user.assignRole("editor");   // async write
user.hasRole("editor");            // true — synchronous
user.can("post.publish");          // permission carried by the role