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

95.45% Statements 42/44
77.77% Branches 7/9
100% Functions 2/2
95.45% Lines 42/44

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 42 43 44 451x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x     5x 5x 5x 5x 5x 5x 5x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x  
import { ForbiddenException, Injectable, Logger, type ExecutionContext } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
 
import { assert, toError } from '@amalia/ext/typescript';
import { type AuthenticatedContext } from '@amalia/kernel/auth/types';
import { CompanyStatus } from '@amalia/tenants/companies/types';
 
import { DeactivatedAccountError, DeactivatedCompanyError } from '../errors';
 
@Injectable()
export class AmaliaAuthGuard extends AuthGuard('jwt') {
  private readonly logger = new Logger(AmaliaAuthGuard.name);
 
  public override handleRequest<TAuthenticatedContext extends AuthenticatedContext>(
    err: unknown,
    authenticatedContext: TAuthenticatedContext,
    info: unknown,
    context: ExecutionContext,
  ) {
    super.handleRequest(err, authenticatedContext, info, context);
 
    if (err) {
      throw toError(err);
    }
 
    assert(authenticatedContext, new ForbiddenException());
 
    const { user, meta } = authenticatedContext;
 
    // If we can't find the user or his account has been deactivated.
    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- make extra sure the user is in a company.
    assert(user.email && user.company && !user.clearedAt, new DeactivatedAccountError());
 
    if (!meta?.amaliaImpersonatorEmail && user.company.status !== CompanyStatus.ACTIVE) {
      this.logger.warn({
        message: `User ${user.email} tried to connect to deactivated company ${user.company.name}`,
        user,
      });
      throw new DeactivatedCompanyError(user.company.name);
    }
 
    return authenticatedContext;
  }
}