Added function DeletePerson in SlabDriver:
[sfa.git] / sfa / senslab / LDAPapi.py
index ad674c9..30ce8b6 100644 (file)
@@ -1,41 +1,49 @@
-
-import string
 import random
 from passlib.hash import ldap_salted_sha1 as lssha
-from sfa.util.xrn import Xrn,get_authority 
+from sfa.util.xrn import get_authority 
 import ldap
 from sfa.util.config import Config
-#from sfa.trust.gid import *
 from sfa.trust.hierarchy import Hierarchy
-#from sfa.trust.auth import *
-from sfa.trust.certificate import *
+#from sfa.trust.certificate import *
 import ldap.modlist as modlist
 from sfa.util.sfalogging import logger
-
+import os.path
 
 #API for OpenLDAP
 
+
+class ldap_config():
+    def __init__(self, config_file =  '/etc/sfa/ldap_config.py'):
+        self.load(config_file)
+
+    def load(self, config_file):
+        try:
+            execfile(config_file, self.__dict__)
+            self.config_file = config_file
+            # path to configuration data
+            self.config_path = os.path.dirname(config_file)
+        except IOError, error:
+            raise IOError, "Could not find or load the configuration file: %s" % config_file
+        
 class ldap_co:
     """ Set admin login and server configuration variables."""
+    
     def __init__(self):
-        
-        self.login = 'cn=admin,dc=senslab,dc=info'
-        self.passwd = 'sfa'  
-        self.server_ip = "192.168.0.251"
-
         #Senslab PROD LDAP parameters 
-        #TODO : Use config file /etc/senslab/config.properties if it is possible
-       self.ldapPort = ldap.PORT
-       self.ldapVersion  = ldap.VERSION3
-       self.ldapSearchScope = ldap.SCOPE_SUBTREE
+        LdapConfig = ldap_config()
+        self.config = LdapConfig
+        self.ldapHost = LdapConfig.LDAP_IP_ADDRESS 
+        self.ldapPeopleDN = LdapConfig.LDAP_PEOPLE_DN
+        self.ldapGroupDN = LdapConfig.LDAP_GROUP_DN
+        self.ldapAdminDN = LdapConfig.LDAP_WEB_DN
+        self.ldapAdminPassword = LdapConfig.LDAP_WEB_PASSWORD
+
+
+        self.ldapPort = ldap.PORT
+        self.ldapVersion  = ldap.VERSION3
+        self.ldapSearchScope = ldap.SCOPE_SUBTREE
 
 
-       self.ldapHost = "" #set ldap.OPT_HOST_NAME maybe ?
-       self.ldapPeopleDN = 'ou=People,dc=senslab,dc=info';
-       self.ldapGroupDN = 'ou=Group,dc=senslab,dc=info';
-       self.ldapUserDN = 'uid=web,ou=Service,dc=senslab,dc=info';
-       self.ldapUserPassword = 'XNB+1z(C '
-    
     def connect(self, bind = True):
         """Enables connection to the LDAP server.
         Set the bind parameter to True if a bind is needed
@@ -44,29 +52,28 @@ class ldap_co:
         
         """
         try:
-            self.ldapserv = ldap.open(self.server_ip)
-        except ldap.LDAPError, e:
-            return {'bool' : False, 'message' : e }
+            self.ldapserv = ldap.open(self.ldapHost)
+        except ldap.LDAPError, error:
+            return {'bool' : False, 'message' : error }
         
         # Bind with authentification
         if(bind): 
             return self.bind()
         
         else:     
-            return {'bool': True}
-    
+            return {'bool': True} 
     
     def bind(self):
         """ Binding method. """
         try:
             # Opens a connection after a call to ldap.open in connect:
-            self.ldapserv = ldap.initialize("ldap://" + self.server_ip )
+            self.ldapserv = ldap.initialize("ldap://" + self.ldapHost)
                 
             # Bind/authenticate with a user with apropriate rights to add objects
-            self.ldapserv.simple_bind_s(self.login, self.passwd)
+            self.ldapserv.simple_bind_s(self.ldapAdminDN, self.ldapAdminPassword)
 
-        except ldap.LDAPError, e:
-            return {'bool' : False, 'message' : e }
+        except ldap.LDAPError, error:
+            return {'bool' : False, 'message' : error }
 
         return {'bool': True}
     
@@ -74,19 +81,27 @@ class ldap_co:
         """ Close the LDAP connection """
         try:
             self.ldapserv.unbind_s()
