49 lines
1.1 KiB
TypeScript
49 lines
1.1 KiB
TypeScript
|
|
import {
|
||
|
|
Injectable,
|
||
|
|
CanActivate,
|
||
|
|
ExecutionContext,
|
||
|
|
ForbiddenException,
|
||
|
|
} from '@nestjs/common';
|
||
|
|
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',
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
const hasRole = requiredRoles.some((role) => user.role === role);
|
||
|
|
|
||
|
|
if (!hasRole) {
|
||
|
|
throw new ForbiddenException({
|
||
|
|
code: ERROR_CODES.INSUFFICIENT_PERMISSIONS,
|
||
|
|
message: 'You do not have permission to perform this action',
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
}
|