I have role guard for ADMIN, SUPERADMIN, USER, MODERATORS,
This is an example of one of the guards. An Admin guard in the case. They are working as I expected but I can't add multiple guards in the controller
import { Injectable, CanActivate, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';
@/Injectable()
export class AdminGuard implements CanActivate {
constructor() { }
canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
const user = request.user;
if (user.usertype == 'Admin') {
return true;
}
throw new HttpException('Unauthorized access', HttpStatus.BAD_REQUEST);
}
}
in my controllers, I have this decorator
@UseGuards(AuthGuard('jwt'), AdminGuard)
I want to be able to do something like this
@UseGuards(AuthGuard('jwt'), AdminGuard, SuperAdminGuard)
or
@UseGuards(AuthGuard('jwt'), [AdminGuard, SuperAdminGuard, UserGuard])
or
@UseGuards(AuthGuard('jwt'), AdminGuard || SuperAdminGuard || UserGuard])
None of the above implementations worked. Is there a better way to go about it? Maybe there is something I am not doing right. I have checked the docs but I can't seem to make it work
@UseGuards(A, B, C)
, ifA
returns false, it won't go toB
. So in order to proceed, all must return true. You may want to handle like this:if (user.usertype === 'Admin' || user.usertype) { return true }
so the next guard can be invoked. – Ambulant