All files / apps/api-gateway/src/auth auth.decorators.ts

100% Statements 11/11
100% Branches 0/0
100% Functions 3/3
100% Lines 8/8

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 3310x                               10x 10x     10x       10x 6x   10x   1x      
import {
  createParamDecorator,
  CustomDecorator,
  ExecutionContext,
  SetMetadata,
} from '@nestjs/common';
import type { Request } from 'express';
 
export type UserRole = 'tenant' | 'manager' | 'technician';
 
export interface AuthenticatedUser {
  /** The user's email — doubles as the JWT subject. */
  sub: string;
  role: UserRole;
}
 
export const IS_PUBLIC_KEY = 'isPublic';
export const ROLES_KEY = 'roles';
 
/** Opts a route out of authentication (health probes, login itself). */
export const Public = (): CustomDecorator => SetMetadata(IS_PUBLIC_KEY, true);
 
/** Restricts a route to the given roles; without it, any authenticated
 * user passes — authentication is the default, authorization is opt-in. */
export const Roles = (...roles: UserRole[]): CustomDecorator =>
  SetMetadata(ROLES_KEY, roles);
 
export const CurrentUser = createParamDecorator(
  (_data: unknown, context: ExecutionContext): AuthenticatedUser | undefined =>
    context.switchToHttp().getRequest<Request & { user?: AuthenticatedUser }>()
      .user,
);