From ba81929519ac37715970c69400f2b0d067bad7aa Mon Sep 17 00:00:00 2001 From: Jon Lockwood Date: Sat, 24 Jul 2021 13:32:20 +0930 Subject: [PATCH] refactor(ldap): reuse existing connection to confirm user credentials, use 'rebind' instead of re-connecting to ldap. This also enables unit testing of all functions except the connection to ldap. issue #13738 --- .../doctype/ldap_settings/ldap_settings.py | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/frappe/integrations/doctype/ldap_settings/ldap_settings.py b/frappe/integrations/doctype/ldap_settings/ldap_settings.py index b10709f02b..a786221489 100644 --- a/frappe/integrations/doctype/ldap_settings/ldap_settings.py +++ b/frappe/integrations/doctype/ldap_settings/ldap_settings.py @@ -219,22 +219,24 @@ class LDAPSettings(Document): search_filter="{0}".format(user_filter), attributes=ldap_attributes) + if len(conn.entries) == 1 and conn.entries[0]: + user = conn.entries[0] + + groups = self.fetch_ldap_groups(user, conn) + + # only try and connect as the user, once we have their fqdn entry. + if conn.rebind(user=user.entry_dn, password=password): + return self.create_or_update_user(self.convert_ldap_entry_to_dict(user), groups=groups) + + raise ldap3.core.exceptions.LDAPInvalidCredentialsResult # even though nothing foundor failed authentication raise invalid credentials + except ldap3.core.exceptions.LDAPInvalidFilterError: frappe.throw(_("Please use a valid LDAP search filter"), title=_("Misconfigured")) - if len(conn.entries) == 1 and conn.entries[0]: - user = conn.entries[0] - - groups = self.fetch_ldap_groups(user, conn) - - # only try and connect as the user, once we have their fqdn entry. - self.connect_to_ldap(base_dn=user.entry_dn, password=password) - - - return self.create_or_update_user(self.convert_ldap_entry_to_dict(user), groups=groups) - else: + except ldap3.core.exceptions.LDAPInvalidCredentialsResult: frappe.throw(_("Invalid username or password")) + def reset_password(self, user, password, logout_sessions=False): from ldap3 import HASHED_SALTED_SHA, MODIFY_REPLACE from ldap3.utils.hashed import hashed