-        except ldap.LDAPError, e:
-            return {'bool' : False, 'message' : e }
+        except ldap.LDAPError, error:
+            return {'bool' : False, 'message' : error }
             
         
 class LDAPapi :
     def __init__(self):
         logger.setLevelDebug() 
         #SFA related config
-        self.senslabauth=Hierarchy()
-        config=Config()
-        self.authname=config.SFA_REGISTRY_ROOT_AUTH
-        self.baseDN = "ou=people,dc=senslab,dc=info"
-        self.conn =  ldap_co()  
+        self.senslabauth = Hierarchy()
+        config = Config()
+        
+        self.authname = config.SFA_REGISTRY_ROOT_AUTH
+
+        self.conn =  ldap_co() 
+        self.ldapUserQuotaNFS = self.conn.config.LDAP_USER_QUOTA_NFS 
+        self.ldapUserUidNumberMin = self.conn.config.LDAP_USER_UID_NUMBER_MIN 
+        self.ldapUserGidNumber = self.conn.config.LDAP_USER_GID_NUMBER 
+        self.ldapUserHomePath = self.conn.config.LDAP_USER_HOME_PATH 
+        
+        self.lengthPassword = 8
+        self.baseDN = self.conn.ldapPeopleDN
         #authinfo=self.senslabauth.get_auth_info(self.authname)
         
         
@@ -98,24 +113,9 @@ class LDAPapi :
                                 'd','e','f','g','h','i','j','k','l','m',\
                                 'n','o','p','q','r','s','t','u','v','w',\
                                 'x','y','z','\'']
-        self.ldapUserQuotaNFS = '/dev/vdb:2000000:2500000:0:0'
-        self.lengthPassword = 8;
-        self.ldapUserHomePath = '/senslab/users/' 
-        self.ldapUserGidNumber = '2000'
-        self.ldapUserUidNumberMin = '2000' 
+        
         self.ldapShell = '/bin/bash'
-        #self.auth=Auth()
-        #gid=authinfo.get_gid_object()
-        #self.ldapdictlist = ['type',
-                        #'pkey',
-                        #'uid',
-                        #'serial',
-                        #'authority',
-                        #'peer_authority',
-                        #'pointer' ,
-                        #'hrn']
-          
-                        
+
     
     def generate_login(self, record):
         """Generate login for adding a new user in LDAP Directory 
@@ -139,21 +139,21 @@ class LDAPapi :
         getAttrs = ['uid']
         if length_last_name >= login_max_length :
             login = lower_last_name[0:login_max_length]
-            index = 0;
-            logger.debug("login : %s index : %s" %login %index);
+            index = 0
+            logger.debug("login : %s index : %s" %(login,index))
         elif length_last_name >= 4 :
             login = lower_last_name
             index = 0
-            logger.debug("login : %s index : %s" %login %index);
+            logger.debug("login : %s index : %s" %(login,index))
         elif length_last_name == 3 :
             login = lower_first_name[0:1] + lower_last_name
             index = 1
-            logger.debug("login : %s index : %s" %login %index);
+            logger.debug("login : %s index : %s" %(login,index))
         elif length_last_name == 2:
             if len ( lower_first_name) >=2:
                 login = lower_first_name[0:2] + lower_last_name
                 index = 2
-                logger.debug("login : %s index : %s" %login %index);
+                logger.debug("login : %s index : %s" %(login,index))
             else:
                 logger.error("LoginException : \
                             Generation login error with \
@@ -163,12 +163,13 @@ class LDAPapi :
         else :
             logger.error("LDAP generate_login failed : \
                             impossible to generate unique login for %s %s" \
-                            %lower_first_name %lower_last_name)
+                            %(lower_first_name,lower_last_name))
             
-        filter = '(uid='+ login+ ')'
+        login_filter = '(uid=' + login + ')'
+        
         try :
             #Check if login already in use
-            while (self.LdapSearch(filter, getAttrs) is not [] ):
+            while (len(self.LdapSearch(login_filter, getAttrs)) is not 0 ):
             
                 index += 1
                 if index >= 9:
@@ -176,15 +177,18 @@ class LDAPapi :
                                     with minimum four characters")
                 else:
                     try:
-                        login = lower_first_name[0,index] + \
-                                    lower_last_name[0,login_max_length-index]
-                        filter = '(uid='+ login+ ')'
+                        login = lower_first_name[0:index] + \
+                                    lower_last_name[0:login_max_length-index]
+                        login_filter = '(uid='+ login+ ')'
                     except KeyError:
                         print "lower_first_name - lower_last_name too short"
+                        
+            logger.debug("LDAP.API \t generate_login login %s" %(login))
             return login
                     
-        except  ldap.LDAPError,e :
-            logger.log_exc("LDAP generate_login Error %s" %e)
+        except  ldap.LDAPError,error :
+            logger.log_exc("LDAP generate_login Error %s" %error)
+            return None
 
         
 
@@ -195,20 +199,21 @@ class LDAPapi :
         
         """
         password = str()
