DjangoRestFramework - has_permission错误地覆盖has_object_permission

时间:2015-11-03 00:32:34

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

这是我的许可:

class IsCreationOrAuthenticatedOrIsOwnerOrWatchOrReadOnly(permissions.BasePermission):
    """
    Allow only the owner (and admin) of the object to make changes (i.e.
    do PUT, PATCH, DELETE and POST requests. Allow all other users
    ReadOnly or Follow options. This is for UserViewSet. Allow unauthenticated users to
    create objects.
    """

    def has_permission(self, request, view):
        if not request.user.is_authenticated():
            if view.action == 'create':
                return True
            return False

        return request.method in permissions.SAFE_METHODS or request.user.is_staff or view.action=='follow'

    def has_object_permission(self, request, view, obj):

        if not request.user.is_authenticated():
            return False

        if request.method in permissions.SAFE_METHODS:
            return True

        if request.user.is_staff:
            return True

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

        return obj.owner == request.user

问题是经过身份验证的用户无法对自己的帐户进行PUT,PATCH或DELETE,因为在has_permission中它说:

return request.method in permissions.SAFE_METHODS or request.user.is_staff or view.action=='follow'

但是,这里的PUT,PATCH和DELETE取决于obj.owner == request.user(取决于对象)。因此,当has_permission无权访问对象时,如何允许用户仅对其帐户进行PUT,PATCH和DELETE,因此不应允许任何PUT,PATCH和DELETE(因为这取决于{{1}是否{{ 1}}。

1 个答案:

答案 0 :(得分:2)

为什么不禁用has_permissions并修改has_object_permission以检查POST?

def has_object_permission(self, request, view, obj):

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

    if not request.user.is_authenticated():
        return False

    if request.method in permissions.SAFE_METHODS:
        return True

    if request.user.is_staff:
        return True

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

    return obj.owner == request.user