Skip to content
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

Adds new refresh tokens to the OutstandingToken db... #865

Closed
Closed
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
1 change: 1 addition & 0 deletions rest_framework_simplejwt/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ def validate(self, attrs: dict[str, Any]) -> dict[str, str]:
refresh.set_jti()
refresh.set_exp()
refresh.set_iat()
refresh.outstand()

data["refresh"] = str(refresh)

Expand Down
24 changes: 24 additions & 0 deletions rest_framework_simplejwt/tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,30 @@ def check_exp(
if claim_time <= current_time - leeway:
raise TokenError(format_lazy(_("Token '{}' claim has expired"), claim))

def outstand(self) -> OutstandingToken:
"""
Ensures this token is included or added in the outstanding token list.
"""
jti = self.payload[api_settings.JTI_CLAIM]
exp = self.payload["exp"]
user_id = self.payload.get(api_settings.USER_ID_CLAIM)
User = get_user_model()
try:
user = User.objects.get(**{api_settings.USER_ID_FIELD: user_id})
except User.DoesNotExist:
user = None

# Ensure outstanding token exists with given jti
return OutstandingToken.objects.get_or_create(
jti=jti,
defaults={
"user": user,
"created_at": self.current_time,
"token": str(self),
"expires_at": datetime_from_epoch(exp),
},
)

@classmethod
def for_user(cls: type[T], user: AuthUser) -> T:
"""
Expand Down
2 changes: 1 addition & 1 deletion tests/test_serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ def test_it_should_blacklist_refresh_token_if_tokens_should_be_rotated_and_black
datetime_to_epoch(now + api_settings.REFRESH_TOKEN_LIFETIME),
)

self.assertEqual(OutstandingToken.objects.count(), 1)
self.assertEqual(OutstandingToken.objects.count(), 2)
self.assertEqual(BlacklistedToken.objects.count(), 1)

# Assert old refresh token is blacklisted
Expand Down
Loading