Django基于框架组的各个视图的权限

时间:2017-07-24 12:06:52

标签: django permissions django-rest-framework django-permissions role-based-access-control

我正在使用DRF编写API。我想为我的Modelviewsets中的每个视图赋予不同的权限。我有两个小组(客户和员工)。我已经在 permissions.py 中将它们过滤为Isstaff和Iscustomer。

class Iscustomer(permissions.BasePermission):
    def has_permission(self, request, view):
        if request.user and request.user.groups.filter(name='customers'):
            return True
        return False


class Isstaff(permissions.BasePermission):
    def has_permission(self, request, view):
        if request.user and request.user.groups.filter(name='staff'):
            return True
        return False

我正在尝试使用get_permissions方法。 当我在self.permission_classes中放置一个组时,它可以正常工作。

class cityviewset(viewsets.ModelViewSet):
    queryset = city.objects.all()
    serializer_class = citySerializer

    def get_permissions(self):    
        if self.request.method == 'POST' or self.request.method == 'DELETE':
            self.permission_classes = [Isstaff]
        return super(cityviewset, self).get_permissions()

但是,当我尝试在self.permission_classes中放置多个组时,它会失败。

def get_permissions(self):
    if self.request.method == 'POST' or self.request.method == 'DELETE':
        self.permission_classes = [Isstaff,Iscustomer,]
    return super(cityviewset, self).get_permissions()

1 个答案:

答案 0 :(得分:1)

问题在于您向视图添加多个permission_classes。检查permissions的方法是check_permissions()。如果你看一下DRF代码,

def check_permissions(self, request):
    """
    Check if the request should be permitted.
    Raises an appropriate exception if the request is not permitted.
    """
    for permission in self.get_permissions():
        if not permission.has_permission(request, self):
            self.permission_denied(
                request, message=getattr(permission, 'message', None)
            )

当您提供多个permission_classes时,用户必须同时满足这两个权限。因此,登录用户必须同时是员工和客户。我认为这就是你的观点失败的原因。