Files
canina/backend/src/common/guards/roles.guard.ts
T
devops ddbf1ca026
Deploy Canina / deploy (push) Successful in 4m1s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 7s
test: comprehensive test suites and quality gates pass across backend, storefront and admin
- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation.
- Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings.
- Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors.
- Fixed unmount lifecycle guards, promise error handling, and component edge cases.
2026-10-13 16:01:00 +00:00

73 lines
2.0 KiB
TypeScript

import {
Injectable,
CanActivate,
ExecutionContext,
ForbiddenException,
} from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { ROLES_KEY } from "../decorators/roles.decorator";
interface RequestWithUser {
user?: {
role?: string;
isApiKey?: boolean;
scopes?: string[];
};
}
@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 request = context.switchToHttp().getRequest<RequestWithUser>();
const user = request.user;
if (!user || !user.role) {
throw new ForbiddenException("شما دسترسی لازم برای این بخش را ندارید");
}
// If request originates from an API key, verify it has admin scope for admin-guarded routes
if (user.isApiKey) {
const scopes = Array.isArray(user.scopes) ? user.scopes : [];
const hasAdminScope = scopes.includes("admin");
if (!hasAdminScope) {
throw new ForbiddenException(
"کلید API ارائه‌شده فاقد اسکوپ مدیریتی لازم برای این عملیات است",
);
}
}
const normalizeRole = (r: string) => r.toLowerCase().replace(/[_-]/g, "");
const userRoleNorm = normalizeRole(user.role);
const hasRole = requiredRoles.some((r) => {
const requiredNorm = normalizeRole(r);
// Direct normalized match
if (requiredNorm === userRoleNorm) return true;
// Superadmin satisfies admin
if (
(userRoleNorm === "superadmin" || userRoleNorm === "adminsuper") &&
requiredNorm === "admin"
) {
return true;
}
return false;
});
if (!hasRole) {
throw new ForbiddenException("سطح دسترسی شما کافی نیست");
}
return true;
}
}