Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override the authToken views in Django Rest

I am using the token based Authentication in Django and need to add User object in addition to token being returned.

How do I override this class view ? Where do I need add this class and make the changes ? Currently this is found in the rest_framework package and I don't want to modify the library .

from rest_framework import parsers, renderers
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.response import Response
from rest_framework.views import APIView


class ObtainAuthToken(APIView):
    throttle_classes = ()
    permission_classes = ()
    parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
    renderer_classes = (renderers.JSONRenderer,)
    serializer_class = AuthTokenSerializer
    print "dasdsa"

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        return Response({'token': token.key})


obtain_auth_token = ObtainAuthToken.as_view()
like image 882
Vidya Avatar asked Feb 08 '16 09:02

Vidya


2 Answers

From docs.

First that you need is to extend the ObtainAuthToken class.

# views.py

from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response

class CustomAuthToken(ObtainAuthToken):

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data,
                                       context={'request': request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        return Response({
            'token': token.key,
            'user_id': user.pk,
            'email': user.email
        })

And after this add the CustomAuthToken class to your urls.py like view

# urls.py
from django.urls import path
from . import views

urlpatterns += [
    path(r'api-token-auth/', views.CustomAuthToken.as_view())
]
like image 130
Druta Ruslan Avatar answered Oct 05 '22 14:10

Druta Ruslan


You should extend your CustomClass from AuthToken, the route default url to your CustomClass:

from rest_framework_jwt.views import ObtainJSONWebToken

class JSONWebTokenAPIOverride(ObtainJSONWebToken):
    """
    Override JWT
    """
    def post(self, request):
        # Do whatever you want

Then in your urls.py:

url(
    r'^api-auth$',
    cache_page(0)(views.JSONWebTokenAPIOverride.as_view())
)

I hope it helps

like image 33
Moe Far Avatar answered Oct 05 '22 14:10

Moe Far