Skip to content

Instantly share code, notes, and snippets.

@pydanny
Created December 31, 2011 20:30
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pydanny/1545255 to your computer and use it in GitHub Desktop.
Save pydanny/1545255 to your computer and use it in GitHub Desktop.
django-rest-framework permissions by groups
""" User Django Rest Framework to check to see if an authenticated user
is in a particular group
Usage::
from api.group_permissions import GroupAPIGETPermission
class SearchProductView(View):
permissions = (IsAuthenticated, GroupAPIGETPermission,)
"""
from django.contrib.auth.models import Group
from djangorestframework.permissions import _403_FORBIDDEN_RESPONSE, BasePermission
class GroupBasePermission(BasePermission):
group_name = ""
def check_permission(self, user):
"""
Should simply return, or raise a 403 response.
"""
try:
user.groups.get(name=self.group_name)
except Group.DoesNotExist:
raise _403_FORBIDDEN_RESPONSE
class GroupAPIGETPermission(GroupBasePermission):
"""
Checks to see if a user is in a particular group
"""
group_name = "API GET"
class GroupAPIPOSTPermission(GroupBasePermission):
"""
Checks to see if a user is in a particular group
"""
group_name = "API POST"
@tomchristie
Copy link

Possibly something like this?...

class APIPermission(BasePermission):
    """
    Verify that user has appropriate 'api_read' and/or 'api_write' permissions.
    """
    perm_codes = {'GET': 'api_read', 'POST': 'api_write', 'PUT': 'api_write', 'DELETE': 'api_write'}

    def check_permission(self, user): 
        perm_code = self.perm_codes.get(self.view.method, None)
        if perm_code and user.has_perm(perm_code):
            return True
        raise _403_FORBIDDEN_RESPONSE

Then:

Add 'api_reader' and 'api_writer' groups.
Give the groups the 'api_read' and 'api_write' permissions.
Assign users to groups.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment