32 lines
932 B
TypeScript
32 lines
932 B
TypeScript
import {
|
|||
|
|
CanActivate,
|
||
|
|
ExecutionContext,
|
||
|
|
ForbiddenException,
|
||
|
|
Injectable,
|
||
|
|
} from '@nestjs/common';
|
||
|
|
import { Reflector } from '@nestjs/core';
|
||
|
|
import type { UserRole } from '@mento/shared';
|
||
|
|
import { ROLES_KEY } from './roles.decorator';
|
||
|
|
|
||
|
|
@Injectable()
|
||
|
|
export class RolesGuard implements CanActivate {
|
||
|
|
constructor(private readonly reflector: Reflector) {}
|
||
|
|
|
||
|
|
canActivate(context: ExecutionContext): boolean {
|
||
|
|
const roles = this.reflector.getAllAndOverride<UserRole[]>(ROLES_KEY, [
|
||
|
|
context.getHandler(),
|
||
|
|
context.getClass(),
|
||
|
|
]);
|
||
|
|
if (!roles?.length) return true;
|
||
|
|
|
||
|
|
const request = context.switchToHttp().getRequest<{
|
||
|
|
user?: { role?: string };
|
||
|
|
}>();
|
||
|
|
const role = request.user?.role as UserRole | undefined;
|
||
|
|
if (!role || !roles.includes(role)) {
|
||
|
|
throw new ForbiddenException('دسترسی به این بخش برای نقش شما مجاز نیست');
|
||
|
|
}
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
}
|