Aviary

Gates

The service-layer Gate over the official AuthorizationService — policy-class and string checks, ad-hoc gates with define, forUser and BoundGate, allowsMany, roles and query scopes.

The official AuthorizationService.can/authorize(Policy, ability, user, ...args) checks a policy from a service. The Gate wraps it and adds what it lacks: Laravel-style string abilities, ad-hoc gates, batches, roles, query scopes, an ambient user and the allow + deny decision event. Every policy decision is still the official service's.

Checking

import { Gate } from '@dudousxd/nestjs-authz';

constructor(private readonly gate: Gate) {}

const user = this.gate.forUser(currentUser);          // a BoundGate

await user.authorize(PostPolicy, 'update', post);     // exactly AuthorizationService.authorize
await user.allows(ReportPolicy, 'export', 'csv');     // any args, typed from the policy
await user.allows('update', post);                    // the policy linked to Post (@PolicyFor)
await user.allows('create', Post);                    // a class-level ability, by resource class
await user.allows('posts.publish');                   // a persisted permission
await user.denies('update', post);

authorize() throws the official AuthorizationError (401 for a guest, 403 otherwise; the official module maps it to the transport's error when it leaves a handler). Without forUser, gate.allows(...) uses the ambient user. forUser(null) is an explicit guest.

How a string ability resolves

gate.allows(ability, resource?) asks, in order:

  1. the global superAdmin(user, ability, resource) hook — true allows;
  2. the DECISION_PROVIDER, when registered — allow or deny is final, undefined abstains;
  3. the policy linked to the resource that defines the ability (official evaluation: its before(), then the ability);
  4. the persisted permissions (RBAC), wildcards included;
  5. an ad-hoc gate registered with define;
  6. otherwise AbilityNotResolvedException.

The policy has the final word

A persisted permission named like one of a policy's abilities (update) does not bypass the policy: gate.allows('update', post) is PostPolicy's to decide, whatever the user's permissions. Only superAdmin (and a DECISION_PROVIDER) come first. Permissions grant the named abilities no policy defines (posts.publish).

Ad-hoc gates

A model-less ability, for app-wide checks:

@Injectable()
export class AuthzGates implements OnModuleInit {
  constructor(private readonly gate: Gate) {}

  onModuleInit() {
    this.gate
      .define('access-admin', (user) => user.isStaff)
      .define('invite-teammates', async (user) => (await plans.of(user)).team);
  }
}

await this.gate.forUser(user).allows('access-admin');

A guest is denied before the function runs. On a route, use the built-in GatePolicy:

@Get('admin')
@Can(GatePolicy, 'allows', ability('access-admin'))
dashboard() {}

gate.hasGate(name) and gate.gateNames() list what is registered.

Batches

const results = await this.gate.forUser(user).allowsMany([
  { ability: 'update', resource: post },
  { policy: ReportPolicy, ability: 'export', args: ['csv'] },
]); // [{ ...item, allowed }], in order

A batch shares one permission fetch (and asks a DECISION_PROVIDER's decideMany once). An item that throws (an unknown ability) denies only itself.

Roles

await this.gate.hasRole('editor');
await this.gate.forUser(user).hasAnyRole(['admin', 'editor']);

A plain fact: superAdmin does not apply here (it does on RolePolicy).

Query scopes

const where = await this.gate.forUser(user).scope(Post);           // or scope(PostPolicy, 'viewAny')
await applyScope(qb, this.gate.forUser(user), Post);               // TypeORM adapter

gate.scope(entity, ability = 'viewAny') resolves:

  1. superAdmin(user, ability, entity) → allow-all;
  2. the DECISION_PROVIDER's planScope, when it does not abstain → used as is;
  3. the policy's before() true / false → allow-all / deny-all;
  4. a guest → deny-all;
  5. the policy's scope(user, entity) (else its ability method).

A persisted permission does not widen a policy's scope; it gives allow-all only when there is no policy method to ask.

Gate and BoundGate

Gate (ambient user)BoundGate (gate.forUser(user))
allows / denies / authorizethe same
allowsMany(items)the same
scope(entity, ability?)the same
hasRole(role) / hasAnyRole(roles)the same
define, hasGate, gateNames—

Next steps

On this page