Aviary

Resource resolution

byId(Resource) loads the record the official @Can passes to your ability — the default IdParamResourceResolver, a custom ORM-backed ResourceResolver, authorizedResource, and resourceLoaders for the can-endpoint.

An instance ability (update(user, post)) needs the record, but a route only has an :id. The official @Can() takes an argument resolver for exactly this; byId is ours:

@Patch(':id')
@Can(PostPolicy, 'update', byId(Post))
update(@Req() req: Request) {
  const post = authorizedResource(req, Post); // the record byId loaded, no second query
}

byId(Resource, { param? }):

  1. asks the registered ResourceResolver for the Resource named by the route param (id, or param);
  2. refuses the call with a 403 when nothing is found, before the policy runs;
  3. keeps the record on the request, for authorizedResource(req, Resource) (which also accepts the ExecutionContext).

Class-level abilities take no resolver at all: @Can(PostPolicy, 'create').

The ResourceResolver interface

import type { ExecutionContext, Type } from '@nestjs/common';

interface ResourceResolver {
  resolve(
    resource: Type<unknown>,
    ctx: ExecutionContext,
    hints?: { param?: string },
  ): Promise<object | undefined> | object | undefined;
}

Return the record, or undefined / null for "not found" (a 403: existence is not leaked to callers who may not see it).

The default: IdParamResourceResolver

AuthzModule.forRoot() registers an IdParamResourceResolver under RESOURCE_RESOLVER. It reads the route param and builds an object whose prototype is the resource class with only id set:

// PATCH /posts/42 → Object.create(Post.prototype) with id = '42'

Enough for id comparisons, not for policies that read other columns. idParam renames the param for the whole app; byId(Post, { param: 'postId' }) for one route.

The default record has only an id. Register a real resolver when your policies read authorId, published or any other field.

A custom, ORM-backed resolver

import { Injectable, type ExecutionContext, type Type } from '@nestjs/common';
import type { ResourceResolver } from '@dudousxd/nestjs-authz';
import { EntityManager } from '@mikro-orm/core';

@Injectable()
export class OrmResourceResolver implements ResourceResolver {
  constructor(private readonly em: EntityManager) {}

  async resolve(resource: Type<unknown>, ctx: ExecutionContext, hints?: { param?: string }) {
    const req = ctx.switchToHttp().getRequest<{ params: Record<string, string> }>();
    const id = req.params[hints?.param ?? 'id'];
    if (id === undefined) return undefined;
    return (await this.em.findOne(resource as never, { id })) ?? undefined;
  }
}

Register it either way:

AuthzModule.forRoot({ resourceResolver: new OrmResourceResolver(em) });
// or, so Nest injects its dependencies:
{ provide: RESOURCE_RESOLVER, useClass: OrmResourceResolver }

One resolver serves every byId(...); branch on resource when entities load differently.

resourceLoaders for the can-endpoint

The opt-in POST /authz/can endpoint receives { type, id } from the client, not a request with route params. Give it loaders keyed by the type name, and it authorizes the real record:

AuthzModule.forRoot({
  canEndpoint: true,
  resourceLoaders: { Post: (id) => posts.findOne(id) }, // nullish → { allowed: false }
});

Without a loader for a type, only class-level abilities and ad-hoc gates resolve. An adapter may also bind the RESOURCE_HYDRATOR token to register loaders. See Enforcement.

Next steps

On this page