Skip to content
Snippets Groups Projects
signals.py 1.45 KiB
Newer Older
from django.conf import settings

import ldap
import ldap.modlist as modlist


def base():
    base = ldap.initialize(LDAP_URL)
    if settings.LDAP_URL.startswith('ldaps://'):
        base.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
        base.set_option(ldap.OPT_X_TLS_NEWCTX, 0)
    base.simple_bind_s(settings.LDAP_USER, settings.LDAP_PASSWORD)

def sync_passwd(base, instance):
    ldap_user = {
        'objectClass': [b'inetOrgPerson', b'organizationalPerson', b'person', b'posixAccount'],
        'uid': instance.uid.encode('ascii'),
        'uidNumber': instance.uid_number,
        'gidNumber': instance.gid_number,
        'homeDirectory': instance.home.encode('utf-8'),
        'loginShell': instance.shell.encode('utf-8'),
        'userPassword': b'{CRYPT}' + instance.password.encode('ascii'),
        'description': instance.gecos.encode('utf-8')
    }
    try:
        old_ldap_user = base.search_s(f'{settings.LDAP_USERS_KEY}={instance.uid},{settings.LDAP_USERS_DN}', ldap.SCOPE_BASE)
    except ldap.NO_SUCH_OBJECT:
        base.add_s(f'{settings.LDAP_USERS_KEY}={instance.uid},{settings.LDAP_USERS_DN}', modlist.addModList(ldap_user))
    else:
        base.modify_s(f'{settings.LDAP_USERS_KEY}={instance.uid},{settings.LDAP_USERS_DN}', modlist.modifyModlist(old_ldap_user, ldap_user))

def pre_save_passwd(sender, instance, using, **kwargs):
    try:
        base = base()
    except ldap.SERVER_DOWN:
        raise
    sync_passwd(base, instance)