【发布时间】:2019-07-25 13:23:46
【问题描述】:
在控制器中,我添加带有保护的用户对象,注入一些服务并调用该服务以获得一些响应。为简洁起见,我删除了很多代码。
@Controller()
@UseGuards(AuthGuard())
export class UserController() {
constructor(private readonly userService: UsersService) {
}
@Get(':id')
async findOne(@Param('id') id) {
return await this.userService.findOne(id);
}
}
由于我有AuthGuard,我现在知道用户在输入:id 路由之前已登录。
在服务中我会做类似的事情
@Injectable()
export class UsersService {
async findOne(id: number): Promise<User> {
return await this.usersRepository.findOne({where: {id: id}});
}
}
当然,我们希望检查登录用户是否有权访问它正在查询的用户。现在的问题是如何获取当前登录的用户。我可以将它作为参数从控制器发送,但由于很多后端需要对当前用户进行安全检查,我不确定这是一个好主意。
@Get(':id')
async findOne(@Param('id') id, @Req() req: any) {
return await this.userService.findOne(id, req.user);
}
理想情况下,这不起作用,我可以在 UserService 中获取它:
async findOne(id: number, @Req req: any): Promise<User> {
if (id === req.user.id || req.user.roles.contains('ADMIN')) {
return await this.userRepository.findOne({where: {id: id}});
}
}
或者也许通过UserService构造函数中的注入
constructor(@Inject(REQUEST_OBJECT) private readonly req: any) {}
那么,有没有比在每次函数调用中始终发送请求对象更好的方式通过后端发送用户对象?
【问题讨论】:
标签: javascript node.js typescript nestjs