Search code examples
pythondjangoresttastypie

How to use tastypie for showing contents of model based on client_id in oauth 2.0?


I have a problem where I want to filter model resourse based on a field and show that particular queryset to the requesting client_id.

I am using tastypie v0.10.0 with django 1.6.5 and swagger UI for documentation.

In Example model I have stored information related to all clients and want to show the data belongs to the particular client based on client id. I have filters fields in Example model based on which I can create queryset for particular client.

class Resource(ModelResource):
    class Meta:
        queryset = Example.objects.all()
        resource_name = 'example'
        authorization = DjangoAuthorization()
        detail_allowed_methods = ['get',]
        authentication = OAuth20Authentication()

Please suggest me the best way to implement the above scenario. Thanks in advance.


Solution

  • Here is the solution I came out with.

    import provider.oauth2
    from provider.oauth2.models import AccessToken
    
    
    class Resource(ModelResource):
        # 
        class Meta:
            queryset = Example.objects.all()
            resource_name = 'example'
            authorization = DjangoAuthorization()
            detail_allowed_methods = ['get',]
            always_return_data = True
            authentication = OAuth20Authentication()
    
            key = bundle.request.GET.get('oauth_consumer_key')
            if not key:
                key = bundle.request.POST.get('oauth_consumer_key')
            if not key:
                auth_header_value = bundle.request.META.get('HTTP_AUTHORIZATION')
                if auth_header_value:
                   key = auth_header_value.split(' ')[1]
    
            token = verify_access_token(key)
            >>>>> token.user this contains username
            >>>> come out with the proper conditions through which you can create queryset
            queryset = Example.objects.filter(field=condition)
            return queryset