can not access user in role.guard

14 Views Asked by At

I am implementing very simple role-based authorization just like Nestjs document .

I want some routes to be accesssible just by Admin role

this is controller

@Controller('transaction')
export class TransactionController {
  constructor(private readonly transactionService: TransactionService) {}

  @UseGuards(JwtAuthGuard)
  @Roles(Role.Admin)
  @Get(':id/toggle-verified')
  update(@Param('id') id: string) {
    return this.transactionService.update(+id);
  }

}

as you see I have used

  @UseGuards(JwtAuthGuard)
  @Roles(Role.Admin)

and this is jwt.strategy

import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { jwtConstants } from './constants';
import { UsersService } from 'src/users/users.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private userService: UsersService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
    });
  }

  async validate(payload: any) {
    const userId = payload.sub;
    const user = await this.userService.findOne(userId);
    // console.log('role', user.role);
    return { userId, username: payload.email, roles: user.role };
  }
}

I am sure that this strategy works fine and it attach user to request seamlessly

the problem is here . this is role.guard

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

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  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();
    console.log('user',user) // it says user is undefined
    return requiredRoles.some((role) => user.roles == role);
  }
}

here user is undefined .

what is the problem ??

0

There are 0 best solutions below