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:
- the global
superAdmin(user, ability, resource)hook —trueallows; - the
DECISION_PROVIDER, when registered — allow or deny is final,undefinedabstains; - the policy linked to the resource that defines the ability (official evaluation: its
before(), then the ability); - the persisted permissions (RBAC), wildcards included;
- an ad-hoc gate registered with
define; - 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 orderA 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 adaptergate.scope(entity, ability = 'viewAny') resolves:
superAdmin(user, ability, entity)→ allow-all;- the
DECISION_PROVIDER'splanScope, when it does not abstain → used as is; - the policy's
before()true/false→ allow-all / deny-all; - a guest → deny-all;
- the policy's
scope(user, entity)(else itsabilitymethod).
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 / authorize | the same |
allowsMany(items) | the same |
scope(entity, ability?) | the same |
hasRole(role) / hasAnyRole(roles) | the same |
define, hasGate, gateNames | — |
Next steps
Policies
Official @nestjs/authorization policies, plus what this package adds — @PolicyFor, the AuthzPolicy base with superAdmin and the external engine, and PolicyIndex.
Enforcement
Routes are guarded by the official deny-by-default AuthorizationGuard. This page covers our helpers for the official @Can, the @Roles / @Permission sugar, the decision channel and the optional can-endpoint.