From 6231476653a6586551f6da90b5580024cee47899 Mon Sep 17 00:00:00 2001
From: Robin Goodall <rjg21@cam.ac.uk>
Date: Fri, 7 May 2021 15:52:08 +0100
Subject: [PATCH] Fix authenticated login

---
 configuration-example.yaml |  3 +++
 gsuitesync/sync/ldap.py    | 15 ++++-----------
 2 files changed, 7 insertions(+), 11 deletions(-)

diff --git a/configuration-example.yaml b/configuration-example.yaml
index dba8141..c8d8004 100644
--- a/configuration-example.yaml
+++ b/configuration-example.yaml
@@ -151,6 +151,9 @@ ldap:
   # use SSL when connecting to the LDAP server, and will attempt to
   # authenticate with these credentials.
   #
+  # Username needs to be the full DN of the group, e.g.
+  #   groupid=123456,ou=groups,o=example-corps,dc=example,dc=com
+  #
   # The username and password properties should _not_ be specified when running
   # the sync tool inside the CUDN (which includes running in the CI pipeline).
   username: null
diff --git a/gsuitesync/sync/ldap.py b/gsuitesync/sync/ldap.py
index 65fe28f..5323061 100644
--- a/gsuitesync/sync/ldap.py
+++ b/gsuitesync/sync/ldap.py
@@ -266,22 +266,15 @@ class LDAPRetriever(ConfigurationStateConsumer):
     def _search(self, *, search_base, search_filter, attributes):
         # Use SSL to access the LDAP server when authentication credentials
         # have been configured
-        use_ssl = self.ldap_config.username and self.ldap_config.password
+        use_ssl = bool(self.ldap_config.username and self.ldap_config.password)
         ldap_server = ldap3.Server(self.ldap_config.host, use_ssl=use_ssl)
 
-        # Keyword arguments to pass to ldap3.Connection
-        connection_kwargs = {
-            'auto_bind': True
-        }
-
         # Add authentication credentials if configured
-        if self.ldap_config.username:
-            connection_kwargs['username'] = self.ldap_config.username
-        if self.ldap_config.password:
-            connection_kwargs['password'] = self.ldap_config.password
+        username = self.ldap_config.username if self.ldap_config.username else None
+        password = self.ldap_config.password if self.ldap_config.password else None
 
         # Connect to the LDAP server and perform the query
-        with ldap3.Connection(ldap_server, **connection_kwargs) as conn:
+        with ldap3.Connection(ldap_server, username, password, auto_bind=True) as conn:
             return conn.extend.standard.paged_search(
                 search_base, search_filter, paged_size=1000, attributes=attributes)
 
-- 
GitLab