Refactor PermissionsGuard to throw UnauthorizedException with detailed message

This commit is contained in:
faris Aljohari
2025-01-10 06:14:45 -06:00
parent 145ef32629
commit 56fba355fc

View File

@ -1,4 +1,8 @@
import { Injectable, ExecutionContext } from '@nestjs/common'; import {
Injectable,
ExecutionContext,
UnauthorizedException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport'; import { AuthGuard } from '@nestjs/passport';
import { Reflector } from '@nestjs/core'; import { Reflector } from '@nestjs/core';
import { RolePermissions } from '@app/common/constants/role-permissions'; import { RolePermissions } from '@app/common/constants/role-permissions';
@ -30,14 +34,34 @@ export class PermissionsGuard extends AuthGuard('jwt') {
const request = context.switchToHttp().getRequest(); const request = context.switchToHttp().getRequest();
const user = request.user; // User is now available after AuthGuard const user = request.user; // User is now available after AuthGuard
const userRole = user?.role.type as RoleType; const userRole = user?.role?.type as RoleType;
if (!userRole || !RolePermissions[userRole]) { if (!userRole || !RolePermissions[userRole]) {
return false; // Deny if role or permissions are missing throw new UnauthorizedException({
message: `Only ${this.getAllowedRoles(requiredPermissions)} role(s) can access this route.`,
});
} }
const userPermissions = RolePermissions[userRole]; const userPermissions = RolePermissions[userRole];
const hasRequiredPermissions = requiredPermissions.every((perm) =>
userPermissions.includes(perm),
);
// Check if the user has the required permissions if (!hasRequiredPermissions) {
return requiredPermissions.every((perm) => userPermissions.includes(perm)); throw new UnauthorizedException({
message: `Only ${this.getAllowedRoles(requiredPermissions)} role(s) can access this route.`,
});
}
return true;
}
private getAllowedRoles(requiredPermissions: string[]): string {
const allowedRoles = Object.entries(RolePermissions)
.filter(([, permissions]) =>
requiredPermissions.every((perm) => permissions.includes(perm)),
)
.map(([role]) => role);
return allowedRoles.join(', ');
} }
} }