Skip to content

Instantly share code, notes, and snippets.

@jleclanche
Last active December 14, 2015 11:49
Show Gist options
  • Save jleclanche/5081567 to your computer and use it in GitHub Desktop.
Save jleclanche/5081567 to your computer and use it in GitHub Desktop.
Tastypie 0.9.12 SameUserAuthorization
from django.contrib.auth.models import User
from tastypie.authorization import Authorization, Unauthorized
class SameUserAuthorization(Authorization):
"""
Authorizes user to create, read and modify resources if they match
a specific or a set of users.
By default, this checks the user against the "user" attribute of the object.
To modify that behaviour, pass a custom `user` argument to
the authorization, e.g.:
SameUserAuthorization(user=lambda bundle: bundle.obj.other_user)
To authorize a specific user:
SameUserAuthorization(user=lambda bundle: User.objects.get(username="admin"))
Or even authorize a set of users:
SameUserAuthorization(user=lambda bundle: User.objects.filter(is_staff=True))
"""
def __init__(self, *args, **kwargs):
self._get_user = kwargs.pop("user", lambda bundle: bundle.obj.user)
super(SameUserAuthorization, self).__init__(*args, **kwargs)
def _check(self, bundle):
user = self._get_user(bundle)
if not user:
return False
elif isinstance(user, User):
return bundle.request.user == user
else:
return bundle.request.user in user
def read_list(self, object_list, bundle):
user = self._get_user(bundle)
if not user:
return []
elif isinstance(user, User):
return object_list.filter(user=user)
else:
return object_list.filter(user__in=user)
def read_detail(self, object_list, bundle):
if not self._check(bundle):
raise Unauthorized("You may only read or write resources you own")
def create_list(self, object_list, bundle):
return object_list
def create_detail(self, object_list, bundle):
if not self._check(bundle):
raise Unauthorized("You may only read or write resources you own")
def update_list(self, object_list, bundle):
return [obj for obj in object_list if self._check(bundle)]
def update_detail(self, object_list, bundle):
if not self._check(bundle):
raise Unauthorized("You may only read or write resources you own")
def delete_list(self, object_list, bundle):
raise Unauthorized("You may not delete resources.")
def delete_detail(self, object_list, bundle):
raise Unauthorized("You may not delete resources.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment