All files / libs/kernel/auth/core/src/lib/guards policies.guard.ts

0% Statements 0/40
0% Branches 0/1
0% Functions 0/1
0% Lines 0/40

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41                                                                                 
import { Injectable, type CanActivate, type ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { type Request } from 'express';

import { assert } from '@amalia/ext/typescript';
import { defineAbilityFor } from '@amalia/kernel/auth/shared';

import { allOf, CHECK_POLICIES_KEY, type PolicyHandler } from '../decorators';
import { UnauthenticatedUserError } from '../errors';

@Injectable()
export class PoliciesGuard implements CanActivate {
  public constructor(private readonly reflector: Reflector) {}

  public canActivate(context: ExecutionContext): boolean {
    const user = this.getUserFromRequest(context);
    const policyHandlers = this.getPolicyHandlers(context);
    const { params, body } = context.switchToHttp().getRequest<Omit<Request, 'body'> & { body: unknown }>();

    const ability = defineAbilityFor(user);

    return allOf(...policyHandlers)(ability, { user, params, body });
  }

  private getPolicyHandlers(context: ExecutionContext): PolicyHandler[] {
    const classPolicies = this.reflector.get<PolicyHandler[] | undefined>(CHECK_POLICIES_KEY, context.getClass()) ?? [];
    const handlerPolicies =
      this.reflector.get<PolicyHandler[] | undefined>(CHECK_POLICIES_KEY, context.getHandler()) ?? [];

    return [...classPolicies, ...handlerPolicies];
  }

  private getUserFromRequest(context: ExecutionContext) {
    const { user } = context.switchToHttp().getRequest<Request>();

    assert(user, new UnauthenticatedUserError());

    return user;
  }
}