ldap_funcs.py 2.75 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
server = Server(settings.AUTH_LDAP_SERVER_URI)


def create_user(user, password, firstname, lastname, email):
PCoder's avatar
PCoder committed
10
    logger.debug("In create_user")
11 12 13
    conn = Connection(server, settings.AUTH_LDAP_BIND_DN,
                      settings.AUTH_LDAP_BIND_PASSWORD)
    if not conn.bind():
14
        logger.error("conn.bind() returned False. Could not connect.")
15
        raise Exception('Could not connect to LDAP Server')
PCoder's avatar
PCoder committed
16

17
    obj_new_user = ObjectDef(['inetOrgPerson', 'posixAccount'], conn)
PCoder's avatar
PCoder committed
18 19
    uidNumber = settings.get_max_uid() + 1
    logger.debug("uidNumber={uidNumber}".format(uidNumber=uidNumber))
20 21 22 23 24 25 26
    results = True
    while results:
        results = conn.search(
            search_base=settings.LDAP_SEARCH_BASE,
            search_filter=(
                '(&(objectClass=inetOrgPerson)(objectClass=posixAccount)'
                '(objectClass=top)(uidNumber={uidNumber}))'.format(
PCoder's avatar
PCoder committed
27
                    uidNumber=uidNumber
28 29 30 31 32 33
                )
            ),
            search_scope=SUBTREE,
            attributes=['uidNumber'],
        )
        if results:
PCoder's avatar
PCoder committed
34 35
            logger.debug("{uid} exists. Trying next.".format(uid=uidNumber))
            uidNumber += 1
36
        else:
PCoder's avatar
PCoder committed
37
            logger.debug("{uid} does not exist. Using it".format(uid=uidNumber))
38

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

    if not w.commit():
        conn.unbind()
53
        logger.error("w.commit() returned False. Could not write user.")
54
        raise Exception("Couldn't write user")
PCoder's avatar
PCoder committed
55
    logger.debug("Created user {user} successfully.".format(user=user))
56
    conn.unbind()
Aatish Neupane's avatar
Aatish Neupane committed
57
    return True
PCoder's avatar
PCoder committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83


def set_max_uid(max_uid):
    """
    a utility function to save max_uid value to a file

    :param max_uid: an integer representing the max uid
    :return:
    """
    with open(settings.LDAP_MAX_UID_PATH, 'w+') as handler:
        handler.write(max_uid)


def get_max_uid():
    """
    A utility function to read the max uid value that was previously set

    :return: An integer representing the max uid value that was previously set
    """
    try:
        with open(settings.LDAP_MAX_UID_PATH, 'r+') as handler:
            return int(handler.read())
    except FileNotFoundError as fnfe:
        logger.error("File not found : " + str(fnfe))
        ret = settings.LDAP_DEFAULT_START_UID
        logger.error("So, returing UID={}".format(ret))