Make LDAP connection thread safe

Add open() and close() methods to LDAP Client.
make-things-work-brutally
crudo 2017-12-17 10:30:43 +01:00
parent da40fc6c20
commit 72b91d123e
2 changed files with 21 additions and 3 deletions

View File

@ -21,10 +21,10 @@ Create a new virtualenv and run `pip install .` inside of it.
>>>
>>> from phi.ldap.client import Client
>>> ldap_client = Client(**ldap_config)
>>>
>>> from phi.ldap.connection import open_connection
>>> open_connection(ldap_client.connection)
>>> ldap_client.open()
>>>
>>> from phi.ldap.commands import whoami
>>> whoami(client)
>>>
>>> ldap_client.close()
```

View File

@ -1,7 +1,9 @@
from threading import Lock
from ldap3.utils.log import set_library_log_detail_level, PROTOCOL
from phi.logging import get_logger
from phi.ldap.connection import make_connection
from phi.ldap.connection import open_connection, close_connection
log = get_logger(__name__)
set_library_log_detail_level(PROTOCOL)
@ -21,9 +23,25 @@ class Client:
self.password = password
self.base_dn = base_dn
self.connection_lock = Lock()
self.connection = make_connection(host=self.host, port=self.port,
encryption=self.encryption,
ciphers=self.ciphers,
validate=self.validate,
username=self.username,
password=self.password)
def open(self):
self.connection_lock.acquire()
if self.connection.closed is True:
open_connection(self.connection)
else:
self.connection_lock.release()
raise Exception("Connection is already open. "
"Cannot open again.")
self.connection_lock.release()
def close(self):
self.connection_lock.acquire()
close_connection(self.connection)
self.connection_lock.release()