Django REST framework object level permissions

前端 未结 5 1970
我寻月下人不归
我寻月下人不归 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:16

    I have done this in the past using a custom permission and overridden has_object_permission like the following:

    from rest_framework import permissions
    
    
    class MyUserPermissions(permissions.BasePermission):
        """
        Handles permissions for users.  The basic rules are
    
         - owner may GET, PUT, POST, DELETE
         - nobody else can access
         """
    
        def has_object_permission(self, request, view, obj):
    
            # check if user is owner
            return request.user == obj
    

    You can do some more detailed things such as deny specific request types (for instance to allow a GET requests for all users):

    class MyUserPermissions(permissions.BasePermission):
    
        def has_object_permission(self, request, view, obj):
    
            # Allow get requests for all
            if request.method == 'GET':
                return True
            return request.user == obj
    

    Then in your view you tell it to use the permissions class:

    from my_custom_permissions import MyUserPermissions
    
    class UserView(generics.ListCreateAPIView):
        ...
        permission_classes = (MyUserPermissions, )
        ...
    

提交回复
热议问题