Skip to content

Commit

Permalink
Merge pull request #3861 from allegro/fix-ldap-sync-bytes
Browse files Browse the repository at this point in the history
Fix ldap sync when bytes received
  • Loading branch information
hipek8 authored Nov 4, 2024
2 parents 021b3e9 + 4927a0c commit a40a030
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
2 changes: 1 addition & 1 deletion requirements/prod_ldap.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
-r prod.txt
django-auth-ldap==1.2.7
django-auth-ldap==1.6.1
26 changes: 16 additions & 10 deletions src/ralph/accounts/management/commands/ldap_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,20 @@
ldap_module_exists = False


def decode_nested_dict(data):
if isinstance(data, dict):
return {key: decode_nested_dict(value) for key, value in data.items()}
elif isinstance(data, list):
return [decode_nested_dict(element) for element in data]
elif isinstance(data, bytes):
try:
return data.decode('utf-8')
except UnicodeDecodeError:
return data
else:
return data


def _truncate(field_key, field_name, ldap_dict):
"""
Truncate user's field when it's longer then default django value, which is
Expand Down Expand Up @@ -274,16 +288,8 @@ def populate_users(self):
"""Load users from ldap and populate them. Returns number of users."""
synced = 0
for user_dn, ldap_dict in self._get_users():
if ldap_dict.get('c'):
try:
ldap_dict['c'] = [v.decode('utf-8') for v in ldap_dict['c']]
except UnicodeDecodeError:
logger.error(
"Can't decode country %s for user %s",
ldap_dict['c'],
user_dn
)
continue
# decode bytes to str
ldap_dict = decode_nested_dict(ldap_dict)
_truncate('sn', 'last_name', ldap_dict)
user = self._create_or_update_user(user_dn, ldap_dict)
self.nested_groups.handle(user)
Expand Down

0 comments on commit a40a030

Please sign in to comment.