ldap_funcs.py 1.8 KB
Newer Older
1
from django.conf import settings
2 3
from ldap3 import Server, Connection, ObjectDef, Writer, SUBTREE
import logging
4

5
logger = logging.getLogger(__name__)
6 7 8 9 10 11 12
server = Server(settings.AUTH_LDAP_SERVER_URI)


def create_user(user, password, firstname, lastname, email):
    conn = Connection(server, settings.AUTH_LDAP_BIND_DN,
                      settings.AUTH_LDAP_BIND_PASSWORD)
    if not conn.bind():
13
        logger.error("conn.bind() returned False. Could not connect.")
14
        raise Exception('Could not connect to LDAP Server')
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
    obj_new_user = ObjectDef(['inetOrgPerson', 'posixAccount'], conn)
    uid = settings.get_max_uid() + 1
    results = True
    while results:
        results = conn.search(
            search_base=settings.LDAP_SEARCH_BASE,
            search_filter=(
                '(&(objectClass=inetOrgPerson)(objectClass=posixAccount)'
                '(objectClass=top)(uidNumber={uidNumber}))'.format(
                    uidNumber=uid
                )
            ),
            search_scope=SUBTREE,
            attributes=['uidNumber'],
        )
        if results:
            logger.debug("{uid} exists. Trying next.".format(uid=uid))
            uid += 1
        else:
            logger.debug("{uid} does not exist. Using it".format(uid=uid))

36
    w = Writer(conn, obj_new_user)
Aatish Neupane's avatar
Aatish Neupane committed
37
    dn = 'uid=%s,ou=users,dc=ungleich,dc=ch' % user
38 39 40 41 42 43
    w.new(dn)
    w[0].givenName = firstname
    w[0].sn = lastname
    w[0].cn = firstname + " " + lastname
    w[0].mail = email
    w[0].userPassword = password
44 45 46
    w[0].gidNumber = settings.IPV6_WORK_USER_GROUP
    w[0].uidNumber = uid
    w[0].homeDirectory = "/home/" + user
47 48 49

    if not w.commit():
        conn.unbind()
50
        logger.error("w.commit() returned False. Could not write user.")
51 52
        raise Exception("Couldn't write user")
    conn.unbind()
Aatish Neupane's avatar
Aatish Neupane committed
53
    return True