src/core/guards/roles.guard.ts
roles guard
Methods |
constructor(reflector: Reflector)
|
||||||||
Defined in src/core/guards/roles.guard.ts:9
|
||||||||
contructs the role guard service
Parameters :
|
canActivate | ||||||||
canActivate(context: ExecutionContext)
|
||||||||
Defined in src/core/guards/roles.guard.ts:23
|
||||||||
checks if the user has allowed permission (role)
Parameters :
Returns :
boolean
returns true if the user has appropriate role |
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Roles as Role } from '..//domain/enums';
import { ROLES_KEY } from '../decorators';
/**
* roles guard
*/
@Injectable()
export class RolesGuard implements CanActivate {
//==================================================================================================
/**
* contructs the role guard service
* @param reflector reflector of the guard
*/
constructor(private reflector: Reflector) {}
//==================================================================================================
/**
* checks if the user has allowed permission (role)
* @param context context of the guard (actual information)
* @returns returns true if the user has appropriate role
*/
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles) {
return true;
}
const { user } = context.switchToHttp().getRequest();
return user.roles.some((role: Role) => requiredRoles.includes(role));
}
//==================================================================================================
}