Skip to content

Commit 21b7066

Browse files
DenisKoledajohn-westcott-iv
authored andcommitted
Fix race condition in OAuth2AccessToken.is_valid() causing HTTP 500
Replace save(update_fields=['last_used']) with QuerySet.update() to avoid DatabaseError when concurrent requests try to update the same token's last_used timestamp. The previous implementation could fail with: django.db.utils.DatabaseError: Save with update_fields did not affect any rows. This happened because between exists() check and save() call, another process could modify the row, causing save() to affect 0 rows and raise an exception. QuerySet.update() handles this gracefully by simply returning 0 affected rows without raising an error.
1 parent e88d917 commit 21b7066

1 file changed

Lines changed: 1 addition & 2 deletions

File tree

ansible_base/oauth2_provider/models/access_token.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,7 @@ def is_valid(self, scopes=None):
8282
self.last_used = now()
8383

8484
def _update_last_used():
85-
if OAuth2AccessToken.objects.filter(pk=self.pk).exists():
86-
self.save(update_fields=['last_used'])
85+
OAuth2AccessToken.objects.filter(pk=self.pk).update(last_used=self.last_used)
8786

8887
connection.on_commit(_update_last_used)
8988
return valid

0 commit comments

Comments
 (0)