nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
67.07k stars 7.56k forks source link

`request.user` is `undefined` in RolesGuard #2810

Closed aasmpro closed 5 years ago

aasmpro commented 5 years ago

Bug Report

Current behavior

request.user is undefined

Input Code

roles.guard.ts

import {
  Injectable,
  CanActivate,
  ExecutionContext,
  UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';

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

  canActivate(context: ExecutionContext): boolean {
    const roles = this.reflector.get<string[]>('roles', context.getHandler());
    if (!roles) {
      return true;
    }
    const request = context.switchToHttp().getRequest();
    const user = request.user; // is undefined
    if (user && user.role) {
      return roles.includes(user.role);
    } else {
      throw new UnauthorizedException();
    }
  }
}

roles.decorator.ts

import { SetMetadata } from '@nestjs/common';

export const Roles = (...roles: string[]) => SetMetadata('roles', roles);

userCrudController.ts

@Controller('api/users')
export class UserCrudController implements CrudController<User> {
  constructor(public service: UserCrudService) {}

  @UseGuards(AuthGuard('jwt')) // it works fine on other routs
  @Roles('admin') // used after AuthGurad
  @Override()
  async getMany(@ParsedRequest() req: CrudRequest) {
    return this.service.getMany(req);
  }
}

app.modules.ts

@Module({
  // other data...
  providers: [
    {
      provide: APP_GUARD,
      useClass: RolesGuard,
    },
  ],
})
export class AppModule {}

Expected behavior

request.user must be defined

Environment


Nest version: 6.5.2


For Tooling issues:
- Node version: v11.15.0
- Platform:  Linux, Windows
kamilmysliwiec commented 5 years ago

Please, use our Discord channel (support) for such questions. We are using GitHub to track bugs, feature requests, and potential improvements.

lock[bot] commented 4 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.