+        length = len(self.charsPassword)
         for index in range(self.lengthPassword):
-            password += self.charsPassword[random.randint(0, \
-                                            len(self.charsPassword))]
+            char_index = random.randint(0,length-1)
+            password += self.charsPassword[char_index]
 
         return password
 
     def encrypt_password(self, password):
-       """ Use passlib library to make a RFC2307 LDAP encrypted password
-       salt size = 8, use sha-1 algorithm. Returns encrypted password.
-       
-       """
-       #Keep consistency with Java Senslab's LDAP API 
-       #RFC2307SSHAPasswordEncryptor so set the salt size to 8 bytres
-       return lssha.encrypt(password,salt_size = 8)
+        """ Use passlib library to make a RFC2307 LDAP encrypted password
+        salt size = 8, use sha-1 algorithm. Returns encrypted password.
+        
+        """
+        #Keep consistency with Java Senslab's LDAP API 
+        #RFC2307SSHAPasswordEncryptor so set the salt size to 8 bytres
+        return lssha.encrypt(password,salt_size = 8)
     
 
 
@@ -221,31 +226,36 @@ class LDAPapi :
         """
         #First, get all the users in the LDAP
         getAttrs = "(uidNumber=*)"
-        filter = ['uidNumber']
+        login_filter = ['uidNumber']
 
-        result_data = self.LdapSearch(getAttrs, filter) 
+        result_data = self.LdapSearch(getAttrs, login_filter) 
         #It there is no user in LDAP yet, First LDAP user
         if result_data == []:
             max_uidnumber = self.ldapUserUidNumberMin
         #Otherwise, get the highest uidNumber
         else:
-            uidNumberList = [r[1]['uidNumber'] for r in result_data ]
+            
+            uidNumberList = [int(r[1]['uidNumber'][0])for r in result_data ]
+            logger.debug("LDAPapi.py \tfind_max_uidNumber  \
+                                    uidNumberList %s " %(uidNumberList))
             max_uidnumber = max(uidNumberList) + 1
             
         return str(max_uidnumber)
-        
-    #TODO ; Get ssh public key from sfa record   
-    #To be filled by N. Turro                
-    def get_ssh_pkey(self, record):
-        return
          
          
-    #TODO Handle OR filtering in the ldap query when 
-    #dealing with a list of records instead of doing a for loop in GetPersons   
-    def make_ldap_filters_from_record(self, record=None):
+    def get_ssh_pkey(self, record):
+        """TODO ; Get ssh public key from sfa record  
+        To be filled by N. Turro ? or using GID pl way?
+        
         """
+        return 'A REMPLIR '
+
+    def make_ldap_filters_from_record(self, record=None):
+        """TODO Handle OR filtering in the ldap query when 
+        dealing with a list of records instead of doing a for loop in GetPersons   
         Helper function to make LDAP filter requests out of SFA records.
         """
+        req_ldap = ''
         req_ldapdict = {}
         if record :
             if 'first_name' in record  and 'last_name' in record:
@@ -255,29 +265,40 @@ class LDAPapi :
                 req_ldapdict['mail'] = record['email']
             if 'mail' in record:
                 req_ldapdict['mail'] = record['mail']
+            if 'enabled' in record:
+                if record['enabled'] == True :
+                    req_ldapdict['shadowExpire'] = '-1'
+                else:
+                    req_ldapdict['shadowExpire'] = '0'
+                
+            #Hrn should not be part of the filter because the hrn 
+            #presented by a certificate of a SFA user not imported in 
+            #Senslab  does not include the senslab login in it 
+            #Plus, the SFA user may already have an account with senslab
+            #using another login.
                 
-            if 'hrn' in record :
-                splited_hrn = record['hrn'].split(".")
-                if splited_hrn[0] != self.authname :
-                    logger.warning(" \r\n LDAP.PY \
-                        make_ldap_filters_from_record I know nothing \
-                        about %s my authname is %s not %s" \
-                        %(record['hrn'], self.authname, splited_hrn[0]) )
+            #if 'hrn' in record :
+                #splited_hrn = record['hrn'].split(".")
+                #if splited_hrn[0] != self.authname :
+                    #logger.warning(" \r\n LDAP.PY \
+                        #make_ldap_filters_from_record I know nothing \
+                        #about %s my authname is %s not %s" \
+                        #%(record['hrn'], self.authname, splited_hrn[0]) )
                         
-                login=splited_hrn[1]
-                req_ldapdict['uid'] = login
+                #login=splited_hrn[1]
+                #req_ldapdict['uid'] = login
             
-            req_ldap=''
+
             logger.debug("\r\n \t LDAP.PY make_ldap_filters_from_record \
                                 record %s req_ldapdict %s" \
                                 %(record, req_ldapdict))
             
             for k in req_ldapdict:
-                req_ldap += '('+str(k)+'='+str(req_ldapdict[k])+')'
+                req_ldap += '('+ str(k)+ '=' + str(req_ldapdict[k]) + ')'
             if  len(req_ldapdict.keys()) >1 :
                 req_ldap = req_ldap[:0]+"(&"+req_ldap[0:]
                 size = len(req_ldap)
-                req_ldap= req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
+                req_ldap = req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
         else:
             req_ldap = "(cn=*)"
         
@@ -295,7 +316,7 @@ class LDAPapi :
                                     "shadowAccount", "systemQuotas",\
                                     "ldapPublicKey"]
         
-        attrs['givenName'] = str(record['first_name']).lower(),capitalize()
+        attrs['givenName'] = str(record['first_name']).lower().capitalize()
         attrs['sn'] = str(record['last_name']).lower().capitalize()
         attrs['cn'] = attrs['givenName'] + ' ' + attrs['sn']
         attrs['gecos'] = attrs['givenName'] + ' ' + attrs['sn']
@@ -304,7 +325,7 @@ class LDAPapi :
         attrs['quota'] = self.ldapUserQuotaNFS 
         attrs['homeDirectory'] = self.ldapUserHomePath + attrs['uid']
         attrs['loginShell'] = self.ldapShell
-        attrs['gidNumber'] = '2000'    
+        attrs['gidNumber'] = self.ldapUserGidNumber
         attrs['uidNumber'] = self.find_max_uidNumber()
         attrs['mail'] = record['mail'].lower()
         
@@ -326,11 +347,11 @@ class LDAPapi :
 
         #Motivation field in Senslab
         attrs['description'] = 'SFA USER FROM OUTSIDE SENSLAB'
-        
-        attrs['ou'] = "SFA"         #Optional: organizational unit
+
+        attrs['ou'] = 'SFA'         #Optional: organizational unit
         #No info about those here:
-        attrs['l'] = ''             #Optional: Locality. 
-        attrs['st'] = ''            #Optional: state or province (country).
+        attrs['l'] = 'To be defined'#Optional: Locality. 
+        attrs['st'] = 'To be defined' #Optional: state or province (country).
 
         return attrs
 
@@ -364,17 +385,17 @@ class LDAPapi :
 
             try:
                 ldif = modlist.addModlist(user_ldap_attrs)
-                logger.debug("\r\n \tLDAPapi.PY add attrs %s \r\n  ldif %s"\
+                logger.debug("LDAPapi.py add attrs %s \r\n  ldif %s"\
                                 %(user_ldap_attrs,ldif) )
                 self.conn.ldapserv.add_s(dn,ldif)
                 
                 logger.info("Adding user %s login %s in LDAP" \
-                        %user_ldap_attrs['cn'] %user_ldap_attrs['uid'])
+                        %(user_ldap_attrs['cn'] ,user_ldap_attrs['uid']))
                         
                         
-            except ldap.LDAPError, e:
-                logger.log_exc("LDAP Add Error %s" %e)
-                return {'bool' : False, 'message' : e }
+            except ldap.LDAPError, error:
+                logger.log_exc("LDAP Add Error %s" %error)
+                return {'bool' : False, 'message' : error }
         
             self.conn.close()
             return {'bool': True}  
@@ -394,8 +415,8 @@ class LDAPapi :
                 self.conn.close()
                 return {'bool': True}
             
-            except ldap.LDAPError, e:
-                logger.log_exc("LDAP Delete Error %s" %e)
+            except ldap.LDAPError, error:
+                logger.log_exc("LDAP Delete Error %s" %error)
                 return {'bool': False}
         
     
@@ -404,8 +425,10 @@ class LDAPapi :
         Deletes a SFA person in LDAP, based on the user's hrn.
         """
         #Find uid of the  person 
