Django REST framework object level permissions

前端 未结 5 1969
我寻月下人不归
我寻月下人不归 2021-02-01 03:46

I am using Django REST Framework to access a resource \'user\'.

As user information is personal, I do not want a GET request to list every user on the system, UNLESS the

5条回答
  •  死守一世寂寞
    2021-02-01 04:17

    Just one more thing to @will-hart's answer.

    In DRF3 documentation,

    Note: The instance-level has_object_permission method will only be called if the view-level has_permission checks have already passed

    Therefore, has_permission should be specified to use has_object_permission.

    from rest_framework import permissions
    
    class MyUserPermissions(permissions.BasePermission):
    
        def has_permission(self, request, view):
            return True
    
        def has_object_permission(self, request, view, obj):
            return request.user == obj
    

    However, above code will give permission to anyone when user tries to get list of user. In this case, it would be better to give permission according to action, not the HTTP method.

    from rest_framework import permissions
    
    def has_permission(self, request, view):
        if request.user.is_superuser:
            return True
        elif view.action == 'retrieve':
            return True
        else:
            return False
    
    def has_object_permission(self, request, view, obj):
        if request.user.is_superuser:
            return True
        elif view.action == 'retrieve':
            return obj == request.user or request.user.is_staff
    

提交回复
热议问题