Hamster
Hamster

Reputation: 680

Python Django Rest Framework authentication

I am attempting to authenticate a GUID that is being passed in the url via the web API interface. However I am not managing to pass GUID to my Authenticate class.

Note: by authenticating I mean making sure it is a valid GUID

My urls.py:

 url(r'^customer_address/(?P<guid>[a-z0-9-]+)/(?P<address_id>[a-z0-9-]+)/$',
    views.CustomerAddressView.as_view()),

My views.py:

class CustomerAddressView(generics.RetrieveAPIView):
    lookup_field = "address_id"       
    queryset = CustomerAddress.objects.all()
    serializer_class = CustomerAddressSerializer     

My settings.py:

REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'customer.authenticate.Authenticate',
        ),
         'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
         )
}

Authenticate class in my customer app looks like this:

class Authenticate(authentication.BaseAuthentication) :
    def authenticate(self, request):

        request = request._request                               
        guid = getattr(request, 'guid', None)


        my_logger.debug(guid)


        if not guid:
            my_logger.debug('There is no guid!')
            return None


        try:
            user = Customer.objects.get(guid=guid,brand=1)
        except Customer.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user')

        return None

And the request looks like this:

enter image description here

Problem: I like to retrieve a GUID in class Authenticate and make sure it is valid. At the moment I keep getting the error you see in the screenshot and my logs read: 'There is no guid!'

How can I pass guid from request to the Authenticate class?

Thanks

Upvotes: 1

Views: 183

Answers (1)

Rahul Gupta
Rahul Gupta

Reputation: 47906

You can do this:

class Authenticate(authentication.BaseAuthentication) :
    def authenticate(self, request):

        request = request._request        

        # This is a bit hacky way to get value of guid                        
        guid = request.path.split('/')[-3]

        my_logger.debug(guid)

        if not guid:
            my_logger.debug('There is no guid!')
        return None

        try:
            user = Customer.objects.get(guid=guid,brand=1)
        except Customer.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user')

    return None

This is a bit hacky since i am trying to access guid by splitting request.path about '/' and access the third-last index of the list obtained after splitting.

I have checked, self has no access to the kwargs which we normally get in DRF views, so we can't access kwargs here.

Another solution would be to pass kwargs in the DRF view explicitly when authenticate() is called by overriding the authentication process of DRF.

Upvotes: 1

Related Questions