aboutsummaryrefslogtreecommitdiffstats
path: root/rest_framework/permissions.py
diff options
context:
space:
mode:
authorTom Christie2013-09-10 20:21:15 +0100
committerTom Christie2013-09-10 20:21:15 +0100
commit75fb4b02b40da04f16c6c288bbe20ea0bc0b4154 (patch)
tree97e7b26506eed113a15d00ae8e9d8f438e0bef60 /rest_framework/permissions.py
parentf5c34926d6a4b4b29fb083d25b99b10d7431eee4 (diff)
parent23fc9dd53fcd9cc25e2c77e5ffae395f04d4990d (diff)
downloaddjango-rest-framework-75fb4b02b40da04f16c6c288bbe20ea0bc0b4154.tar.bz2
Merge branch 'master' of git://github.com/bwreilly/django-rest-framework into bwreilly-master
Diffstat (limited to 'rest_framework/permissions.py')
-rw-r--r--rest_framework/permissions.py45
1 files changed, 45 insertions, 0 deletions
diff --git a/rest_framework/permissions.py b/rest_framework/permissions.py
index 1036663e..70bf9c61 100644
--- a/rest_framework/permissions.py
+++ b/rest_framework/permissions.py
@@ -7,6 +7,7 @@ import warnings
SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
+from django.http import Http404
from rest_framework.compat import oauth2_provider_scope, oauth2_constants
@@ -151,6 +152,50 @@ class DjangoModelPermissionsOrAnonReadOnly(DjangoModelPermissions):
authenticated_users_only = False
+class DjangoObjectLevelModelPermissions(DjangoModelPermissions):
+ """
+ The request is authenticated using `django.contrib.auth` permissions.
+ See: https://docs.djangoproject.com/en/dev/topics/auth/#permissions
+
+ It ensures that the user is authenticated, and has the appropriate
+ `add`/`change`/`delete` permissions on the object using .has_perms.
+
+ This permission can only be applied against view classes that
+ provide a `.model` or `.queryset` attribute.
+ """
+
+ actions_map = {
+ 'GET': ['read_%(model_name)s'],
+ 'OPTIONS': ['read_%(model_name)s'],
+ 'HEAD': ['read_%(model_name)s'],
+ 'POST': ['add_%(model_name)s'],
+ 'PUT': ['change_%(model_name)s'],
+ 'PATCH': ['change_%(model_name)s'],
+ 'DELETE': ['delete_%(model_name)s'],
+ }
+
+ def get_required_object_permissions(self, method, model_cls):
+ kwargs = {
+ 'model_name': model_cls._meta.module_name
+ }
+ return [perm % kwargs for perm in self.actions_map[method]]
+
+ def has_object_permission(self, request, view, obj):
+ model_cls = getattr(view, 'model', None)
+ queryset = getattr(view, 'queryset', None)
+
+ if model_cls is None and queryset is not None:
+ model_cls = queryset.model
+
+ perms = self.get_required_object_permissions(request.method, model_cls)
+ user = request.user
+
+ check = user.has_perms(perms, obj)
+ if not check:
+ raise Http404
+ return user.has_perms(perms, obj)
+
+
class TokenHasReadWriteScope(BasePermission):
"""
The request is authenticated as a user and the token used has the right scope