# Handles queries to the LDAP backend
# Reads the LDAP server configuration from a JSON file

import json
import ldap

# TODO:
# 1. Queries to get current list of users in LDAP database
# 2. Compare with local list of users to see if there are any not processed
# 3. Run external script (add script variables in config.json) if there are new users
# 4. Update local list with the new users
# 5. Return meaningful status message

# Boolean to keep track of if the configuration file has been loaded
first_connect = True
# The default config filename
config_file = 'config.json'

# Load the configuration from file
def load_config():
    with open(config_file, 'r') as f:
        config = json.load(f)
    ldap_server = config['ldap_server']
    ldap_version = config['ldap_version']
    ldap_password = config['ldap_password']
    ldap_user = config['ldap_user']

# Connect to the LDAP backend
def connect():
    # Load the config if it has not been loaded
    if first_connect:
        load_config()
        first_connect = False
    # Connect to the backend
    l = ldap.initialize('ldap://' + ldap_server)
    try:
        l.protocol_version = ldap_version
        l.simple_bind_s(ldap_user, ldap_password)
        valid = True
    except ldap.INVALID_CREDENTIALS:
        print("Invalid login credentials")
        sys.exit(-1)
    except ldap.LDAPError as e:
        if type(e.message) == dict and e.message.has_key('desc'):
            print(e.message['desc'])
        else:
            print(e)
        sys.exit(-2)

@@ -1056,17 +1056,30 @@
 end%0A    
-l
+backend_server
  = ldap.
@@ -1131,17 +1131,30 @@
         
-l
+backend_server
 .protoco
@@ -1186,17 +1186,30 @@
         
-l
+backend_server
 .simple_
@@ -1262,16 +1262,46 @@
  = True%0A
+        return backend_server%0A
     exce
@@ -1584,8 +1584,778 @@
 xit(-2)%0A
+%0A# Query the LDAP backend%0Adef find_users(backend_server, base_dn, search_scope, search_filter, search_attribute):%0A    # Query result asynchronus%0A    ldap_result_id = backend_server.search(basedn, search_scope, search_filter, search_attribute)%0A    result_set = %5B%5D%0A    try:%0A        while 1:%0A            result_type, result_data = backend_server.result(ldap_result_id, 0)%0A            if (result_data == %5B%5D):%0A                break%0A            else:%0A                if result_type == ldap.RES_SEARCH_ENTRY:%0A                    result_set.append(result_data)%0A        return result_set%0A    except ldap.LDAPError as e:%0A        if type(e.message) == dict and e.message.has_key('desc'):%0A            print(e.message%5B'desc'%5D)%0A        else:%0A            print(e)%0A        sys.exit(-2)%0A

Add generic query structure to the LDAP backend