如何获得REST框架中的OR权限而不是AND [英] How to get OR permissions instead of AND in REST framework

查看:115
本文介绍了如何获得REST框架中的OR权限而不是AND的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当REST框架检查权限时,权限类似乎被AND了。这就是每个权限类都需要返回True才能授予权限。这使诸如如果您是超级用户,您可以访问任何东西,但是如果您是普通用户,则需要显式权限之类的东西有点难以实现,则不能仅返回False,这会使整个堆栈失败。有没有办法短路权限?诸如如果授予此权限,请停止检查?之类的内容。还是其他类似的方法?

It seems that permission classes are ANDed when REST framework checks permissions. That is every permission class needs to return True for permission to be granted. This makes things like "if you are a superuser, you can access anything, but if you are a regular user you need explicit permissions" a bit hard to implement, you cannot just return False, it will fail the whole stack. Is there a way to maybe short-circuit permissions? Something like "if this permission is granted, stop checking?" or some other way to deal with cases like that?

推荐答案

我认为您也许可以使用 django-rules 库。 链接

I think you might be able to use django-rules library here. Link

这是基于规则的引擎与决策树非常相似,并且可以轻松地与DRF的Permissions_class框架集成。

It is a rule based engine very similar to decision trees and it can be easily integrated with permissions_class framework of DRF.

最好的部分是您可以对简单权限执行设置操作,并从中创建复杂权限。

The best part is you can perform set operations on simple permissions and create complex permissions from them.

示例

>>> @rules.predicate
>>> def is_admin(user):
...     return user.is_staff 
...


>>> @rules.predicate
>>> def is_object_owner(user, object):
        return object.owner == user

谓词可以使用给定的参数几乎可以执行任何操作,但是如果检查的条件为true,则必须始终返回True,否则返回False。
现在将这两个谓词组合起来。

Predicates can do pretty much anything with the given arguments, but must always return True if the condition they check is true, False otherwise. Now combining these two predicates..

is_object_editable = is_object_owner | is_admin

您可以使用此新谓词规则 is_object_editable 在您的权限类的has_permissions方法中。

You can use this new predicate rule is_object_editable inside your has_permissions method of permission class.

这篇关于如何获得REST框架中的OR权限而不是AND的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