[Answer]-In Tastypie, what is the right way to override Resource.is_authorized() to implement row-level permissions

1👍

The docs for tastypie 0.9.12 have a good example of this.

https://django-tastypie.readthedocs.org/en/v0.9.12/authorization.html#implementing-your-own-authorization

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.

👤erikcw

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 :

https://gist.github.com/airtonix/5476453

Leave a comment