monstar-lab-oss / nestjs-starter-rest-api

NestJS Starter Kit. Monolithic Backend. REST API.
MIT License
546 stars 85 forks source link

list all users fails with @UseGuards(JwtAuthGuard) #418

Closed vijaykumar1710 closed 10 months ago

vijaykumar1710 commented 10 months ago

list all users api fails to retrieve all the users if the guard is added and throws the Internal server error

war1oc commented 10 months ago

Hello @vijaykumar1710, can you add more detail such as a stack trace from the console? Meanwhile, @ZulfikarAliZihan let's try to see if we can reproduce this issue.

vijaykumar1710 commented 10 months ago

Hello @vijaykumar1710, can you add more detail such as a stack trace from the console? Meanwhile, @ZulfikarAliZihan let's try to see if we can reproduce this issue.

console error looks like this

{"contextName":"AllExceptionsFilter","ctx":{"ip":"::1","requestID":"fd4382dc-c1b4-42cf-bb7f-4803ce94b9f3","url":"/api/v1/users","user":null},"error":{"details":"","errorName":"InternalException","message":"Internal server error","path":"/api/v1/users","requestId":"fd4382dc-c1b4-42cf-bb7f-4803ce94b9f3","statusCode":500,"timestamp":"2023-12-22T10:42:01.205Z"},"level":"warn","message":"Internal server error","timestamp":"2023-12-22T10:42:01.206Z"}

Modification i have done is added one more role super_admin and modified user acl service as below. But i hope it has nothing to do with the above error, which should work irrespective of my changes.

annotation changes i have done is

 @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(ROLE.ADMIN, ROLE.SUPERADMIN)
constructor() {
    super();
    //super Admin can do all action
    this.canDo(ROLE.SUPERADMIN, [Action.Manage]);
    // Admin can do all action
    this.canDo(ROLE.ADMIN, [Action.Read]);
    //user can read himself or any other user
    this.canDo(ROLE.USER, [Action.Read], this.isUserItself);
    // user can only update himself
    this.canDo(ROLE.USER, [Action.Update], this.isUserItself);
  }
vijaykumar1710 commented 10 months ago

@war1oc @ZulfikarAliZihan This issue is also re-producible at my end, even if i remove all my changes. This needs to be looked. Only admin should be allowed to see all users list.

curl -X 'GET' \ 'http://localhost:3000/api/v1/users' \ -H 'accept: application/json'

there is no bearer token being sent here. This could be the root cause.

vijaykumar1710 commented 10 months ago

Please order the annotations for the api function as below. It started working.

@UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(ROLE.ADMIN, ROLE.SUPERADMIN)
  @ApiBearerAuth()
  @UseInterceptors(ClassSerializerInterceptor)
  @Get()
  @ApiOperation({
    summary: 'Get users as a list API',
  })
  @ApiResponse({
    status: HttpStatus.OK,
    type: SwaggerBaseApiResponse([UserOutput]),
  })
  @ApiResponse({
    status: HttpStatus.UNAUTHORIZED,
    type: BaseApiErrorResponse,
  })