indexOutOfBounds
indexOutOfBounds

Reputation: 571

Django Rest API Djoser Refresh and Access Token Problem

I am trying to get access and refresh tokens when the user registers using the /auth/users/ endpoint.

I have already extended the serializer and it is showing all custom fields. It registers the user successfully and returns the result as follows:

{
    "mobile": "12345",
    "driving_id": "478161839",
    "full_name": "John Doe",

} 

This is where I would want to have an access and refresh token. I read that djoser uses django simple jwt library to provide access and refresh tokens. This is the function to create the tokens manually which I am able to do but the only thing I am not understanding is where to return the data with other details.

from rest_framework_simplejwt.tokens import RefreshToken

def get_tokens_for_user(user):
    refresh = RefreshToken.for_user(user)

    return {
        'refresh': str(refresh),
        'access': str(refresh.access_token),
    }

Upvotes: 2

Views: 1665

Answers (1)

indexOutOfBounds
indexOutOfBounds

Reputation: 571

I solved it but I do not know if it is the best way or not. I imported the userview set from djoser.views and then overrode the create method. I fetch the user and then create JWT tokens for it, add it to the response dict and return it.

from rest_framework import status
from djoser.views import UserViewSet
from djoser import signals
from djoser.compat import get_user_email

from rest_framework_simplejwt.tokens import RefreshToken


class CustomRegistrationView(UserViewSet):

    def perform_create(self, serializer):
        user = serializer.save()
        signals.user_registered.send(
            sender=self.__class__, user=user, request=self.request
        )

        context = {"user": user}
        to = [get_user_email(user)]
        if settings.SEND_ACTIVATION_EMAIL:
            settings.EMAIL.activation(self.request, context).send(to)
        elif settings.SEND_CONFIRMATION_EMAIL:
            settings.EMAIL.confirmation(self.request, context).send(to)


    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        response_data = serializer.data

        user = User.objects.get(username = response_data['username'])
        refresh = RefreshToken.for_user(user)
        response_data['refresh'] = str(refresh)
        response_data['access'] = str(refresh.access_token)

        return Response(response_data, status=status.HTTP_201_CREATED, headers=headers)

Upvotes: 4

Related Questions