32 lines
1001 B
Python
32 lines
1001 B
Python
from ldap3 import Connection, ObjectDef, Reader
|
|
from ldap3.core.exceptions import LDAPSocketSendError
|
|
|
|
class Ldap:
|
|
def __init__(self, conf):
|
|
self.base = conf['base_dn']
|
|
self.url = conf['url']
|
|
self.__setup_connection()
|
|
|
|
def __setup_connection(self):
|
|
self.conn = Connection(self.url, auto_bind=True)
|
|
self.pdef = ObjectDef('inetOrgPerson', self.conn)
|
|
|
|
def search(self, term):
|
|
r = Reader(self.conn, self.pdef, self.base, term)
|
|
try:
|
|
r.search()
|
|
except LDAPSocketSendError as e:
|
|
self.__setup_connection()
|
|
return self.search(term)
|
|
return r
|
|
|
|
def get_name(self, uid):
|
|
r = self.search('uid:'+uid)
|
|
if len(r) == 0:
|
|
m = f'User "{uid}" not found in LDAP ({self.url})'
|
|
raise Exception(m)
|
|
if len(r) != 1:
|
|
m = f'Multiple hits when searching for "{uid}" in LDAP ({self.url})'
|
|
raise Exception(m)
|
|
return str(r[0].cn)
|