Querying subjects
Most checks start from a subject ("can this user edit articles?"). Sometimes you need the reverse: "which users are writers?" or "who may edit articles?". The engine has two methods for that, two for the opposite ("which of these users are not admins?"), plus hasExactRoles for strict role checks on one subject.
subjectsWithRole
Returns the ids of subjects of the given type that have any of the given roles.
rbac.subjectsWithRole(
subjectType: string,
roles: RoleName | Role | (RoleName | Role)[],
options?: { guard?: string; team?: TeamId },
): Promise<Id[]>await rbac.subjectsWithRole('user', 'writer') // ['1', '4']
await rbac.subjectsWithRole('user', ['writer', 'editor']) // writers OR editors
await rbac.subjectsWithRole('client', 'integration', { guard: 'api' })
await rbac.subjectsWithRole('user', 'admin', { team: 42 }) // admins in team 42subjectsWithPermission
Returns the ids of subjects of the given type that have any of the given permissions, either directly or through one of their roles.
rbac.subjectsWithPermission(
subjectType: string,
permissions: PermissionName | Permission | (PermissionName | Permission)[],
options?: { guard?: string; team?: TeamId; expandWildcards?: boolean },
): Promise<Id[]>await rbac.subjectsWithPermission('user', 'edit articles')
await rbac.subjectsWithPermission('user', ['edit articles', 'delete articles'])
await rbac.subjectsWithPermission('user', 'edit articles', { team: 42, guard: 'api' })Each id appears only once, even if a subject matches several roles or has the permission both directly and through a role.
Wildcards
With wildcard: true, pass expandWildcards: true to also return the subjects whose granted permission is a wildcard that covers the name, directly or through a role:
// Alice holds articles.edit, Bob has a role with articles.*, Carol holds *
await rbac.subjectsWithPermission('user', 'articles.edit') // [alice]
await rbac.subjectsWithPermission('user', 'articles.edit', { expandWildcards: true }) // [alice, bob, carol]- The engine loads the permission names of the guard, keeps the ones that imply a name you asked for (with the same rules as
can()), and then looks up the subjects that hold any of them. It uses the regular adapter methods, so every adapter supports it. - The names you pass don't have to exist as permissions, as with
hasPermissionTo()when wildcards are on. A name no stored permission covers returns[]. - Without
wildcard: truethe option has no effect: only exact rows match and unknown names throw. - The default stays
false, so existing calls return what they returned before.
subjectsWithoutRole and subjectsWithoutPermission
The opposite queries (spatie: User::withoutRole(), User::withoutPermission()). The engine only knows the subjects that have assignments, not your whole users table, so you pass the candidates in among, and it returns the ones that have none of the given roles or permissions:
rbac.subjectsWithoutRole(
subjectType: string,
roles: RoleName | Role | (RoleName | Role)[],
options: { among: Id[]; guard?: string; team?: TeamId },
): Promise<Id[]>
rbac.subjectsWithoutPermission(
subjectType: string,
permissions: PermissionName | Permission | (PermissionName | Permission)[],
options: { among: Id[]; guard?: string; team?: TeamId; expandWildcards?: boolean },
): Promise<Id[]>const page = await prisma.user.findMany({ take: 50 })
// The users on this page who are not admins
await rbac.subjectsWithoutRole('user', 'admin', { among: page.map((u) => u.id) })
// ... who may not publish, in team 42
await rbac.subjectsWithoutPermission('user', 'publish articles', { among: page.map((u) => u.id), team: 42 })- The result keeps the order of
among. Ids are compared as strings, so a numeric primary key matches the string ids SQL adapters store. - Same scope, options and errors as
subjectsWithRole/subjectsWithPermission. An expired assignment doesn't count, so its subject is returned. - For a query over the whole table (with pagination in the database), filter with
NOT INinstead:
const admins = await rbac.subjectsWithRole('user', 'admin')
const nonAdmins = await prisma.user.findMany({
where: { id: { notIn: admins.map(Number) } },
take: 50,
})Loading the records
All four methods return ids only. Load the records with your own ORM:
const ids = await rbac.subjectsWithRole('user', 'writer')
const writers = await prisma.user.findMany({
where: { id: { in: ids.map(Number) } }, // SQL adapters return ids as strings
})import { inArray } from 'drizzle-orm'
const ids = await rbac.subjectsWithPermission('user', 'edit articles')
const editors = await db
.select()
.from(users)
.where(inArray(users.id, ids.map(Number)))Id types
The Prisma and Drizzle adapters store subject_id as text, so they always return strings ('1'). MemoryAdapter returns ids in the form you stored them. Convert with Number(...) when your primary key is numeric. UUID keys need no conversion.
Scope: guard and team
- Guard. Only roles and permissions of the given guard (default:
defaultGuard) are considered. - Team. With teams enabled,
teamselects which assignments count. Only role and permission links made in that team match. A role name resolves the same way as everywhere else: a team-specific role wins over a global role with the same name. - Passing
teamwhenteamsis off throwsRbacErrorwith codeTEAMS_NOT_ENABLED.
// Users who hold the global 'admin' role inside team 42
await rbac.subjectsWithRole('user', 'admin', { team: 42 })
// Users who hold 'admin' with no team (global assignments)
await rbac.subjectsWithRole('user', 'admin')Errors
Unknown names throw, the same way assignments do:
| Situation | Error |
|---|---|
| A role name doesn't exist in that guard / team | RoleDoesNotExist |
| A permission name doesn't exist in that guard | PermissionDoesNotExist |
A Role / Permission object has another guard | GuardDoesNotMatch |
A Role object belongs to another team | RbacError (TEAM_DOES_NOT_MATCH) |
See Errors for the full list.
Caveats
Expired assignments are skipped
With temporary access, both queries leave out subjects whose role or direct permission expired, by the engine's clock, even before pruneExpired() deletes the rows. The filter runs in the database, as part of the same query.
Wildcards are expanded only on request
By default subjectsWithPermission matches stored permission rows, not wildcard patterns. A user who holds articles.* is not returned by subjectsWithPermission('user', 'articles.edit'), and the name you pass must exist as a permission, or the call throws PermissionDoesNotExist. Pass { expandWildcards: true } to include wildcard holders, see Wildcards.
Super-admins and before are not included
superAdminRoles and the before hook only affect can() and friends. These queries look only at stored data, so a super-admin appears in the results only if they actually hold the role or permission. To include them, query the super-admin role separately and merge the ids:
const ids = new Set([
...(await rbac.subjectsWithPermission('user', 'edit articles')),
...(await rbac.subjectsWithRole('user', 'super-admin')),
])hasExactRoles
On a single subject, hasExactRoles is true only when the subject holds all of the given roles and no other role in the current guard and team.
const user = rbac.for({ type: 'user', id: 1 })
await user.syncRoles('writer', 'editor')
await user.hasExactRoles('writer', 'editor') // true
await user.hasExactRoles(['writer', 'editor']) // true (array form)
await user.hasExactRoles('writer') // false: also has editor
await user.hasExactRoles('writer', 'editor', 'admin') // false: no adminCompare it with the other role checks:
| Method | True when the subject has... |
|---|---|
hasRole(a) / hasRole([a, b]) | a / any of a, b |
hasAnyRole(a, b) | any of them |
hasAllRoles(a, b) | all of them, others allowed |
hasExactRoles(a, b) | all of them and nothing else |
Role checks never throw for unknown names. They return false.
