ldap_funcs.py 868 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
from django.conf import settings
from ldap3 import Server, ServerPool, Connection, ObjectDef, AttrDef, Reader, Writer

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():
        raise Exception('Could not connect to LDAP Server')
    obj_new_user = ObjectDef(
        ['inetOrgPerson'], conn)
    w = Writer(conn, obj_new_user)
    dn = 'uid=%s,ou=users,dc=example,dc=com' % user
    w.new(dn)
    w[0].givenName = firstname
    w[0].sn = lastname
    w[0].cn = firstname + " " + lastname
    w[0].mail = email
    w[0].userPassword = password

    if not w.commit():
        conn.unbind()
        raise Exception("Couldn't write user")
    conn.unbind()
    return True