fix: avoid triggering password history save on every user save

This commit is contained in:
feng
2026-07-08 14:49:25 +08:00
committed by 老广
parent 8a4b7ea641
commit 34eb21ada6
2 changed files with 16 additions and 9 deletions

View File

@@ -134,6 +134,7 @@ class AuthMixin:
self.date_password_last_updated = timezone.now()
post_user_change_password.send(self.__class__, user=self)
super().set_password(raw_password) # noqa
self._password_changed = True
def set_ssh_key(self, public_key, private_key, **kwargs):
if self.can_update_ssh_key():

View File

@@ -105,19 +105,25 @@ def save_user_email_lookup(sender, instance, **kwargs):
@receiver(post_save, sender=User)
def save_passwd_change(sender, instance: User, **kwargs):
if not getattr(instance, '_password_changed', False):
return
if instance.source != User.Source.local.value or not instance.password:
instance._password_changed = False
return
passwords = UserPasswordHistory.objects \
.filter(user=instance) \
.order_by('-date_created') \
.values_list('password', flat=True)[:settings.OLD_PASSWORD_HISTORY_LIMIT_COUNT]
try:
passwords = UserPasswordHistory.objects \
.filter(user=instance) \
.order_by('-date_created') \
.values_list('password', flat=True)[:settings.OLD_PASSWORD_HISTORY_LIMIT_COUNT]
if instance.password not in list(passwords):
UserPasswordHistory.objects.create(
user=instance, password=instance.password,
date_created=instance.date_password_last_updated
)
if instance.password not in list(passwords):
UserPasswordHistory.objects.create(
user=instance, password=instance.password,
date_created=instance.date_password_last_updated
)
finally:
instance._password_changed = False
def update_role_superuser_if_need(user):