Skip to content
Snippets Groups Projects
Select Git revision
2 results Searching

syncldapusers.py

Blame
  • syncldapusers.py 1.12 KiB
    import logging
    
    from django.core.management.base import BaseCommand
    from django.contrib.auth import get_user_model
    import django.conf
    from django_mailman3.lib.mailman import get_mailman_user
    from allauth.account.models import EmailAddress
    
    from postorius_ldap_membership_management.utils import get_ldap_connection, execute_ldap_search_without_hiding_errors, populate_user
    
    logger = logging.getLogger(__name__)
    
    class Command(BaseCommand):
    	can_import_settings = True
    	help = 'Synchronize users from a LDAP server'
    
    	def handle(self, *args, **options):
    		ldap_conn = get_ldap_connection()
    		results = execute_ldap_search_without_hiding_errors(django.conf.settings.AUTH_LDAP_USER_SEARCH_ALL_NAME, ldap_conn)
    		ldap_usernames = [list(attr.values())[0][0] for dn, attr in results]
    		for username in ldap_usernames:
    			logger.warning(f'creating or updating {username}')
    			# populate_user ignores all errors
    			populate_user(username)
    
    		users = get_user_model().objects.filter(is_active=True)
    		for user in users:
    			if not user.username in ldap_usernames:
    				logger.warning(f'deactivating {user.username}')
    				user.is_active = False
    				user.save()