Skip to content

Instantly share code, notes, and snippets.

@Symmetric
Last active December 3, 2015 20:32
Show Gist options
  • Save Symmetric/2edf67350e85e740c81c to your computer and use it in GitHub Desktop.
Save Symmetric/2edf67350e85e740c81c to your computer and use it in GitHub Desktop.
#! /usr/bin/env python
class UserViewSet(ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
def get_permissions(self):
# Allow non-authenticated user to create (i.e. register) by POST
return [AllowAny() if self.request.method == 'POST' else IsSuperOrTargetUser()]
class IsSuperOrTargetUser(BasePermission):
"""Permission class allowing super-user access, plus targeted access for non-super-users.
Cribbed from http://richardtier.com/2014/02/25/django-rest-framework-user-endpoint/
TODO: This permission model leaks information about the valid user_ids, since the has_object_permission
check won't be run if the object doesn't exist.
"""
def has_permission(self, request, view):
# Allow non-superusers to retrieve individual records, subject to per-object permissions below.
return view.action == 'retrieve' or request.user.is_staff
def has_object_permission(self, request, view, obj):
# Allow superusers access to all objects, otherwise only allow users access to their own object.
return request.user.is_superuser or obj == request.user
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment