我一直在学习Nest.js。 我按照文档 nestjs casl 集成
将 auth 和 authz 与 jwt + casl 集成一切正常,除了 casl 条件检查:
can(Action.Update, User, { id: user.id })
这里,虽然
id
不等于user.id
,但它并不限制动作
User 是数据库模型吗? 因为在那种情况下它不会工作。
这是因为在检查权限时必须传递该类的实例,但这是不切实际的(想象一下每次要比较“id”时从数据库中查询特定用户)。
在我的例子中,我使用了一个“dto”来验证大多数用户的属性。确保定义了“id”属性。
例如:
更新UserDto
export class UpdateUserDto {
id: string;
username: string;
profile_picture;
}
现在在您的 user.service.ts
/*Assuming you returned an 'user' object from an 'auth guard'*/
updateUser(updatedData: UpdateUserDto, user) {
const ability = this.caslFactory.createForUser(user);
if(!ability.can(Actions.update, updatedData)) throw new ForbiddenExceptionError('This user can't perform this kind of action')
}
希望这有帮助。