Home > OS >  Django rest framework custom Token (send User object with the token access and refress)
Django rest framework custom Token (send User object with the token access and refress)

Time:07-01

I am trying to create a custom token to send the user object alongside the access and refresh.

Note: if there is another way to do it please tell me about it. Starting the token code from scratch is an option.

token_serializer.py

from rest_framework_simplejwt.serializers import (
    TokenObtainSerializer,
    RefreshToken,
    api_settings,
    update_last_login,
)
from django.core import serializers
from app.models.user import AppUser


class TokenSerializer(TokenObtainSerializer):
    @classmethod
    def get_token(cls, user):
        return RefreshToken.for_user(user)

    def validate(self, attrs):
        data = super().validate(attrs)

        refresh = self.get_token(self.user)

        data["refresh"] = str(refresh)
        data["access"] = str(refresh.access_token)

        @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
        serialized_app_user = serializers.serialize("json", AppUser)
        app_user = serialized_app_user .objects.filter(pk=self.user.id).first()
        @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

        
        if app_user:
            data["user"] = app_user
        else:
            data["user"] = None

        if api_settings.UPDATE_LAST_LOGIN:
            update_last_login(None, self.user)

        return data


token_view.py

from rest_framework_simplejwt.views import TokenViewBase
from app.api.serializers import TokenSerializer


class TokenView(TokenViewBase):
    serializer_class = TokenSerializer

This code led to this error: 'ModelBase' object is not iterable

The line which causes this error is

serialized_app_user = serializers.serialize("json", AppUser)

But I added it because without it the following error happens: Object of type AppUser is not JSON serializable

CodePudding user response:

If you really need the user information in token obtain endpoint, then you will need to serialize the AppUser object:

...
from rest_framework import serializers
from app.models.user import AppUser


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = AppUser
        fields = '__all__'  # or any specific fields


class TokenSerializer(TokenObtainSerializer):
    def validate(self, attrs):
        ...
        app_user = serialized_app_user .objects.filter(pk=self.user.id).first()
        if app_user:
            data["user"] = UserSerializer(app_user).data
        else:
            data["user"] = None
  • Related