django 复合权限DRF

iih3973s  于 2023-01-27  发布在  Go
关注(0)|答案(1)|浏览(142)

我有一个从RetrieveUpdateDestroyAPIView继承的视图类。我需要为不同的方法设置不同的权限类,因此我重写了get_permissions方法,但遇到错误
TypeError:不支持的操作数类型|:“是超级管理员”和“是所有者”。
views.py

class UserView(RetrieveUpdateDestroyAPIView):
        queryset = User.objects.all()
        serializer_class = UserSerializer
        http_method_names = ['patch', 'get', 'delete']

        def get_permissions(self):
            if self.request.method == 'GET':
            return [IsAuthenticated(), IsSuperAdmin()|IsOwner()|IsAdmin(), ]
            elif self.request.method == 'DELETE':
                return [IsAuthenticated(), IsSuperAdmin()|IsAdmin()]
            else:
            return [IsAuthenticated(), IsSuperAdmin()|IsAdmin()|IsOwner(), ]

permissions.py

class IsSuperAdmin(BasePermission):
        message = "You must be super admin to perform requested operation"

        def has_permission(self, request, view):
            if  request.user.role == "super_admin":
                return True
            return False

    class IsAdmin(BasePermission):
        message = "You must be admin to perform requested operation"

        def has_permission(self, request, view):
            if  request.user.role == "admin":
                return True
            return False


    class IsOwner(BasePermission):
        message = "You must be owner of resource to perform requested operaton"

        def has_object_permission(self, request, view, obj):
            if obj.id == request.user.id:
                return True
            return False
ubof19bj

ubof19bj1#

您不需要示例化权限类,因此代码

return [IsAuthenticated(), IsSuperAdmin()|IsOwner()|IsAdmin(), ]

应该像

return [IsAuthenticated, IsSuperAdmin |IsOwner | IsAdmin ]

参考其余框架文件:https://www.django-rest-framework.org/api-guide/permissions/#setting-the-permission-policy

相关问题