py.lib

Yohn Y. 2020-12-25 Parent:cab7fedf8432 Child:84b54a8a6d4c

16:6c38121a0c86 Go to Latest

py.lib/db/ldap.py

+ Добавления инструмента миграций

History
1 # coding: utf-8
3 from ldap3 import Server, Connection, SIMPLE, SUBTREE
5 LDAP_PAGE=1000
7 class LdapError(Exception): pass
9 class LdapRes():
10 def __init__(self, dn, attrib):
11 self.dn = dn
12 self.attr = attrib
14 def __getitem__(self, item):
15 return self.attr[item]
17 def __iter__(self):
18 return iter(self.attr)
20 def __repr__(self):
21 return '<LdapRes: dn: %s>' % self.dn
23 @classmethod
24 def fromLdapQuery(cls, q):
25 if not isinstance(q, dict):
26 raise LdapError('LdapRes: Parsing Error, not ldap response item')
27 if not (('dn' in q) and ('attributes' in q)):
28 raise LdapError('LdapRes: Parsing Error, format mismatch')
30 return cls(q['dn'], q['attributes'])
32 class Ldap():
33 def __init__(self, host, user, passwd, timeout=60, queryTimeout=300, **kwa):
34 if 'baseDN' in kwa:
35 self._baseDN = kwa['baseDN']
36 del kwa['baseDN']
37 else:
38 self._baseDN = None
39 ldapSrv = Server(host, connect_timeout=timeout, **kwa)
40 self._conn = self._makeConnFabric(ldapSrv, authentication=SIMPLE,
41 user=user, password=passwd,
42 check_names=True, lazy=True,
43 auto_referrals=False, raise_exceptions=True, auto_range=True
44 )
45 self.queryTimeout = queryTimeout
47 def __call__(self, filter, attrib, queryTimeout=None, baseDN = None):
48 if baseDN is None:
49 if self._baseDN is None:
50 raise LdapError('No base dn on query execution')
51 baseDN = self._baseDN
52 if queryTimeout is None:
53 queryTimeout = self.queryTimeout
54 try:
55 conn = self._conn()
56 with conn:
57 conn.open()
58 conn.bind()
60 res = conn.extend.standard.paged_search(baseDN,
61 filter, attributes=attrib, paged_size=LDAP_PAGE, generator=False,
62 search_scope=SUBTREE, time_limit=queryTimeout
63 )
65 for i in res:
66 if i['type'] == 'searchResEntry':
67 yield LdapRes.fromLdapQuery(i)
69 except Exception as e:
70 raise LdapError("Error on get data (%s): %s" % (type(e), str(e)), *e.args[1:])
72 def getList(self, *a, **kwa):
73 return [ i for i in self(*a, **kwa) ]
75 @staticmethod
76 def _makeConnFabric(*a, **kwa):
77 def _func():
78 return Connection(*a, **kwa)
80 return _func