Associate ldap_dn on a first User() login

To avoid calling the user.save() on every single login (PR#9703)
we can check if the user.profile is available. For new users,
accessing the user.profile throws an ValueError exception which
is capture on this fix.

Example:
----
>>> _ = user.profile
*** ValueError: save() prohibited to prevent data loss due to unsaved related object 'user'.
>>> User.objects.filter(username=user.username).count()
0

This way, the user.save() gets called for brand users and will get the
ldap_dn associated as expected.
This commit is contained in:
Marcelo Moreira de Mello 2021-08-29 22:02:00 -04:00
parent e9b7f9ac40
commit e23e634974

View File

@ -395,10 +395,17 @@ def on_populate_user(sender, **kwargs):
remove = bool(team_opts.get('remove', True))
_update_m2m_from_groups(user, ldap_user, team.member_role.members, users_opts, remove)
# Check if user.profile is available, otherwise force user.save()
try:
_ = user.profile
except ValueError:
force_user_update = True
finally:
if force_user_update:
user.save()
# Update user profile to store LDAP DN.
if force_user_update:
user.save()
profile = user.profile
if profile.ldap_dn != ldap_user.dn:
profile.ldap_dn = ldap_user.dn
profile.save()
profile = user.profile
if profile.ldap_dn != ldap_user.dn:
profile.ldap_dn = ldap_user.dn
profile.save()