Reputation: 48972
I've added row-level authorization to a Tastypie Resource as follows:
from tastypie.exceptions import ImmediateHttpResponse
from tastypie.http import HttpUnauthorized
class MyResource(ModelResources):
...
def is_authorized(self, request, object=None):
super(MyResource, self).is_authorized(request, object)
if object and (object.user != request.user):
raise ImmediateHttpResponse(response=HttpUnauthorized())
For brevity, I've left out the usual imports and only specified the imports that are relavant to the question.
My question is, is there a cleaner way to override is_authorized
without having to import ImmediateHttpResponse
and HttpUnauthorized
? It seems to me that these are implementation details, and I should be able to simply return True
or False
.
Upvotes: 0
Views: 1265
Reputation: 5169
For the long run, you're much better off integrating django-guardian into your application with an authorization class like the following :
https://gist.github.com/airtonix/5476453
Upvotes: 0
Reputation: 11057
The docs for tastypie 0.9.12 have a good example of this.
Here is the "read" part -- see the docs for the rest:
class UserObjectsOnlyAuthorization(Authorization):
def read_list(self, object_list, bundle):
# This assumes a ``QuerySet`` from ``ModelResource``.
return object_list.filter(user=bundle.request.user)
def read_detail(self, object_list, bundle):
# Is the requested object owned by the user?
return bundle.obj.user == bundle.request.user
# DON'T FORGET TO IMPLEMENT METHODS FOR CREATE/UPDATE/DELETE as shown in the docs.
You'll notice that UserObjectsOnlyAuthorization.read_detail()
returns True/False. The read_list
method will return an empty list, which is acceptable according to the docs, but you can also raise Unauthorized
exception if you prefer.
Upvotes: 1
Reputation: 2382
Although your code is perfectly fine, but if you don't want to import the response classes then a cleaner way is to write an authorization class and use it in your Resource class
from tastypie.authorization import Authorization
class RowLevelAuthorization(Authorization):
def is_authorized(self, request, object=None):
if object and (object.user != request.user):
return False
else:
return True
class MyResource(ModelResources):
class Meta:
authorization = RowLevelAuthorization()
Upvotes: 0