from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from apps.captcha_app import exceptions as captcha_exception from rest_framework_simplejwt.settings import api_settings from django.contrib.auth.models import update_last_login from rest_framework import exceptions from django.core.cache import cache from typing import Any class CustomizedTokenObtainPairSerializer(TokenObtainPairSerializer): # noqa """ customize jwt token 'set new variables in generated token' """ def validate(self, attrs: dict[str, Any]) -> dict[str, str]: """ override validate method to add more conditions """ captcha_code, captcha_key = attrs['captcha_code'], attrs['captcha_key'] if captcha_code != cache.get(captcha_key) or captcha_code not in attrs.keys(): raise captcha_exception.CaptchaFailed() data = super().validate(attrs) refresh = self.get_token(self.user) data["refresh"] = str(refresh) data["access"] = str(refresh.access_token) data["otp_status"] = self.user.otp_status if not self.user.is_active: raise exceptions.AuthenticationFailed( self.error_messages["no_active_account"], "no_active_account", ) if api_settings.UPDATE_LAST_LOGIN: update_last_login(None, self.user) return data @classmethod def get_token(cls, user): """ set variables in encoded jwt token """ token = super().get_token(user) # Add custom claims token['name'] = user.username return token