diff --git a/README.md b/README.md index cb4a689..09ac580 100644 --- a/README.md +++ b/README.md @@ -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() ``` diff --git a/src/phi/ldap/client.py b/src/phi/ldap/client.py index 77acae5..b5c6e54 100644 --- a/src/phi/ldap/client.py +++ b/src/phi/ldap/client.py @@ -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()