0
import { ROLES_KEY } from './role.decorator';
import { UserRole } from '../users/role.enum';
import { CanActivate, Injectable, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const requiredRole = this.reflector.getAllAndOverride<UserRole[]>(
      ROLES_KEY,
      [context.getClass(), context.getHandler()],
    );
    if (!requiredRole) {
      return true
    }
    const req = context.switchToHttp().getRequest();
    const user = req.user;
    console.log('Before');
console.log(user)
    return requiredRole.some((role) => {
      if(role==="ADMIN"){
        console.log("True")
      }
      return role === 'ADMIN' 
    });
  }
}

The reason after return role==="ADMIN" then user can log but how can i get user before return role==="ADMIN execute ? I can get user only after the role==="ADMIN" return only Im using nest js working on RoleGuard

BlueDragon
  • 57
  • 1
  • 7
  • 1
    I'd be willing to bet that you're expecting `req.user` to be populated due to passport, but have the `RolesGuard` bound globally or in a way that executes before the `AuthGuard()` does. Is that the case? – Jay McDoniel Dec 15 '20 at 17:38
  • ```@Roles(UserRole.ADMIN) @UseGuards(JwtAuthGuard, RolesGuard) @Get() findAll():Observable { return from(this.usersService.findAll()); }.``` My Controller and RoleGuard I have import it in proivder of appModule.ts – BlueDragon Dec 15 '20 at 18:11
  • Now My Problem is solved Thank you I used it in another module as global its my mistake – BlueDragon Dec 15 '20 at 18:19

0 Answers0