如何在DRF中合并/混合对象级别和用户级别的权限?

时间:2019-04-19 18:29:31

标签: python django django-rest-framework django-permissions

我目前正在DRF项目中,管理员用户,教师用户和所有者用户应该可以访问对象的详细视图。基本上是所有用户类型,但不是对象所有者,教师或管理员用户的用户类型除外。我能够为每个对象实现单独的权限,但是当我需要在视图上组合这些权限时,我遇到了障碍,因为在检查用户级别的权限之前先检查用户级别的权限。因此,我不能使用布尔操作数来组合它们,而必须为我的视图编写这些难看的权限类。

我的问题是:

如何以更简洁的方式在详细视图上实现这些权限?或者,有没有更简洁的方式来获取结果?

正如您将看到的,我违反了DRY,因为我有一个IsAdminOrOwner和IsAdminOrTeacherOrOwner烫发。在我看来,您还将注意到,我覆盖了get_permissions()以使其具有用于相应请求方法的适当权限类。欢迎对此方法和其他实现方式发表任何评论,我想批评一下,以便对此进行改进。

遵循Permissions.py:

from rest_framework import permissions
from rest_framework.permissions import IsAdminUser

class IsOwner(permissions.BasePermission):

    def has_permission(self, request, view):
        return True

    def has_object_permission(self, request, view, obj):
        return request.user == obj

class IsTeacher(permissions.BasePermission):

    def has_permission(self, request, view):
        return request.user.groups.filter(
            name='teacher_group').exists()

class IsAdminOrOwner(permissions.BasePermission):

    def has_object_permission(self, *args):
        is_owner = IsOwner().has_object_permission(*args)

        #convert tuple to list
        new_args = list(args)
        #remove object for non-object permission args
        new_args.pop()
        is_admin = IsAdminUser().has_permission(*new_args)

        return is_owner or is_admin

class IsAdminOrTeacherOrOwner(permissions.BasePermission):

    def has_object_permission(self, *args):
        is_owner = IsOwner().has_object_permission(*args)

        #convert tuple to list
        new_args = list(args)
        #remove object for non-object permission args
        new_args.pop()
        is_admin = IsAdminUser().has_permission(*new_args)
        is_teacher = IsTeacher().has_permission(*new_args)

        return is_admin or is_teacher or is_owner

这是我的看法:

class UserRetrieveUpdateView(APIView):
    serializer_class = UserSerializer

    def get_permissions(self):
        #the = is essential, because with each view
        #it resets the permission classes
        #if we did not implement it, the permissions
        #would have added up incorrectly
        self.permission_classes = [IsAuthenticated]

        if self.request.method == 'GET':
            self.permission_classes.append(
                IsAdminOrTeacherOrOwner)

        elif self.request.method == 'PUT':
            self.permission_classes.append(IsOwner)

        return super().get_permissions()

    def get_object(self, pk):
        try:
            user = User.objects.get(pk=pk)
            self.check_object_permissions(self.request, user)
            return user
        except User.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        user = self.get_object(pk)
        serializer = self.serializer_class(user)
        return Response(serializer.data, status.HTTP_200_OK)

    def put(self, request, pk, format=None):
        user = self.get_object(pk)
        #we use partial to update only certain values
        serializer = self.serializer_class(user,
            data=request.data, partial=True)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data,
                status.HTTP_200_OK)

        return Response(status=status.HTTP_400_BAD_REQUEST)

1 个答案:

答案 0 :(得分:0)

Permissions in DRF可以使用按位或运算符组合。例如,您可以这样做:

permission_classes = (IsAdmin | IsOwner | IsTeacher)

通过这种方式,您不必定义单独的类即可将它们组合在一起。