# Path: labshare/backends/authentication/ldap.py
# class LDAPBackend(DjangoLDAPBackend):
# 
#     def update_mail_addresses(self, user):
#         all_saved_email_addresses = [user.email] + [address.email for address in user.email_addresses.all()]
#         all_ldap_email_addresses = user.ldap_user.attrs.get(user.ldap_user.settings.USER_ATTR_MAP['email'], [])
# 
#         all_saved_email_addresses.sort()
#         all_ldap_email_addresses.sort()
#         if all_saved_email_addresses != all_ldap_email_addresses:
#             # something changed and we need to change all addresses
#             user.email = all_ldap_email_addresses[0]
#             user.save()
# 
#             # first: delete all current addresses and then start over
#             EmailAddress.objects.filter(user=user).delete()
# 
#             # second: create extra email address objects for user
#             for address in all_ldap_email_addresses[1:]:
#                 email = EmailAddress.objects.create(user=user, email=address)
#                 email.save()
# 
#     def set_groups_of_user(self, user):
#         user_groups = user.ldap_user.group_dns
#         ldap_user_groups = Group.objects.filter(
#             name__in=[settings.AUTH_LDAP_GROUP_MAP.get(group_name, None) for group_name in user_groups]
#         )
#         user_groups = user.groups.all()
# 
#         if ldap_user_groups.count() == 0:
#             # we need the default group!
#             ldap_user_groups = Group.objects.filter(name=settings.AUTH_LDAP_DEFAULT_GROUP_NAME)
# 
#         if ldap_user_groups.difference(user_groups).count() == 0:
#             # all groups are already correct
#             return
# 
#         # we set the groups of the current to the group names provided by LDAP
#         user.groups.clear()
#         user.save()
#         for group in ldap_user_groups:
#             group.user_set.add(user)
#             group.save()
# 
#     def authenticate_ldap_user(self, ldap_user, password):
#         user = super().authenticate_ldap_user(ldap_user, password)
#         if user is None:
#             return None
# 
#         self.update_mail_addresses(user)
#         self.set_groups_of_user(user)
# 
#         return user


import ldap
from django.conf import settings
from django.contrib.auth.models import User
from django.core.management import BaseCommand
from django_auth_ldap.backend import _LDAPUser
from django_auth_ldap.config import LDAPSearch
from labshare.backends.authentication.ldap import LDAPBackend
        return [user for user in users if len(user.email) > 0 and not hasattr(user, 'device')]

    def handle(self, *args, **options):
        ldap_backend = LDAPBackend()
        dummy_user = _LDAPUser(ldap_backend, username="dummy")
        user_search = LDAPSearch(settings.AUTH_LDAP_USER_DN, ldap.SCOPE_SUBTREE, "(uid=*)")

        user_data = user_search.execute(dummy_user.connection)
        list_of_current_ldap_users = self.process_user_list(user_data)

        known_users = self.filter_django_users(User.objects.all())
        num_deleted_users = 0
        num_imported_users = 0

        for user in known_users:
            if user.username in list_of_current_ldap_users:
                index = list_of_current_ldap_users.index(user.username)
                list_of_current_ldap_users.pop(index)
            else:
                if not user.is_superuser:
                    user.delete()
                    num_deleted_users += 1

        # if there are any usernames left, we need to add new users to the database
        for username in list_of_current_ldap_users:
            django_user = ldap_backend.populate_user(username)
            if django_user is None:
                self.stderr.write(self.style.ERROR(f"Could not create user with username {username}"))
                continue


# Path: labshare/backends/authentication/ldap.py
# class LDAPBackend(DjangoLDAPBackend):
# 
#     def update_mail_addresses(self, user):
#         all_saved_email_addresses = [user.email] + [address.email for address in user.email_addresses.all()]
#         all_ldap_email_addresses = user.ldap_user.attrs.get(user.ldap_user.settings.USER_ATTR_MAP['email'], [])
# 
#         all_saved_email_addresses.sort()
#         all_ldap_email_addresses.sort()
#         if all_saved_email_addresses != all_ldap_email_addresses:
#             # something changed and we need to change all addresses
#             user.email = all_ldap_email_addresses[0]
#             user.save()
# 
#             # first: delete all current addresses and then start over
#             EmailAddress.objects.filter(user=user).delete()
# 
#             # second: create extra email address objects for user
#             for address in all_ldap_email_addresses[1:]:
#                 email = EmailAddress.objects.create(user=user, email=address)
#                 email.save()
# 
#     def set_groups_of_user(self, user):
#         user_groups = user.ldap_user.group_dns
#         ldap_user_groups = Group.objects.filter(
#             name__in=[settings.AUTH_LDAP_GROUP_MAP.get(group_name, None) for group_name in user_groups]
#         )
#         user_groups = user.groups.all()
# 
#         if ldap_user_groups.count() == 0:
#             # we need the default group!
#             ldap_user_groups = Group.objects.filter(name=settings.AUTH_LDAP_DEFAULT_GROUP_NAME)
# 
#         if ldap_user_groups.difference(user_groups).count() == 0:
#             # all groups are already correct
#             return
# 
#         # we set the groups of the current to the group names provided by LDAP
#         user.groups.clear()
#         user.save()
#         for group in ldap_user_groups:
#             group.user_set.add(user)
#             group.save()
# 
#     def authenticate_ldap_user(self, ldap_user, password):
#         user = super().authenticate_ldap_user(ldap_user, password)
#         if user is None:
#             return None
# 
#         self.update_mail_addresses(user)
#         self.set_groups_of_user(user)
# 
#         return user


# Path: labshare/management/commands/sync_users.py
import ldap
from django.conf import settings
from django.contrib.auth.models import User
from django.core.management import BaseCommand
from django_auth_ldap.backend import _LDAPUser
from django_auth_ldap.config import LDAPSearch
from labshare.backends.authentication.ldap import LDAPBackend

        return [user for user in users if len(user.email) > 0 and not hasattr(user, 'device')]

    def handle(self, *args, **options):
        ldap_backend = LDAPBackend()
        dummy_user = _LDAPUser(ldap_backend, username="dummy")
        user_search = LDAPSearch(settings.AUTH_LDAP_USER_DN, ldap.SCOPE_SUBTREE, "(uid=*)")

        user_data = user_search.execute(dummy_user.connection)
        list_of_current_ldap_users = self.process_user_list(user_data)

        known_users = self.filter_django_users(User.objects.all())
        num_deleted_users = 0
        num_imported_users = 0

        for user in known_users:
            if user.username in list_of_current_ldap_users:
                index = list_of_current_ldap_users.index(user.username)
                list_of_current_ldap_users.pop(index)
            else:
                if not user.is_superuser:
                    user.delete()
                    num_deleted_users += 1

        # if there are any usernames left, we need to add new users to the database
        for username in list_of_current_ldap_users:
            django_user = ldap_backend.populate_user(username)
            if django_user is None:
                self.stderr.write(self.style.ERROR(f"Could not create user with username {username}"))
                continue


            ldap_backend.update_mail_addresses(django_user)