Last active
December 3, 2015 20:32
-
-
Save Symmetric/2edf67350e85e740c81c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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