Backend · Architecture & Multi-Tenancy· 8 min read
5-level hierarchical RBAC: role-aware DTOs and dynamic NestJS guards
Implementing 5-level hierarchical role-based access control. How custom decorators, permission bitmasks, and response DTO filtering prevent unauthorized actions and data leakage.
RBACAuthorizationNestJSSecurityDTOs
Simple role checks like `@Roles('ADMIN')` fail as soon as an enterprise platform scales. In our multi-tenant HRMS and consultancy ecosystem, access control operates across a 5-tier hierarchy: Super Admin (Platform Owner), Organization Admin, HR/Payroll Manager, Department Manager, and Employee. An HR Manager can view employee salaries but cannot configure company tax settings. A Department Manager can approve leaves for their direct reports but cannot view disciplinary notes.
The 5-tier permission hierarchy
| Role Level | Identifier | Scope of Authority | Inherited Permissions |
|---|---|---|---|
| Level 5 | SUPER_ADMIN | Global platform governance & cross-tenant support | All global & tenant permissions |
| Level 4 | ORG_ADMIN | Full organizational configuration & billing | Levels 1 through 3 within own tenant |
| Level 3 | HR_MANAGER | Workforce operations, payroll, PMS appraisals | Levels 1 & 2 within own tenant |
| Level 2 | DEPT_MANAGER | Direct report approvals, shift scheduling | Level 1 for assigned department |
| Level 1 | EMPLOYEE | Personal attendance, leave requests, own profile | Self-service data only |
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
export const RoleHierarchy: Record<string, number> = {
SUPER_ADMIN: 5,
ORG_ADMIN: 4,
HR_MANAGER: 3,
DEPT_MANAGER: 2,
EMPLOYEE: 1,
};
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRole = this.reflector.get<string>('minRole', context.getHandler());
if (!requiredRole) return true;
const request = context.switchToHttp().getRequest();
const userRole = request.user?.role;
if (!userRole || (RoleHierarchy[userRole] ?? 0) < RoleHierarchy[requiredRole]) {
throw new ForbiddenException('Insufficient role privileges for this operation');
}
return true;
}
}Role-aware DTO projection: never leak sensitive fields
Endpoint authorization is only half the battle. If a `GET /employees/:id` endpoint returns `bankAccountNumber`, `panNumber`, and `currentSalaryPence` to an ordinary peer employee, a severe data privacy violation occurs. We use role-aware serializer interceptors that sanitize outgoing JSON payloads based on the caller's role level.