mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-11-27 01:24:54 +00:00
Add permission and role management features
This commit is contained in:
44
src/guards/permissions.guard.ts
Normal file
44
src/guards/permissions.guard.ts
Normal 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));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user