djangorestframework-simplejwt
djangorestframework-simplejwt copied to clipboard
Prevent `DoesNotExist` exception in TokenRefreshSerializer
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.
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.
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)