Commit e244f961 authored by mherrb's avatar mherrb Committed by Élie Bouttier
Browse files

Add purge_ldap.py command to remove inactive / deleted entries from LDAP

parent 19033104
from django.core.management.base import BaseCommand, CommandParser, CommandError
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import User
from django.conf import settings
from adhesions.models import Adhesion, Corporation
from ldap3 import Server, Connection, ALL
from ldap3 import BASE, LEVEL, SUBTREE
from ldap3 import ALL_ATTRIBUTES
import ldap3
class Command(BaseCommand):
help = 'Supprimer de la base LDAP les comptes inactifs ou supprimés de Djadhère.'
def add_arguments(self, parser):
pass
def handle(self, *args, **options):
ldap3.set_config_parameter('DEFAULT_SERVER_ENCODING', 'utf-8')
ldap3.set_config_parameter('DEFAULT_CLIENT_ENCODING', 'utf-8')
server = Server(settings.LDAP_HOST, use_ssl=True, get_info=ALL)
with Connection(server, user=settings.LDAP_MANAGER, password=settings.LDAP_PASSWORD,
auto_bind=ldap3.AUTO_BIND_TLS_BEFORE_BIND) as conn:
conn.search(search_base=settings.LDAP_USERS_BASE,
search_filter='(objectClass=inetOrgPerson)',
search_scope=LEVEL,
attributes=ALL_ATTRIBUTES)
self.stdout.write(self.style.SUCCESS('{} users founnd in LDAP.'.format(len(conn.entries))))
for ldap_user in conn.entries:
delete = False;
# print(ldap_user.uid.value)
try:
adh = Adhesion.objects.get(pk=ldap_user.uid.value)
except Adhesion.DoesNotExist:
self.stdout.write(self.style.ERROR("Adhesion ADT{} inexistante"\
.format(ldap_user.uid.value)))
delete = True
#if adh.active is None:
# self.stdout.write(self.style.ERROR("Adhesion ADT{} {} unknown"\
# .format(adh.pk, ldap_user.cn.value)))
# delete = False
if adh.active == False:
self.stdout.write(self.style.ERROR("Adhesion ADT{} {} inactive"\
.format(adh.pk, ldap_user.cn.value)))
delete = True
if delete:
conn.delete(ldap_user.entry_dn)
if conn.result['result'] != 0:
self.stdout.write(self.style.ERROR("{}: {}"\
.format(ldap_user.entry_dn,
conn.result['description'])))
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment