Skip to content

Commit 930cf85

Browse files
authored
fix: Avoid DoesNotExist exception in TokenRefreshSerializer (#861)
* Check user before passing it to the rule * Use `Optional` in the type annotation for the default user authentication rule since the user can be `None`
1 parent 6c45510 commit 930cf85

File tree

3 files changed

+9
-9
lines changed

3 files changed

+9
-9
lines changed

rest_framework_simplejwt/authentication.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ def get_user(self, validated_token: Token) -> AuthUser:
171171
JWTTokenUserAuthentication = JWTStatelessUserAuthentication
172172

173173

174-
def default_user_authentication_rule(user: AuthUser) -> bool:
174+
def default_user_authentication_rule(user: Optional[AuthUser]) -> bool:
175175
# Prior to Django 1.10, inactive users could be authenticated with the
176176
# default `ModelBackend`. As of Django 1.10, the `ModelBackend`
177177
# prevents inactive users from authenticating. App designers can still

rest_framework_simplejwt/serializers.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -112,12 +112,13 @@ def validate(self, attrs: dict[str, Any]) -> dict[str, str]:
112112
refresh = self.token_class(attrs["refresh"])
113113

114114
user_id = refresh.payload.get(api_settings.USER_ID_CLAIM, None)
115-
if user_id and (
116-
user := get_user_model().objects.get(
117-
**{api_settings.USER_ID_FIELD: user_id}
115+
if user_id:
116+
user = (
117+
get_user_model()
118+
.objects.filter(**{api_settings.USER_ID_FIELD: user_id})
119+
.first()
118120
)
119-
):
120-
if not api_settings.USER_AUTHENTICATION_RULE(user):
121+
if not user or not api_settings.USER_AUTHENTICATION_RULE(user):
121122
raise AuthenticationFailed(
122123
self.error_messages["no_active_account"],
123124
"no_active_account",

tests/test_serializers.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
from django.conf import settings
66
from django.contrib.auth import get_user_model
7-
from django.core import exceptions as django_exceptions
87
from django.test import TestCase, override_settings
98
from rest_framework import exceptions as drf_exceptions
109

@@ -286,10 +285,10 @@ def test_it_should_raise_error_for_deleted_users(self):
286285

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

289-
with self.assertRaises(django_exceptions.ObjectDoesNotExist) as e:
288+
with self.assertRaises(drf_exceptions.AuthenticationFailed) as e:
290289
s.is_valid()
291290

292-
self.assertIn("does not exist", str(e.exception))
291+
self.assertIn("No active account", str(e.exception))
293292

294293
def test_it_should_raise_error_for_inactive_users(self):
295294
refresh = RefreshToken.for_user(self.user)

0 commit comments

Comments
 (0)