[Answer]-Passing user credentials from Tastypie to Django Model

1👍

What you could do is override the obj_get_list method that returns the list of resources for a request. Also, you could set the username and password to the request object itself, so the paramters get carried over the request-response path. Also, you’d need to set the queryset to all().

def obj_get_list(self, bundle, **kwargs):
    original = super(TestResource, self).obj_get_list(bundle, **kwargs)
    request = bundle.request
    return original.get_all(request.username, request.password)

Or the other way round – you could add custom authorization that would filter the objects list. The request attributes part still holds.

class MyAuth(Authorization):
   def authorized_read_list(self, objects, bundle):
       request = bundle.request
       return objects.get_all(request.username, request.password)

If you would rather imitate queryset using get_all than just alternating list endpoint, you could override the get_object_list.

def get_object_list(self, request):
    original = super(TestResource, self).get_object_list(request)
    return original.get_all(request.username, request.password)

0👍

I looked into the Tastypie documentation, and it seems like the following could be a solution, albeit amateurish:

class TestResource(ModelResource):

    class Meta:
        queryset = Test.remote_supported.get_all('dummyusername','dummypassword')
        resource_name = 'test'
        filtering = {
            'id' : ALL,
        }
        detail_allowed_methods = ['get', 'post', 'patch']       
        authorization = Authorization()
        authentication = MyCustomAuth()
        always_return_data = True

    def get_object_list(self, request):
        """
        This method calls a clone of the queryset declared in the Metaclass.
        It is called every time a query is executed.
        Here the actual username and password is passed to the model.
        """         
        return Site.remote_supported.get_all(self.username,self.password)

The problem was that the queryset declaration happened in the Metaclass only once, not per query, so the username and password acquired from the http request could not be passed on to the query in the Meta level. But since get_object_list() clones the declaration and performs the actual call with the updates argument values, this gets the job done. It is working for me, but I feel there should be a better solution for doing this.

Leave a comment