Skip to content

fix: Avoid DoesNotExist exception in TokenRefreshSerializer #861

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion rest_framework_simplejwt/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def get_user(self, validated_token: Token) -> AuthUser:
JWTTokenUserAuthentication = JWTStatelessUserAuthentication


def default_user_authentication_rule(user: AuthUser) -> bool:
def default_user_authentication_rule(user: Optional[AuthUser]) -> bool:
# Prior to Django 1.10, inactive users could be authenticated with the
# default `ModelBackend`. As of Django 1.10, the `ModelBackend`
# prevents inactive users from authenticating. App designers can still
Expand Down
11 changes: 6 additions & 5 deletions rest_framework_simplejwt/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,12 +112,13 @@ def validate(self, attrs: dict[str, Any]) -> dict[str, str]:
refresh = self.token_class(attrs["refresh"])

user_id = refresh.payload.get(api_settings.USER_ID_CLAIM, None)
if user_id and (
user := get_user_model().objects.get(
**{api_settings.USER_ID_FIELD: user_id}
if user_id:
user = (
get_user_model()
.objects.filter(**{api_settings.USER_ID_FIELD: user_id})
.first()
Comment on lines +116 to +119
Copy link
Member

@Andrew-Chen-Wang Andrew-Chen-Wang Feb 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this may not be expected since the USER_AUTHENTICATION_RULE expects a user object, not None

def default_user_authentication_rule(user: AuthUser) -> bool:

suggestion: simply check if the user exists OR check authentication rule does not pass rather than solely rely on the authentication rule

Copy link
Author

@yuekui yuekui Feb 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the USER_AUTHENTICATION_RULE method already performs the user is not None check, would adding another check outside the method introduce unnecessary code duplication?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yea, the problem is the initial typing was typed assuming the user object is valid...

I mean that's my fault for not checking that. I guess this is fine, but we should also update the typing for the authentication rule?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense, updated

)
):
if not api_settings.USER_AUTHENTICATION_RULE(user):
if not user or not api_settings.USER_AUTHENTICATION_RULE(user):
raise AuthenticationFailed(
self.error_messages["no_active_account"],
"no_active_account",
Expand Down
5 changes: 2 additions & 3 deletions tests/test_serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core import exceptions as django_exceptions
from django.test import TestCase, override_settings
from rest_framework import exceptions as drf_exceptions

Expand Down Expand Up @@ -286,10 +285,10 @@ def test_it_should_raise_error_for_deleted_users(self):

s = TokenRefreshSerializer(data={"refresh": str(refresh)})

with self.assertRaises(django_exceptions.ObjectDoesNotExist) as e:
with self.assertRaises(drf_exceptions.AuthenticationFailed) as e:
s.is_valid()

self.assertIn("does not exist", str(e.exception))
self.assertIn("No active account", str(e.exception))

def test_it_should_raise_error_for_inactive_users(self):
refresh = RefreshToken.for_user(self.user)
Expand Down
Loading