import { CanActivate, ExecutionContext, ForbiddenException, Injectable, Type, UnauthorizedException, } from '@nestjs/common'; import { hasPassengerPermission, hasPassengerPermissionStrict, } from './passenger-permission.util'; export type PassengerPermissionGuardOptions = { /** * When true, super admins and org admins do NOT bypass the check — the * permission key must be explicitly granted to them like anyone else. */ strict?: boolean; }; export function PassengerPermissionGuard( permissions: string[], options: PassengerPermissionGuardOptions = {}, ): Type { const check = options.strict ? hasPassengerPermissionStrict : hasPassengerPermission; @Injectable() class PassengerPermissionsGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest<{ user?: any }>(); const user = request.user; if (!permissions?.length) return true; if (!user) throw new UnauthorizedException('Authentication required'); if (permissions.some((p) => check(user, p))) return true; throw new ForbiddenException( `Missing permission. Required one of: ${permissions.join(', ')}` + (options.strict ? ' (granted explicitly — admin role does not bypass)' : ''), ); } } return PassengerPermissionsGuard; }