DjangoRestFramework - 如何正确分离has_permission和has_object_permission

时间:2015-11-01 23:30:03

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

这是我的许可类:

class IsCreationOrFollowOrOwnerOrReadOnly(permissions.BasePermission):
    """
    Allow any users to create, get and follow objects. Allow only owners to
    PUT, PATCH and DELETE.
    """
    def has_permission(self, request, view):
        if request.method in permissions.SAFE_METHODS or request.user.is_staff:
            return True

        if view.action == 'create':
            return True

        return False

    def has_object_permission(self, request, view):
        if request.method in permissions.SAFE_METHODS or request.user.is_staff or view.action=='follow':
            return True

        try:
            return obj.owner == request.user
        except:
            return obj == request.user # If obj Is request.user

要关注对象,您必须使用follow操作。这是我的观点:

class {ageViewSet(viewsets.ModelViewSet):
    queryset = Page.objects.all()
    serializer_class = PageSerializer
    permission_classes = (IsAuthenticated, IsCreationOrFollowOrOwnerOrReadOnly,)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user, location=self.request.user.userextended.location)

    @detail_route(methods=['post'])
    def follow(self, request, pk=None):
        page = self.get_object()    

        page.users.add(request.user)

        return Response(status=status.HTTP_204_NO_CONTENT)

问题是,当我尝试关注某个对象时,它会给我一个403_FORBIDDEN状态代码。我假设这是因为在has_permission中,我必须添加以下行:

if view.action=='follow':
    return True

但即使我添加该行,当所有者试图将其投放到他自己的对象时,我会收到403_FORBIDDEN错误(这可能是因为我的has_permission方法中我没有if view.action == 'update': return True但是PUT,PATCH和DELETE都依赖于对象本身(if obj.owner == request.user)所以如何在允许任何用户使用FOLLOW对象的同时正确地允许用户进行PUT,PATCH和DELETE(FOLLOW也是一个对象级权限,因此将其置于has_permission对我来说没有意义,因为它与对象有关。)

1 个答案:

答案 0 :(得分:0)

您无需覆盖has_permission。只需覆盖has_object_permission即可:

def has_object_permission(self, request, view, obj):
    if request.method in permissions.SAFE_METHODS or request.user.is_staff or obj.owner == request.user:
        return True

    if request.method=='POST':
        return True

    return False

这样,所有者和员工可以执行任何操作。但是用户只能获取,发布和关注。