How to get OR permissions instead of AND in REST framework

前端 未结 6 1440
遇见更好的自我
遇见更好的自我 2021-02-05 06:45

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 t

6条回答
  •  时光取名叫无心
    2021-02-05 07:16

    Here is a generic solution:

    from functools import reduce
    from rest_framework.decorators import permission_classes
    from rest_framework.permissions import BasePermission
    
    
    def any_of(*perm_classes):
        """Returns permission class that allows access for
           one of permission classes provided in perm_classes"""
        class Or(BasePermission):
            def has_permission(*args):
                allowed = [p.has_permission(*args) for p in perm_classes]
                return reduce(lambda x, y: x or y, allowed)
    
        return Or
    
    
    class IsAdmin(BasePermission):
        """Allow access to admins"""
    
        def has_object_permission(self, request, view, obj):
            return request.user.is_admin()
    
    
    class IsOwner(BasePermission):
        """Allow access to owners"""
    
        def has_object_permission(self, request, view, obj):
            request.user.is_owner(obj)
    
    
    """Allow access to admins and owners"""
    
    
    @permission_classes((any_of(IsAdmin, IsOwner),))
    def you_function(request):
        # Your logic
        ...
    

提交回复
热议问题