from django.conf import settings from ldap3 import Server, Connection, ObjectDef, Writer, SUBTREE import logging logger = logging.getLogger(__name__) server = Server(settings.AUTH_LDAP_SERVER_URI) def create_user(user, password, firstname, lastname, email): logger.debug("In create_user") conn = Connection(server, settings.AUTH_LDAP_BIND_DN, settings.AUTH_LDAP_BIND_PASSWORD) if not conn.bind(): logger.error("conn.bind() returned False. Could not connect.") raise Exception('Could not connect to LDAP Server') obj_new_user = ObjectDef(['inetOrgPerson', 'posixAccount'], conn) uidNumber = get_max_uid() + 1 logger.debug("uidNumber={uidNumber}".format(uidNumber=uidNumber)) results = True while results: results = conn.search( search_base=settings.LDAP_CUSTOMER_DN, search_filter=( '(&(objectClass=inetOrgPerson)(objectClass=posixAccount)' '(objectClass=top)(uidNumber={uidNumber}))'.format( uidNumber=uidNumber ) ), search_scope=SUBTREE, attributes=['uidNumber'], ) if results: logger.debug("{uid} exists. Trying next.".format(uid=uidNumber)) uidNumber += 1 logger.debug("{uid} does not exist. Using it".format(uid=uidNumber)) set_max_uid(uidNumber) w = Writer(conn, obj_new_user) dn = 'uid=%s,%s' % (user, settings.LDAP_CUSTOMER_DN) w.new(dn) w[0].givenName = firstname w[0].sn = lastname w[0].cn = firstname + " " + lastname w[0].mail = email w[0].userPassword = password w[0].gidNumber = settings.LDAP_IPV6_WORK_USER_GROUP w[0].uidNumber = uidNumber w[0].homeDirectory = "/home/" + user if not w.commit(): conn.unbind() logger.error("w.commit() returned False. Could not write user.") raise Exception("Couldn't write user") logger.debug("Created user {user} successfully.".format(user=user)) conn.unbind() return True 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(str(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: try: return_value = int(handler.read()) except ValueError as ve: logger.error( "Error reading int value from {}. {}" "Returning default value {} instead".format( settings.LDAP_MAX_UID_PATH, str(ve), settings.LDAP_DEFAULT_START_UID ) ) return_value = settings.LDAP_DEFAULT_START_UID return return_value except FileNotFoundError as fnfe: logger.error("File not found : " + str(fnfe)) retrun_value = settings.LDAP_DEFAULT_START_UID logger.error("So, returning UID={}".format(retrun_value)) return retrun_value