1👍
✅
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.
0👍
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()
0👍
For the long run, you’re much better off integrating django-guardian into your application with an authorization class like the following :
- [Answer]-Web framework for an application that runs a hourly job and has simple GUI
- [Answer]-How to count objects count that have ForeignKey relationship?
- [Answer]-GeoDjango or just plain Django?
Source:stackexchange.com