phi/src/phi/ldap/client.py

60 lines
2.0 KiB
Python
Raw Normal View History

from threading import Lock
2017-12-21 13:44:54 +01:00
from ldap3.utils.log import set_library_log_detail_level, PROTOCOL
2017-12-16 23:03:03 +01:00
from phi.logging import get_logger
from phi.ldap.connection import make_connection
from phi.ldap.connection import open_connection, close_connection
2017-12-16 23:03:03 +01:00
log = get_logger(__name__)
2017-12-21 13:44:54 +01:00
set_library_log_detail_level(PROTOCOL)
2017-12-16 23:03:03 +01:00
class Client:
2017-12-21 13:44:54 +01:00
def __init__(self,
host=None, port=389,
encryption=None, ciphers=None, validate=False, ca_certs=None,
username=None, password=None,
base_dn=None,
attribute_id='uid', attribute_mail='mail'):
log.info("Initializing LDAP Client.")
2017-12-21 13:44:54 +01:00
2017-12-16 23:03:03 +01:00
self.host = host
self.port = port
2017-12-21 13:44:54 +01:00
2017-12-16 23:03:03 +01:00
self.encryption = encryption
self.ciphers = ciphers
self.validate = validate
self.ca_certs = ca_certs
2017-12-21 13:44:54 +01:00
2017-12-16 23:03:03 +01:00
self.username = username
self.password = password
2017-12-21 13:44:54 +01:00
2017-12-16 23:03:03 +01:00
self.base_dn = base_dn
2017-12-21 13:44:54 +01:00
self.attribute_id = attribute_id
self.attribute_mail = attribute_mail
self.connection_lock = Lock()
2017-12-16 23:03:03 +01:00
self.connection = make_connection(host=self.host, port=self.port,
encryption=self.encryption,
ciphers=self.ciphers,
validate=self.validate,
ca_certs=self.ca_certs,
2017-12-16 23:03:03 +01:00
username=self.username,
password=self.password)
def open(self):
self.connection_lock.acquire()
if self.connection.closed is True:
open_connection(self.connection)
self.connection_lock.release()
else:
self.connection_lock.release()
2017-12-21 13:44:54 +01:00
raise Exception("Trying to open a connection, "
"but it is already open.")
def close(self):
self.connection_lock.acquire()
close_connection(self.connection)
self.connection_lock.release()