-        person = self.LdapFindUser(record_filter)
-        
+        person = self.LdapFindUser(record_filter,[])
+        logger.debug("LDAPapi.py \t LdapDeleteUser record %s person %s" \
+        %(record_filter, person))
+
         if person:
             dn = 'uid=' + person['uid'] + "," +self.baseDN 
         else:
@@ -418,54 +441,77 @@ class LDAPapi :
     def LdapModify(self, dn, old_attributes_dict, new_attributes_dict): 
         """ Modifies a LDAP entry """
          
-        ldif = modlist.modifyModlist(old_attributes_dict,new_attributes)
+        ldif = modlist.modifyModlist(old_attributes_dict,new_attributes_dict)
         # Connect and bind/authenticate    
-        result = self.conn.connect(bind
+        result = self.conn.connect() 
         if (result['bool']): 
             try:
-                self.conn.ldapserver.modify_s(dn,ldif)
+                self.conn.ldapserv.modify_s(dn,ldif)
                 self.conn.close()
                 return {'bool' : True }
-            except ldap.LDAPError, e:
-                logger.log_exc("LDAP LdapModify Error %s" %e)
+            except ldap.LDAPError, error:
+                logger.log_exc("LDAP LdapModify Error %s" %error)
                 return {'bool' : False }
     
         
-    def LdapModifyUser(self, record_filter, new_attributes):
+    def LdapModifyUser(self, user_record, new_attributes_dict):
         """
-        Gets the record from one user based on record_filter 
+        Gets the record from one user_uid_login based on record_filter 
         and changes the attributes according to the specified new_attributes.
         Does not use this if we need to modify the uid. Use a ModRDN 
         #operation instead ( modify relative DN )
         """
-        if record_filter is None:
-            logger.error("LDAP \t LdapModifyUser Need record filter ")
+        if user_record is None:
+            logger.error("LDAP \t LdapModifyUser Need user record  ")
             return {'bool': False} 
         
-        #Get all the attributes of the user 
-        person = self.LdapFindUser(record_filter,[])
-        if person and len(person) > 1 :
+        #Get all the attributes of the user_uid_login 
+        #person = self.LdapFindUser(record_filter,[])
+        req_ldap = self.make_ldap_filters_from_record(user_record)
+        person_list = self.LdapSearch(req_ldap,[])
+        logger.debug("LDAPapi.py \t LdapModifyUser person_list : %s" %(person_list))
+        if person_list and len(person_list) > 1 :
             logger.error("LDAP \t LdapModifyUser Too many users returned")
             return {'bool': False}
-        if person is None :
+        if person_list is None :
             logger.error("LDAP \t LdapModifyUser  User %s doesn't exist "\
-                        %(record_filter['hrn']))
+                        %(user_record))
             return {'bool': False} 
         
         # The dn of our existing entry/object
