Moved ownership at the BaseResource level, as any resource can provide a Django User, not only a model instance

This commit is contained in:
Camille Harang 2012-02-03 03:12:20 +01:00
parent 92da637752
commit f0cc46861b
3 changed files with 21 additions and 10 deletions

View File

@ -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):
"""

View File

@ -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:
if self.view.get_owner() == user:
return
except: pass
raise _403_FORBIDDEN_RESPONSE

View File

@ -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):
"""