From 38154963880dc29b9063dfb75a6d750461042199 Mon Sep 17 00:00:00 2001
From: Fred Thomsen <me@fredthomsen.net>
Date: Fri, 22 Jan 2021 22:28:40 -0800
Subject: [PATCH] Handle empty search results w/references

If a search result is empty but there are result reference locations
that are returned, then the current code will return invalid information
or throw an AttributeError.

Address issue #70.

The search result would be in the format a dn string and then a dictionary
containing the proper information about the user, but when the search is
empty you just end up with the search references as shown below, and
obviously the second item in each tuple is not a dict:

[(None, ['ldap://ForestDnsZones.mycompany.com/DC=ForestDnsZones,DC=mycompany,DC=com']),
 (None, ['ldap://DomainDnsZones.mycompany.com/DC=DomainDnsZones,DC=mycompany,DC=com']),
 (None, ['ldap://mycompany.com/CN=Configuration,DC=mycompany,DC=com'])]

A successful search looks something like this:
[('CN=My Name,OU=Users,OU=Accounts,DC=mycompany,DC=com',
 {'accountExpires': [b'9223372036854775807'],
  'cn': [b'First Last'],
  'userPrincipalName': [b'email@mycompany.com'],
  'whenChanged': [b'20210119003635.0Z'],
  'whenCreated': [b'20201005164610.0Z']}),
  (None, ['ldap://ForestDnsZones.mycompany.com/DC=ForestDnsZones,DC=mycompany,DC=com']),
  (None, ['ldap://DomainDnsZones.mycompany.com/DC=DomainDnsZones,DC=mycompany,DC=com']),
  (None, ['ldap://mycompany.com/CN=Configuration,DC=mycompany,DC=com'])]

Signed-off-by: Fred Thomsen <me@fredthomsen.net>
---
 flask_simpleldap/__init__.py | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/flask_simpleldap/__init__.py b/flask_simpleldap/__init__.py
index 73ab24c..c4b7afe 100644
--- a/flask_simpleldap/__init__.py
+++ b/flask_simpleldap/__init__.py
@@ -184,7 +184,8 @@ class LDAP(object):
                                     ldap.SCOPE_SUBTREE, query, fields)
             conn.unbind_s()
             result = {}
-            if records:
+            if records and\
+               records[0][0] is not None and isinstance(records[0][1], dict):
                 if dn_only:
                     if current_app.config['LDAP_OPENLDAP']:
                         if records:
-- 
GitLab