-        dn  = 'uid=' + person['uid'] + "," +self.baseDN  
+        #One result only from ldapSearch
+        person = person_list[0][1]
+        dn  = 'uid=' + person['uid'][0] + "," +self.baseDN  
+       
         if new_attributes_dict:
             old = {}
-            for k in new_attributes:
-                old[k] =  person[k]
-                
-            result = self.LdapModify(dn, old,new_attributes)
+            for k in new_attributes_dict:
+                if k not in person:
+                    old[k] =  ''
+                else :
+                    old[k] = person[k]
+            logger.debug(" LDAPapi.py \t LdapModifyUser  new_attributes %s"\
+                                %( new_attributes_dict))  
+            result = self.LdapModify(dn, old,new_attributes_dict)
             return result
         else:
             logger.error("LDAP \t LdapModifyUser  No new attributes given. ")
             return {'bool': False} 
             
             
+            
+            
+    def LdapMarkUserAsDeleted(self, record): 
+
+        
+        new_attrs = {}
+        #Disable account
+        new_attrs['shadowExpire'] = '0'
+        logger.debug(" LDAPapi.py \t LdapMarkUserAsDeleted ")
+        ret = self.LdapModifyUser(record, new_attrs)
+        return ret
+
+            
     def LdapResetPassword(self,record):
         """
         Resets password for the user whose record is the parameter and changes
@@ -475,34 +521,40 @@ class LDAPapi :
         password = self.generate_password()
         attrs = {}
         attrs['userPassword'] = self.encrypt_password(password)
-        logger.debug("LDAP LdapModifyUser Error %s" %e)
+        logger.debug("LDAP LdapResetPassword encrypt_password %s"\
+                    %(attrs['userPassword']))
         result = self.LdapModifyUser(record, attrs)
         return result
         
-
+        
     def LdapSearch (self, req_ldap = None, expected_fields = None ):
         """
         Used to search directly in LDAP, by using ldap filters and
         return fields. 
         When req_ldap is None, returns all the entries in the LDAP.
-        
+      
         """
         result = self.conn.connect(bind = False)
         if (result['bool']) :
             
             return_fields_list = []
             if expected_fields == None : 
-                return_fields_list = ['mail','givenName', 'sn', 'uid','sshPublicKey']
+                return_fields_list = ['mail','givenName', 'sn', 'uid', \
+                                        'sshPublicKey', 'shadowExpire']
             else : 
                 return_fields_list = expected_fields
-  
+            #No specifc request specified, get the whole LDAP    
+            if req_ldap == None:
+                req_ldap = '(cn=*)'
+               
             logger.debug("LDAP.PY \t LdapSearch  req_ldap %s \
-                            return_fields_list %s" %(req_ldap,return_fields_list))
+                                    return_fields_list %s" \
+                                    %(req_ldap, return_fields_list))
 
             try:
                 msg_id = self.conn.ldapserv.search(
                                             self.baseDN,ldap.SCOPE_SUBTREE,\
-                                            req_ldap,return_fields_list)     
+                                            req_ldap, return_fields_list)     
                 #Get all the results matching the search from ldap in one 
                 #shot (1 value)
                 result_type, result_data = \
@@ -515,30 +567,40 @@ class LDAPapi :
 
                 return result_data
             
-            except  ldap.LDAPError,e :
-                logger.log_exc("LDAP LdapSearch Error %s" %e)
+            except  ldap.LDAPError,error :
+                logger.log_exc("LDAP LdapSearch Error %s" %error)
                 return []
             
             else:
                 logger.error("LDAP.PY \t Connection Failed" )
                 return 
             
-
-    def LdapFindUser(self,record = None, expected_fields = None):
+    def LdapFindDisabledUsers(self):
+        return self.LdapSearch('(shadowExpire=-0)', []) 
+        
+    def LdapFindUser(self, record = None, is_user_enabled=None, \
+            expected_fields = None):
         """
         Search a SFA user with a hrn. User should be already registered 
         in Senslab LDAP. 
         Returns one matching entry 
-        """   
+        """  
+        if is_user_enabled: 
+            custom_record = {}
+            custom_record['enabled'] = is_user_enabled
+        if record:  
+            custom_record.update(record)
+
 
-        req_ldap = self.make_ldap_filters_from_record(record) 
+        req_ldap = self.make_ldap_filters_from_record(custom_record)     
         return_fields_list = []
         if expected_fields == None : 
-            return_fields_list = ['mail','givenName', 'sn', 'uid','sshPublicKey']
+            return_fields_list = ['mail','givenName', 'sn', 'uid', \
+                                    'sshPublicKey']
         else : 
             return_fields_list = expected_fields
             
-        result_data = self.LdapSearch(req_ldap,  return_fields_list )
+        result_data = self.LdapSearch(req_ldap, return_fields_list )
         logger.debug("LDAP.PY \t LdapFindUser  result_data %s" %(result_data))
            
         if len(result_data) is 0:
@@ -566,7 +628,7 @@ class LDAPapi :
                 if parent_hrn is not self.authname:
                     peer_authority = parent_hrn
 
-                results=  {    
+                results =  {   
                             'type': 'user',
                             'pkey': ldapentry['sshPublicKey'][0],
                             #'uid': ldapentry[1]['uid'][0],
@@ -582,10 +644,10 @@ class LDAPapi :
                             'pointer' : -1,
                             'hrn': hrn,
                             }
-            except KeyError:
-                lorrer.log_exc("LDAPapi \t LdapSearch KEyError results %s" \
-                                %(results) )
-                pass 
+            except KeyError,error:
+                logger.log_exc("LDAPapi \t LdaFindUser KEyError %s" \
+                                %error )
+                return
         else:
         #Asked for all users in ldap
             results = []
@@ -619,7 +681,8 @@ class LDAPapi :
                             'pointer' : -1,
                             'hrn': hrn,
                             } ) 
-                except KeyError:
-                    pass
+                except KeyError,error:
+                    logger.log_exc("LDAPapi.PY \t LdapFindUser EXCEPTION %s" %(error))
+                    return
         return results