Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apply_authorization_limits is not called

I try to get details about my authenticated user in my Django app.

For that I created a new resource :

class MyUserResource(ModelResource):
    class Meta:
        queryset = ReaderUser.objects.all()
        resource_name = 'me'
        list_allowed_methods = []
        detail_allowed_methods = ['get']
        authorization = Authorization()
        authentication = SessionAuthentication()
        excludes = ('password', 'id', 'is_active', 'is_admin', 'last_login')

    def apply_authorization_limits(self, request, object_list):
        print request.user
        return object_list.filter(pk=request.user.pk)

    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
        ]

When I call my API using /api/me/?format=json I got the following : More than one resource is found at this URI.

I have also tried without the prepend_urls. What I don't understand is that the print statement is never executed in the method apply_authorization_limits

Any hints about what I am doing wrong?

like image 722
Jeremy D Avatar asked Oct 02 '22 21:10

Jeremy D


1 Answers

I found two ways to fix my issue:

The first one is two create my own authorization.

In my case, the following:

from tastypie.authorization import Authorization

class SimpleReaderAuthorization(Authorization):
    def read_list(self, object_list, bundle):
        return object_list.filter(email=bundle.request.user.email)

And I just need to update my resource:

class MyUserResource(ModelResource):
    class Meta:
        queryset = ReaderUser.objects.all()
        resource_name = 'me'
        list_allowed_methods = ['get']
        authorization = SimpleReaderAuthorization()
        authentication = SessionAuthentication()
        excludes = ('password', 'id', 'is_active', 'is_admin', 'last_login')

Another simple way is to do the following, as indicated in the documentation.

def get_object_list(self, request): 
        return super(YourResource, self).get_object_list(request).filter(pk=request.user.pk)

Conclusion: I chose the second one as it is cleaner, and simple.

like image 131
Jeremy D Avatar answered Oct 05 '22 10:10

Jeremy D