finance-api/src/common/guards/roles.guard.ts
Заид Омар Медхат 33602d0fe9 chore: initialize NestJS project with Docker and environment configuration
Add project scaffolding and development infrastructure:
- Add environment configuration files (.env.development, .env.example) with database, JWT, security, AI integration, logging, and CORS settings
- Add .gitignore to exclude build artifacts, logs, IDE files, and environment variables
- Add .prettierrc with single quotes and trailing commas configuration
- Add multi-stage Dockerfile with development, build, and production stages
- Ad
2025-12-13 15:45:08 +05:00

35 lines
979 B
TypeScript

import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY, Role } from '../decorators/roles.decorator';
import { ErrorMessages } from '../constants/error-messages';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles) {
return true;
}
const { user } = context.switchToHttp().getRequest();
if (!user || !user.role) {
throw new ForbiddenException(ErrorMessages.ACCESS_DENIED);
}
const hasRole = requiredRoles.some((role) => user.role === role);
if (!hasRole) {
throw new ForbiddenException(ErrorMessages.ACCESS_DENIED);
}
return true;
}
}