Howto get req.user in services in Nest JS

前端 未结 1 1163
甜味超标
甜味超标 2021-02-08 09:25

In a controller, I add the user object with a guard, inject some service and call that service to get some response. I have removed a lot of code for brevity.

@C         


        
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-08 09:51

    Update March 2019

    Since version v6, you can now inject the request object into a request-scoped provider:

    import { REQUEST } from '@nestjs/core';
    import { Request } from 'express';
    
    @Injectable({ scope: Scope.REQUEST })
    export class UsersService {
      constructor(@Inject(REQUEST) private readonly request: Request) {}
    }
    

    Outdated answer

    It's not possible to inject the user (or request) directly into the service. Nest.js does not yet support request-scoped providers. This might change with version 6. Until then, a service does not know anything about a request.

    Logged in user

    You can create a custom decorator @User. Using a decorator is preferable over injecting the request object because then a lot of nest's advantages get lost (like inceptors and exception filters).

    export const User = createParamDecorator((data, req) => {
      return req.user;
    });
    

    And then use it like this:

    @UseGuards(AuthGuard()) 
    @Get(':id)
    async findOne(@Param('id') id, @User() user) {
       return await this.userService.findOne(id, user);
    }
    

    Roles

    You can create a RolesGuard that makes sure the logged in user has the required roles. For details, see this answer.

    0 讨论(0)
提交回复
热议问题