canina/backend/src/auth/roles.guard.ts
parsa aghaei 62bd8811fa
All checks were successful
Deploy Canina / deploy (push) Successful in 4m58s
style: apply standard ESLint & Prettier formatting across backend
2026-07-29 15:41:53 +03:30

37 lines
979 B
TypeScript

import {
Injectable,
CanActivate,
ExecutionContext,
ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from './roles.decorator';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<string[]>(
ROLES_KEY,
[context.getHandler(), context.getClass()],
);
if (!requiredRoles || requiredRoles.length === 0) {
return true;
}
const { user } = context.switchToHttp().getRequest();
if (!user || !user.role) {
throw new ForbiddenException('شما دسترسی لازم برای این بخش را ندارید');
}
const hasRole = requiredRoles.includes(user.role);
if (!hasRole) {
throw new ForbiddenException('سطح دسترسی شما کافی نیست');
}
return true;
}
}