From 8da0b7c533ff3fc27aed49a5a8c9886e7a33f084 Mon Sep 17 00:00:00 2001 From: kakwa Date: Mon, 25 May 2015 19:52:54 +0200 Subject: [PATCH] code factoring --- ldapcherry/backend/backendLdap.py | 58 ++++++++++++------------------- 1 file changed, 23 insertions(+), 35 deletions(-) diff --git a/ldapcherry/backend/backendLdap.py b/ldapcherry/backend/backendLdap.py index 2874fcc..b9a8579 100644 --- a/ldapcherry/backend/backendLdap.py +++ b/ldapcherry/backend/backendLdap.py @@ -66,7 +66,7 @@ class Backend(ldapcherry.backend.Backend): def del_user(self, username): pass - def search(self, searchstring): + def _search(self, searchfilter, attrs): ldap_client = self._connect() try: ldap_client.simple_bind_s(self.binddn, self.bindpassword) @@ -75,69 +75,57 @@ class Backend(ldapcherry.backend.Backend): logging.ERROR, "Configuration error, wrong credentials, unable to connect to ldap with '" + self.binddn + "'", ) - #raise cherrypy.HTTPError("500", "Configuration Error, contact administrator") + ldap_client.unbind_s() raise e except ldap.SERVER_DOWN as e: self._logger( logging.ERROR, "Unable to contact ldap server '" + self.uri + "', check 'auth.ldap.uri' and ssl/tls configuration", ) + ldap_client.unbind_s() raise e - user_filter = self.search_filter_tmpl % { - 'searchstring': searchstring - } - print user_filter try: r = ldap_client.search_s(self.userdn, ldap.SCOPE_SUBTREE, - user_filter, - attrlist=None + searchfilter, + attrlist=attrs ) except ldap.FILTER_ERROR as e: - #self._logger( - # logging.ERROR, - # "Bad search filter, check '" + self.backend_name + ".search_filter_tmpl'", - # ) + self._logger( + logging.ERROR, + "Bad search filter, check '" + self.backend_name + ".*_filter_tmpl' params", + ) + ldap_client.unbind_s() raise e + + ldap_client.unbind_s() return r + + def search(self, searchstring): + + searchfilter = self.search_filter_tmpl % { + 'searchstring': searchstring + } + + return self._search(searchfilter, None) + def get_user(self, username, attrs=True): if attrs: a = self.attrlist else: a = None - ldap_client = self._connect() - try: - ldap_client.simple_bind_s(self.binddn, self.bindpassword) - except ldap.INVALID_CREDENTIALS as e: - self._logger( - logging.ERROR, - "Configuration error, wrong credentials, unable to connect to ldap with '" + self.binddn + "'", - ) - #raise cherrypy.HTTPError("500", "Configuration Error, contact administrator") - raise e - except ldap.SERVER_DOWN as e: - self._logger( - logging.ERROR, - "Unable to contact ldap server '" + self.uri + "', check 'auth.ldap.uri' and ssl/tls configuration", - ) - raise e user_filter = self.user_filter_tmpl % { 'username': username } - r = ldap_client.search_s(self.userdn, - ldap.SCOPE_SUBTREE, - user_filter, - attrlist=a - ) + r = self._search(user_filter, a) + if len(r) == 0: - ldap_client.unbind_s() return None - ldap_client.unbind_s() if attrs: dn_entry = r[0] else: