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
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) {}
}
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.
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);
}
You can create a RolesGuard
that makes sure the logged in user has the required roles. For details, see this answer.