Andrew Barr
Andrew Barr

Reputation: 3800

how to limit GET access to resources using DjangoAuthorization() in tastypie

I am using tastypie to create a RESTful API. I have hit a snag with limiting user authorization based on the django admin permissions. Per the docs, I am trying to implement DjangoAuthorization().

class myResource(ModelResource):
   class Meta:
      queryset = myModel.objects().all()
      allowed_methods = ['get','post']
      authentication = ApiKeyAuthentication()
      authorization = DjangoAuthorization()

Currently, a user fakeuser with no Django permissions at all on myModel can still GET data from the api. This user is appropriatly restricted from POSTing data.

tl;dr How can I extend the DjangoAuthorization() class to restrict GET for users with no Django permisions on a model

Upvotes: 2

Views: 1046

Answers (1)

Aamir Rind
Aamir Rind

Reputation: 39689

Write your own Authorization Backend extending from DjangoAuthorization which overrides access methods according to your criteria, one example of how to override the read_detail (GET) method below:

from tastypie.authorization import DjangoAuthorization
from tastypie.exceptions import Unauthorized

class CustomDjangoAuthorization(DjangoAuthorization):

    def read_detail(self, object_list, bundle):
        result = super(CustomDjangoAuthorization, self).read_detail(object_list, bundle)

        # now we check here for specific permission
        if not bundle.request.user.has_perm('any_permission'):
            raise Unauthorized("You are not allowed to access that resource.")

        return result

Now use CustomDjangoAuthorization class in your resource:

class myResource(ModelResource):
   class Meta:
      queryset = myModel.objects().all()
      allowed_methods = ['get','post']
      authentication = ApiKeyAuthentication()
      authorization = CustomDjangoAuthorization()

Upvotes: 6

Related Questions