|
| 1 | +import { |
| 2 | + CanActivate, |
| 3 | + ExecutionContext, |
| 4 | + Injectable, |
| 5 | + UnauthorizedException, |
| 6 | +} from '@nestjs/common'; |
| 7 | +import { AuthenticatedRequest } from './types'; |
| 8 | + |
| 9 | +@Injectable() |
| 10 | +export class RoleValidator implements CanActivate { |
| 11 | + private readonly unauthenticatedErrorMessage: string; |
| 12 | + private readonly noRolesSpecifiedErrorMessage: string; |
| 13 | + private readonly accessDeniedErrorMessage: string; |
| 14 | + private readonly allowedRoles: string[] | null; |
| 15 | + |
| 16 | + constructor(allowedRoles: string[] | null) { |
| 17 | + this.allowedRoles = allowedRoles; |
| 18 | + |
| 19 | + this.unauthenticatedErrorMessage = |
| 20 | + 'Role-based authorization requires user authentication (JWT token)'; |
| 21 | + this.noRolesSpecifiedErrorMessage = 'No roles specified for authorization'; |
| 22 | + this.accessDeniedErrorMessage = |
| 23 | + 'Access denied. User does not have the required roles: {allowedRoles}, user has roles: {userRoles}'; |
| 24 | + } |
| 25 | + |
| 26 | + async canActivate(context: ExecutionContext): Promise<boolean> { |
| 27 | + const request = context.switchToHttp().getRequest<AuthenticatedRequest>(); |
| 28 | + |
| 29 | + const { userRoles, userId, organizationId, authType, isApiKey } = request; |
| 30 | + |
| 31 | + if (!this.allowedRoles || this.allowedRoles.length === 0) { |
| 32 | + throw new UnauthorizedException(this.noRolesSpecifiedErrorMessage); |
| 33 | + } |
| 34 | + |
| 35 | + // API keys are organization-scoped and not tied to a specific user/member. |
| 36 | + // They are allowed through role-protected endpoints. |
| 37 | + if (isApiKey || authType === 'api-key') { |
| 38 | + if (!organizationId) { |
| 39 | + throw new UnauthorizedException( |
| 40 | + 'Organization context required for API key authentication', |
| 41 | + ); |
| 42 | + } |
| 43 | + |
| 44 | + return true; |
| 45 | + } |
| 46 | + |
| 47 | + // JWT requests must have user context + roles for role-based authorization |
| 48 | + if (!userId || !organizationId || !userRoles || userRoles.length === 0) { |
| 49 | + throw new UnauthorizedException(this.unauthenticatedErrorMessage); |
| 50 | + } |
| 51 | + |
| 52 | + const hasRequiredRoles = this.allowedRoles.some((role) => |
| 53 | + userRoles.includes(role), |
| 54 | + ); |
| 55 | + |
| 56 | + if (!hasRequiredRoles) { |
| 57 | + throw new UnauthorizedException( |
| 58 | + this.accessDeniedErrorMessage |
| 59 | + .replace('{allowedRoles}', this.allowedRoles.join(', ')) |
| 60 | + .replace('{userRoles}', userRoles.join(', ')), |
| 61 | + ); |
| 62 | + } |
| 63 | + |
| 64 | + return true; |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +export const RequireRoles = (...roles: string[]) => new RoleValidator(roles); |
0 commit comments