Anjula Samarasinghe
Anjula Samarasinghe

Reputation: 237

User is undefined on the context.switchToHttp().getRequest() nestjs

I'm new to nestJs and I needed to add role based access to the application so I followed the documentation but in the execution context user doesn't exist. I can't seems to find the problem here's the github repo if you need to seem more code: https://github.com/anjula-sack/slinc-backend

roles.guard.ts

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

@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(context.switchToHttp().getRequest().req);

    return requiredRoles.some((role) => user.type === role);
  }
}

app.controller.ts

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Get('me/business')
  @Roles(Role.ADMIN)
  getBusiness(@Request() req) {
    return this.usersService.getUserBusiness(req.user.id);
  }

Upvotes: 5

Views: 8143

Answers (1)

Mic Fung
Mic Fung

Reputation: 5692

From the code, I think you are mixing global and local guard

In app.module.ts, the below code is for registering global guard. and app.useGlobalGuard() should be used together if you want to apply guard globally.

// Remove the following code in app.module.ts
{
    provide: APP_GUARD,
    useClass: RolesGuard,
}

But your intention should be building a local role guard, so please remove the above code and the request user will work.

Upvotes: 7

Related Questions