All files / apps/api-gateway/src/auth jwt-auth.guard.ts

100% Statements 25/25
100% Branches 20/20
100% Functions 2/2
100% Lines 22/22

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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 592x           2x 2x   2x 2x                   2x   7x 7x       8x       8x   7x           7x 2x     5x 5x 3x     2x 2x 1x 1x 1x   1x        
import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import type { Request } from 'express';
import { setCurrentUserId } from '@app/observability';
import { AuthenticatedUser, IS_PUBLIC_KEY } from './auth.decorators';
 
/**
 * Global authentication guard: every route requires a Bearer token unless
 * explicitly marked @Public(). On success the payload lands on request.user
 * (for the RolesGuard) and the user id enters the ALS request context, from
 * where the DownstreamClient propagates it — identity travels the same road
 * the correlation id already does.
 */
@Injectable()
export class JwtAuthGuard implements CanActivate {
  constructor(
    private readonly reflector: Reflector,
    private readonly jwt: JwtService,
  ) {}
 
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (isPublic) return true;
 
    const request = context
      .switchToHttp()
      .getRequest<Request & { user?: AuthenticatedUser }>();
 
    // Prometheus scrapes carry no JWT; the metrics route comes from the
    // shared observability lib, out of reach of the @Public() decorator.
    if (request.path === '/metrics' || request.path === '/api/metrics') {
      return true;
    }
 
    const [scheme, token] = request.headers.authorization?.split(' ') ?? [];
    if (scheme !== 'Bearer' || !token) {
      throw new UnauthorizedException('missing bearer token');
    }
 
    try {
      const payload = await this.jwt.verifyAsync<AuthenticatedUser>(token);
      request.user = payload;
      setCurrentUserId(payload.sub);
      return true;
    } catch {
      throw new UnauthorizedException('invalid or expired token');
    }
  }
}