From 4749868f3eb0bafe90d38507b45d04e4acb8cd14 Mon Sep 17 00:00:00 2001
From: Alexander Bias <alexander.bias@uni-ulm.de>
Date: Wed, 7 Feb 2018 15:40:02 +0100
Subject: [PATCH] Bugfix: Login via email for first-time LDAP logins did not
 work if multiple LDAP contexts were configured

---
 CHANGES.md | 4 ++++
 auth.php   | 4 ++--
 2 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/CHANGES.md b/CHANGES.md
index 33fd946..685ae54 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -4,6 +4,10 @@ moodle-auth_ldap_syncplus
 Changes
 -------
 
+### Unreleased
+
+* 2018-02-07 - Bugfix: Login via email for first-time LDAP logins did not work if multiple LDAP contexts were configured; Credits to derhelge.
+
 ### v3.4-r2
 
 * 2018-02-07 - Add forgotten sync_roles task definition
diff --git a/auth.php b/auth.php
index 475d20c..ea88f5e 100644
--- a/auth.php
+++ b/auth.php
@@ -517,8 +517,8 @@ class auth_plugin_ldap_syncplus extends auth_plugin_ldap {
                 $ldapresult = ldap_list($ldapconnection, $context, $filter, array($authplugin->config->user_attribute));
             }
 
-            // If there is no LDAP result, continue with next context.
-            if (!$ldapresult) {
+            // If there is no LDAP result or if the user was not found in this context, continue with next context.
+            if (!$ldapresult || ldap_count_entries($ldapconnection, $ldapresult) == 0) {
                 continue;
             }
 
-- 
GitLab