简体   繁体   English

NestJS:基于实例属性最佳实践的授权

[英]NestJS: Authorization based on instances property best practice

I need authorization in NestJS based on instances property.我需要基于实例属性在 NestJS 中进行授权。 Ex.前任。 user can update only his own articles.用户只能更新自己的文章。

Is there another way despite defining the logic in each services?尽管在每个服务中定义了逻辑,还有另一种方法吗? ( I know it is possible using CASL ) (我知道使用 CASL 是可能的)

Not having a global guard will facility errors, and everything is authorized by default unless add logic on the service.没有全局守卫会导致错误,并且默认情况下所有内容都是授权的,除非在服务上添加逻辑。

what about creating a function that takes the request, the model and the name of the proprety and use it wherever you want?如何创建一个 function 来接收请求、model 和财产名称并在任何你想使用的地方使用它?

const verifAuthorization = (req: Request, propName: string, model:any): void=> {
const sender: User = req.user;
if (!sender) {
throw new BadRequestException('there is no user in the token');
}
if(!sender._id.equals(model[propName])) {
throw new UnauthorizedException();
}
}

yes, you will call it in every service you want to check the authorization in, but it will save you a lot of time and code是的,您将在每个要检查授权的服务中调用它,但它会为您节省大量时间和代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM