Add permission and role management features

This commit is contained in:
faris Aljohari
2024-12-16 00:19:14 -06:00
parent 57397e653a
commit 64027d3a16
22 changed files with 473 additions and 17 deletions

View File

@ -0,0 +1,44 @@
import { Injectable, ExecutionContext } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Reflector } from '@nestjs/core';
import { RolePermissions } from '@app/common/constants/role-permissions';
import { RoleType } from '@app/common/constants/role.type.enum';
@Injectable()
export class PermissionsGuard extends AuthGuard('jwt') {
constructor(private reflector: Reflector) {
super();
}
async canActivate(context: ExecutionContext): Promise<boolean> {
// First, run the AuthGuard logic to validate the JWT
const isAuthenticated = await super.canActivate(context);
if (!isAuthenticated) {
return false;
}
// Authorization logic
const requiredPermissions = this.reflector.get<string[]>(
'permissions',
context.getHandler(),
);
if (!requiredPermissions) {
return true; // Allow if no permissions are specified
}
const request = context.switchToHttp().getRequest();
const user = request.user; // User is now available after AuthGuard
console.log('user', user);
const userRole = user?.role.type as RoleType;
if (!userRole || !RolePermissions[userRole]) {
return false; // Deny if role or permissions are missing
}
const userPermissions = RolePermissions[userRole];
// Check if the user has the required permissions
return requiredPermissions.every((perm) => userPermissions.includes(perm));
}
}