mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-11-26 09:54:55 +00:00
Refactor PermissionsGuard to throw UnauthorizedException with detailed message
This commit is contained in:
@ -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(', ');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user