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
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