Search code examples
pythondjangoauthenticationtastypie

Get authenticated user in django-tastypie


I'm just starting with Python and Django, and using tastypie to create a RESTful API.

I need to calculate a field of a resource based on the authenticated user, I plan to override the dehydrate_field method in my resource, but I don't know how to get the authenticated user within the dehydrate_field method.

I'm using tastypie's ApiKeyAuthentication, and I'm currently passing the authentication parameters in the query string of the URL but I'd like to be able to pass the authentication parameters in the Authentication header too.

I think I should be able to get username from the query string or the Authorization header myself, and find the user with that, but I have a feeling like it has to be implemented in tastypie somewhere already, but I couldn't find it in the docs.

Here's some sample code:

class MyModelResource(ModelResource):

    calculated_field = fields.BooleanField(readonly=True)

    class Meta:
        queryset = MyModel.objects.all()
        resource_name = 'mymodel'
        authentication = ApiKeyAuthentication()     

    def dehydrate_calculated_field(self, bundle):
        user = <get authenticated user somehow>
        return <some boolean that's calculated depending on authenticated user>

I'd like to know if tastypie has some built-in functionality for getting the authenticated user or a proper way to roll my own, based on query string parameters or header fields.


Solution

  • I found the answer to the question, to get the current user I'm doing

    user = bundle.request.user
    

    Thanks to Aidan Ewen for pointing me in the right direction.