#Doesn't success to get the user from context.switchToHttp().getRequest();

5 messages · Page 1 of 1 (latest)

vast jolt
#

Hello,
I am trying to create a roles.guard for my nestJS API and I am stuck with this :

//roles.guard.ts
async canActivate(context: ExecutionContext): Promise<boolean> {
    
    const roles = this.reflector.get<Role[]>(ROLES_KEY, context.getHandler());

    const request = context.switchToHttp().getRequest();
    console.log(request.user)```
I always get "undefined" with the console.log(request.user).
Here is my controller : ```ts
//job.controller.ts
@Get()
    @UseGuards(JwtAuthGuard)
    @UseGuards(RolesGuard)
    @Roles(Role.MANAGER)
    findAll() {
        return this.jobService.findAll();
    }```
and when I tried this, I get the user as I want : 
```ts
//job.controller.ts
@UseGuards(JwtAuthGuard)
    @Get('test')
    test(@Req() req) {
        return req.user;
    }```
Do you have any suggestions on what I should do to fix this problem please?
woeful dock
#

Shouldn't the two guards on the controller be swapped? jwt guard must be activated first to add a user.

vast jolt
#

Ok, thank you, it works, I didn't know that the order was important.
So here is the result:

//job.controller.ts
@Get()
    @UseGuards(RolesGuard)
    @UseGuards(JwtAuthGuard)
    @Roles(Role.MANAGER)
    findAll() {
        return this.jobService.findAll();
    }```
intead of:
```ts
//job.controller.ts
@Get()
    @UseGuards(JwtAuthGuard)
    @UseGuards(RolesGuard)
    @Roles(Role.MANAGER)
    findAll() {
        return this.jobService.findAll();
    }```
woeful dock
brazen arrow