Created
September 18, 2019 05:20
-
-
Save pythoneast/94fbd1d2b6ffdeec4c8cc774027605a0 to your computer and use it in GitHub Desktop.
Group based permissions for Django Rest Framework
This file contains hidden or 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
from django.contrib.auth.models import User, Group | |
from rest_framework import permissions | |
def is_in_group(user, group_name): | |
try: | |
return Group.objects.get(name=group_name).user_set.filter(id=user.id).exists() | |
except Group.DoesNotExist: | |
return False | |
class HasGroupPermission(permissions.BasePermission): | |
def has_permission(self, request, view): | |
required_groups = view.permission_groups.get(view.action) | |
if required_groups == None: | |
return False | |
elif '_Public' in required_groups: | |
return True | |
else: | |
return any([is_in_group(request.user, group_name) for group_name in required_groups]) |
This file contains hidden or 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
#import some stuff | |
from .permissions import * | |
class FooViewSet(viewsets.ModelViewSet) | |
queryset = Foo.objects.all() | |
serializer_class = FooSerializer | |
permission_classes = [HasGroupPermission] | |
permission_groups = { | |
'create': ['Developers'] # Developers can POST | |
'partial_update': ['Designers','Developers'], # Designers and Developers can PATCH | |
'retrieve': ['_Public'], # retrieve can be accessed without credentials (GET 'site.com/api/foo/1') | |
# list returns None and is therefore NOT accessible by anyone (GET 'site.com/api/foo') | |
} | |
# which methods are accessible, but setting a non-existent group also locks down methods. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment