2026-02-08 18:44:05 -04:00
|
|
|
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
|
2026-02-07 10:23:29 -04:00
|
|
|
import { Reflector } from '@nestjs/core';
|
|
|
|
|
import { UserRole } from '../enums';
|
|
|
|
|
import { ERROR_CODES } from '../constants';
|
|
|
|
|
|
|
|
|
|
export const ROLES_KEY = 'roles';
|
|
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
|
export class RolesGuard implements CanActivate {
|
|
|
|
|
constructor(private reflector: Reflector) {}
|
|
|
|
|
|
|
|
|
|
canActivate(context: ExecutionContext): boolean {
|
|
|
|
|
const requiredRoles = this.reflector.getAllAndOverride<UserRole[]>(ROLES_KEY, [
|
|
|
|
|
context.getHandler(),
|
|
|
|
|
context.getClass(),
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
if (!requiredRoles) {
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const request = context.switchToHttp().getRequest();
|
|
|
|
|
const user = request.user;
|
|
|
|
|
|
|
|
|
|
if (!user || !user.role) {
|
|
|
|
|
throw new ForbiddenException({
|
|
|
|
|
code: ERROR_CODES.INSUFFICIENT_PERMISSIONS,
|
|
|
|
|
message: 'Access denied',
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-08 18:44:05 -04:00
|
|
|
// Map CITIZEN role to APPLICANT for backwards compatibility
|
|
|
|
|
const normalizedUserRole = user.role === 'CITIZEN' ? UserRole.APPLICANT : user.role;
|
|
|
|
|
const hasRole = requiredRoles.some(role => normalizedUserRole === role);
|
2026-02-07 10:23:29 -04:00
|
|
|
|
|
|
|
|
if (!hasRole) {
|
|
|
|
|
throw new ForbiddenException({
|
|
|
|
|
code: ERROR_CODES.INSUFFICIENT_PERMISSIONS,
|
|
|
|
|
message: 'You do not have permission to perform this action',
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
}
|