From f0cc46861b1da8c5928f63da2935423803b631bc Mon Sep 17 00:00:00 2001 From: Camille Harang Date: Fri, 3 Feb 2012 03:12:20 +0100 Subject: [PATCH] Moved ownership at the BaseResource level, as any resource can provide a Django User, not only a model instance --- djangorestframework/mixins.py | 10 ++++++++++ djangorestframework/permissions.py | 15 +++++---------- djangorestframework/resources.py | 6 ++++++ 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/djangorestframework/mixins.py b/djangorestframework/mixins.py index 106b56ef0..d5eeac818 100644 --- a/djangorestframework/mixins.py +++ b/djangorestframework/mixins.py @@ -527,6 +527,16 @@ class ModelMixin(object): """ return self.get_queryset().get(**kwargs) + def get_owner(self): + """ + Returns the model instance's owner, if any. + + The owner is retrieved by calling the .get_owner() function on the model instance, if implemented. + """ + try: + return self.model_instance.get_owner() + except: pass + @property def model_instance(self): """ diff --git a/djangorestframework/permissions.py b/djangorestframework/permissions.py index b350d29bf..8d02c4e5a 100644 --- a/djangorestframework/permissions.py +++ b/djangorestframework/permissions.py @@ -13,7 +13,7 @@ __all__ = ( 'BasePermission', 'FullAnonAccess', 'IsAuthenticated', - 'IsModelInstanceOwnerOrIsAnonReadOnly', + 'IsResourceOwnerOrIsAnonReadOnly', 'IsAdminUser', 'IsUserOrIsAnonReadOnly', 'PerUserThrottling', @@ -78,12 +78,9 @@ class IsAdminUser(BasePermission): raise _403_FORBIDDEN_RESPONSE -class IsModelInstanceOwnerOrIsAnonReadOnly(BasePermission): +class IsResourceOwnerOrIsAnonReadOnly(BasePermission): """ - The request is authenticated as the owner of the model instance, or is a read-only request. - - In order to determine the owner, the model has to provide a .get_owner() function that - returns the owner, otherwise the permission will be denied. + The request is authenticated as the owner of the resource, or is a read-only request. """ def check_permission(self, user): @@ -94,10 +91,8 @@ class IsModelInstanceOwnerOrIsAnonReadOnly(BasePermission): if not user.is_authenticated(): raise _403_FORBIDDEN_RESPONSE - try: - if self.view.model_instance.get_owner() == user: - return - except: pass + if self.view.get_owner() == user: + return raise _403_FORBIDDEN_RESPONSE diff --git a/djangorestframework/resources.py b/djangorestframework/resources.py index cc338cc05..7d0d1d5ff 100644 --- a/djangorestframework/resources.py +++ b/djangorestframework/resources.py @@ -32,6 +32,12 @@ class BaseResource(Serializer): """ return self.serialize(obj) + def get_owner(self): + """ + Returns a Django User instance as the owner of the resource, if any. + """ + return None + class Resource(BaseResource): """