djangorestframework-simplejwt icon indicating copy to clipboard operation
djangorestframework-simplejwt copied to clipboard

Prevent `DoesNotExist` exception in TokenRefreshSerializer

Open yuekui opened this issue 10 months ago • 2 comments

For deleted users, they should be treated the same as when no active user is found. This DoesNotExist exception was introduced in the previous version.

yuekui avatar Feb 06 '25 20:02 yuekui

I've hit this as well.

As a workaround, I'm using a wrapper kinda like this:

class TokenRefreshSerializerFixed(TokenRefreshSerializer):
    def validate(self, attrs):
        user_id = self.token_class(attrs['refresh'].payload.get(api_settings.USER_ID_CLAIM, None)
        if user_id:
            try:
                get_user_model().objects.get(**{api_settings.USER_ID_FIELD: user_id})
            except get_user_model().DoesNotExist:
                raise AuthenticationFailed(
                    self.error_messages['no_active_account'],
                    'no_active_account',
                )

        return super().validate(attrs)

It's a bit more crude than the approach in PR, but it works as a simple shim until a proper fix lands.

mjbogusz avatar Mar 14 '25 17:03 mjbogusz

Also has this error, guess I will use suggested wrapper by @mjbogusz (btw you missed closing bracket)

from rest_framework.exceptions import AuthenticationFailed
from rest_framework_simplejwt.serializers import TokenRefreshSerializer, api_settings

class TokenRefreshSerializerFixed(TokenRefreshSerializer):
    def validate(self, attrs):
        user_id = self.token_class(attrs['refresh'].payload.get(api_settings.USER_ID_CLAIM, None))
        if user_id:
            try:
                get_user_model().objects.get(**{api_settings.USER_ID_FIELD: user_id})
            except get_user_model().DoesNotExist:
                raise AuthenticationFailed(
                    self.error_messages['no_active_account'],
                    'no_active_account',
                )

        return super().validate(attrs)

verhovensky avatar Mar 21 '25 13:03 verhovensky