Merge branch 'senslab2'
[sfa.git] / sfa / senslab / LDAPapi.py
1 import random
2 from passlib.hash import ldap_salted_sha1 as lssha
3 from sfa.util.xrn import get_authority 
4 import ldap
5 from sfa.util.config import Config
6 from sfa.trust.hierarchy import Hierarchy
7
8 import ldap.modlist as modlist
9 from sfa.util.sfalogging import logger
10 import os.path
11
12 #API for OpenLDAP
13
14
15 class LdapConfig():
16     def __init__(self, config_file =  '/etc/sfa/ldap_config.py'):
17         
18         try:
19             execfile(config_file, self.__dict__)
20        
21             self.config_file = config_file
22             # path to configuration data
23             self.config_path = os.path.dirname(config_file)
24         except IOError:
25             raise IOError, "Could not find or load the configuration file: %s" \
26                             % config_file
27   
28         
29 class ldap_co:
30     """ Set admin login and server configuration variables."""
31     
32     def __init__(self):
33         #Senslab PROD LDAP parameters
34         self.ldapserv = None
35         ldap_config = LdapConfig()
36         self.config = ldap_config
37         self.ldapHost = ldap_config.LDAP_IP_ADDRESS 
38         self.ldapPeopleDN = ldap_config.LDAP_PEOPLE_DN
39         self.ldapGroupDN = ldap_config.LDAP_GROUP_DN
40         self.ldapAdminDN = ldap_config.LDAP_WEB_DN
41         self.ldapAdminPassword = ldap_config.LDAP_WEB_PASSWORD
42
43
44         self.ldapPort = ldap.PORT
45         self.ldapVersion  = ldap.VERSION3
46         self.ldapSearchScope = ldap.SCOPE_SUBTREE
47
48
49     def connect(self, bind = True):
50         """Enables connection to the LDAP server.
51         Set the bind parameter to True if a bind is needed
52         (for add/modify/delete operations).
53         Set to False otherwise.
54         
55         """
56         try:
57             self.ldapserv = ldap.open(self.ldapHost)
58         except ldap.LDAPError, error:
59             return {'bool' : False, 'message' : error }
60         
61         # Bind with authentification
62         if(bind): 
63             return self.bind()
64         
65         else:     
66             return {'bool': True} 
67     
68     def bind(self):
69         """ Binding method. """
70         try:
71             # Opens a connection after a call to ldap.open in connect:
72             self.ldapserv = ldap.initialize("ldap://" + self.ldapHost)
73                 
74             # Bind/authenticate with a user with apropriate 
75             #rights to add objects
76             self.ldapserv.simple_bind_s(self.ldapAdminDN, \
77                                     self.ldapAdminPassword)
78
79         except ldap.LDAPError, error:
80             return {'bool' : False, 'message' : error }
81
82         return {'bool': True}
83     
84     def close(self):
85         """ Close the LDAP connection """
86         try:
87             self.ldapserv.unbind_s()
88         except ldap.LDAPError, error:
89             return {'bool' : False, 'message' : error }
90             
91         
92 class LDAPapi :
93     def __init__(self):
94         logger.setLevelDebug() 
95         #SFA related config
96         self.senslabauth = Hierarchy()
97         config = Config()
98         
99         self.authname = config.SFA_REGISTRY_ROOT_AUTH
100
101         self.conn =  ldap_co() 
102         self.ldapUserQuotaNFS = self.conn.config.LDAP_USER_QUOTA_NFS 
103         self.ldapUserUidNumberMin = self.conn.config.LDAP_USER_UID_NUMBER_MIN 
104         self.ldapUserGidNumber = self.conn.config.LDAP_USER_GID_NUMBER 
105         self.ldapUserHomePath = self.conn.config.LDAP_USER_HOME_PATH 
106         
107         self.lengthPassword = 8
108         self.baseDN = self.conn.ldapPeopleDN
109         #authinfo=self.senslabauth.get_auth_info(self.authname)
110         
111         
112         self.charsPassword = [ '!','$','(',')','*','+',',','-','.', \
113                                 '0','1','2','3','4','5','6','7','8','9', \
114                                 'A','B','C','D','E','F','G','H','I','J', \
115                                 'K','L','M','N','O','P','Q','R','S','T', \
116                                 'U','V','W','X','Y','Z','_','a','b','c', \
117                                 'd','e','f','g','h','i','j','k','l','m', \
118                                 'n','o','p','q','r','s','t','u','v','w', \
119                                 'x','y','z','\'']
120         
121         self.ldapShell = '/bin/bash'
122
123     
124     def generate_login(self, record):
125         """Generate login for adding a new user in LDAP Directory 
126         (four characters minimum length)
127         Record contains first name and last name.
128         
129         """ 
130         if 'first_name' in record and 'last_name' in record:
131             #Remove all special characters from first_name/last name
132             lower_first_name = record['first_name'].replace('-','')\
133                                             .replace('_','').replace('[','')\
134                                             .replace(']','').replace(' ','')\
135                                             .lower()
136             lower_last_name = record['last_name'].replace('-','')\
137                                             .replace('_','').replace('[','')\
138                                             .replace(']','').replace(' ','')\
139                                             .lower()  
140
141             
142         #No first name and last name 
143         #check  email    
144         else:
145             #For compatibility with other ldap func
146             if 'mail' in record and 'email' not in record:
147                 record['email'] = record['mail']
148             email = record['email']
149             email = email.split('@')[0].lower()
150             lower_first_name = None
151             lower_last_name = None
152             #Assume there is first name and last name in email
153             #if there is a  separator
154             separator_list = ['.','_','-']
155             for sep in separator_list:
156                 if sep in email:
157                     mail = email.split(sep)
158                     lower_first_name = mail[0]
159                     lower_last_name = mail[1]
160                     break
161             #Otherwise just take the part before the @ as the 
162             #lower_first_name  and lower_last_name
163             if lower_first_name is None:
164                lower_first_name = email
165                lower_last_name = email
166                
167         length_last_name = len(lower_last_name)  
168         login_max_length = 8
169         
170         #Try generating a unique login based on first name and last name
171         getAttrs = ['uid']
172         if length_last_name >= login_max_length :
173             login = lower_last_name[0:login_max_length]
174             index = 0
175             logger.debug("login : %s index : %s" %(login, index))
176         elif length_last_name >= 4 :
177             login = lower_last_name
178             index = 0
179             logger.debug("login : %s index : %s" %(login, index))
180         elif length_last_name == 3 :
181             login = lower_first_name[0:1] + lower_last_name
182             index = 1
183             logger.debug("login : %s index : %s" %(login, index))
184         elif length_last_name == 2:
185             if len ( lower_first_name) >=2:
186                 login = lower_first_name[0:2] + lower_last_name
187                 index = 2
188                 logger.debug("login : %s index : %s" %(login, index))
189             else:
190                 logger.error("LoginException : \
191                             Generation login error with \
192                             minimum four characters")
193             
194                 
195         else :
196             logger.error("LDAP generate_login failed : \
197                             impossible to generate unique login for %s %s" \
198                             %(lower_first_name,lower_last_name))
199             
200         login_filter = '(uid=' + login + ')'
201         
202         try :
203             #Check if login already in use
204             while (len(self.LdapSearch(login_filter, getAttrs)) is not 0 ):
205             
206                 index += 1
207                 if index >= 9:
208                     logger.error("LoginException : Generation login error \
209                                     with minimum four characters")
210                 else:
211                     try:
212                         login = lower_first_name[0:index] + \
213                                     lower_last_name[0:login_max_length-index]
214                         login_filter = '(uid='+ login+ ')'
215                     except KeyError:
216                         print "lower_first_name - lower_last_name too short"
217                         
218             logger.debug("LDAP.API \t generate_login login %s" %(login))
219             return login
220                     
221         except  ldap.LDAPError, error :
222             logger.log_exc("LDAP generate_login Error %s" %error)
223             return None
224
225         
226
227     def generate_password(self):
228     
229         """Generate password for adding a new user in LDAP Directory 
230         (8 characters length) return password
231         
232         """
233         password = str()
234         length = len(self.charsPassword)
235         for index in range(self.lengthPassword):
236             char_index = random.randint(0, length-1)
237             password += self.charsPassword[char_index]
238
239         return password
240
241     def encrypt_password(self, password):
242         """ Use passlib library to make a RFC2307 LDAP encrypted password
243         salt size = 8, use sha-1 algorithm. Returns encrypted password.
244         
245         """
246         #Keep consistency with Java Senslab's LDAP API 
247         #RFC2307SSHAPasswordEncryptor so set the salt size to 8 bytres
248         return lssha.encrypt(password, salt_size = 8)
249     
250
251
252     def find_max_uidNumber(self):
253             
254         """Find the LDAP max uidNumber (POSIX uid attribute) .
255         Used when adding a new user in LDAP Directory 
256         returns string  max uidNumber + 1
257         
258         """
259         #First, get all the users in the LDAP
260         getAttrs = "(uidNumber=*)"
261         login_filter = ['uidNumber']
262
263         result_data = self.LdapSearch(getAttrs, login_filter) 
264         #It there is no user in LDAP yet, First LDAP user
265         if result_data == []:
266             max_uidnumber = self.ldapUserUidNumberMin
267         #Otherwise, get the highest uidNumber
268         else:
269             
270             uidNumberList = [int(r[1]['uidNumber'][0])for r in result_data ]
271             logger.debug("LDAPapi.py \tfind_max_uidNumber  \
272                                     uidNumberList %s " %(uidNumberList))
273             max_uidnumber = max(uidNumberList) + 1
274             
275         return str(max_uidnumber)
276          
277          
278     def get_ssh_pkey(self, record):
279         """TODO ; Get ssh public key from sfa record  
280         To be filled by N. Turro ? or using GID pl way?
281         
282         """
283         return 'A REMPLIR '
284
285     def make_ldap_filters_from_record(self, record=None):
286         """TODO Handle OR filtering in the ldap query when 
287         dealing with a list of records instead of doing a for loop in GetPersons   
288         Helper function to make LDAP filter requests out of SFA records.
289         """
290         req_ldap = ''
291         req_ldapdict = {}
292         if record :
293             if 'first_name' in record  and 'last_name' in record:
294                 req_ldapdict['cn'] = str(record['first_name'])+" "\
295                                         + str(record['last_name'])
296             if 'email' in record :
297                 req_ldapdict['mail'] = record['email']
298             if 'mail' in record:
299                 req_ldapdict['mail'] = record['mail']
300             if 'enabled' in record:
301                 if record['enabled'] == True :
302                     req_ldapdict['shadowExpire'] = '-1'
303                 else:
304                     req_ldapdict['shadowExpire'] = '0'
305                 
306             #Hrn should not be part of the filter because the hrn 
307             #presented by a certificate of a SFA user not imported in 
308             #Senslab  does not include the senslab login in it 
309             #Plus, the SFA user may already have an account with senslab
310             #using another login.
311                 
312            
313
314             logger.debug("\r\n \t LDAP.PY make_ldap_filters_from_record \
315                                 record %s req_ldapdict %s" \
316                                 %(record, req_ldapdict))
317             
318             for k in req_ldapdict:
319                 req_ldap += '('+ str(k)+ '=' + str(req_ldapdict[k]) + ')'
320             if  len(req_ldapdict.keys()) >1 :
321                 req_ldap = req_ldap[:0]+"(&"+req_ldap[0:]
322                 size = len(req_ldap)
323                 req_ldap = req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
324         else:
325             req_ldap = "(cn=*)"
326         
327         return req_ldap
328         
329     def make_ldap_attributes_from_record(self, record):
330         """When addind a new user to Senslab's LDAP, creates an attributes 
331         dictionnary from the SFA record.
332         
333         """
334
335         attrs = {}
336         attrs['objectClass'] = ["top", "person", "inetOrgPerson", \
337                                     "organizationalPerson", "posixAccount", \
338                                     "shadowAccount", "systemQuotas", \
339                                     "ldapPublicKey"]
340        
341             
342         attrs['uid'] = self.generate_login(record)   
343         try:
344             attrs['givenName'] = str(record['first_name']).lower().capitalize()
345             attrs['sn'] = str(record['last_name']).lower().capitalize()
346             attrs['cn'] = attrs['givenName'] + ' ' + attrs['sn']
347             attrs['gecos'] = attrs['givenName'] + ' ' + attrs['sn']
348             
349         except: 
350             attrs['givenName'] = attrs['uid']
351             attrs['sn'] = attrs['uid']
352             attrs['cn'] = attrs['uid']
353             attrs['gecos'] = attrs['uid']
354             
355                      
356         attrs['quota'] = self.ldapUserQuotaNFS 
357         attrs['homeDirectory'] = self.ldapUserHomePath + attrs['uid']
358         attrs['loginShell'] = self.ldapShell
359         attrs['gidNumber'] = self.ldapUserGidNumber
360         attrs['uidNumber'] = self.find_max_uidNumber()
361         attrs['mail'] = record['mail'].lower()
362         try:
363             attrs['sshPublicKey'] = record['pkey']
364         except KeyError:
365             attrs['sshPublicKey'] = self.get_ssh_pkey(record) 
366         
367
368         #Password is automatically generated because SFA user don't go 
369         #through the Senslab website  used to register new users, 
370         #There is no place in SFA where users can enter such information
371         #yet.
372         #If the user wants to set his own password , he must go to the Senslab 
373         #website.
374         password = self.generate_password()
375         attrs['userPassword'] = self.encrypt_password(password)
376         
377         #Account automatically validated (no mail request to admins)
378         #Set to 0 to disable the account, -1 to enable it,
379         attrs['shadowExpire'] = '-1'
380
381         #Motivation field in Senslab
382         attrs['description'] = 'SFA USER FROM OUTSIDE SENSLAB'
383
384         attrs['ou'] = 'SFA'         #Optional: organizational unit
385         #No info about those here:
386         attrs['l'] = 'To be defined'#Optional: Locality. 
387         attrs['st'] = 'To be defined' #Optional: state or province (country).
388
389         return attrs
390
391
392
393     def LdapAddUser(self, record) :
394         """Add SFA user to LDAP if it is not in LDAP  yet. """
395         logger.debug(" \r\n \t LDAP LdapAddUser \r\n\r\n =====================================================\r\n ")
396         user_ldap_attrs = self.make_ldap_attributes_from_record(record)
397
398         
399         #Check if user already in LDAP wih email, first name and last name
400         filter_by = self.make_ldap_filters_from_record(user_ldap_attrs)
401         user_exist = self.LdapSearch(filter_by)
402         if user_exist:
403             logger.warning(" \r\n \t LDAP LdapAddUser user %s %s \
404                         already exists" %(user_ldap_attrs['sn'], \
405                         user_ldap_attrs['mail'])) 
406             return {'bool': False}
407         
408         #Bind to the server
409         result = self.conn.connect()
410         
411         if(result['bool']):
412             
413             # A dict to help build the "body" of the object
414             
415             logger.debug(" \r\n \t LDAP LdapAddUser attrs %s " %user_ldap_attrs)
416
417             # The dn of our new entry/object
418             dn = 'uid=' + user_ldap_attrs['uid'] + "," + self.baseDN 
419
420             try:
421                 ldif = modlist.addModlist(user_ldap_attrs)
422                 logger.debug("LDAPapi.py add attrs %s \r\n  ldif %s"\
423                                 %(user_ldap_attrs,ldif) )
424                 self.conn.ldapserv.add_s(dn,ldif)
425                 
426                 logger.info("Adding user %s login %s in LDAP" \
427                         %(user_ldap_attrs['cn'] ,user_ldap_attrs['uid']))
428                         
429                         
430             except ldap.LDAPError, error:
431                 logger.log_exc("LDAP Add Error %s" %error)
432                 return {'bool' : False, 'message' : error }
433         
434             self.conn.close()
435             return {'bool': True, 'uid':user_ldap_attrs['uid']}  
436         else: 
437             return result
438
439         
440     def LdapDelete(self, person_dn):
441         """
442         Deletes a person in LDAP. Uses the dn of the user.
443         """
444         #Connect and bind   
445         result =  self.conn.connect()
446         if(result['bool']):
447             try:
448                 self.conn.ldapserv.delete_s(person_dn)
449                 self.conn.close()
450                 return {'bool': True}
451             
452             except ldap.LDAPError, error:
453                 logger.log_exc("LDAP Delete Error %s" %error)
454                 return {'bool': False}
455         
456     
457     def LdapDeleteUser(self, record_filter): 
458         """
459         Deletes a SFA person in LDAP, based on the user's hrn.
460         """
461         #Find uid of the  person 
462         person = self.LdapFindUser(record_filter,[])
463         logger.debug("LDAPapi.py \t LdapDeleteUser record %s person %s" \
464         %(record_filter, person))
465
466         if person:
467             dn = 'uid=' + person['uid'] + "," +self.baseDN 
468         else:
469             return {'bool': False}
470         
471         result = self.LdapDelete(dn)
472         return result
473         
474
475     def LdapModify(self, dn, old_attributes_dict, new_attributes_dict): 
476         """ Modifies a LDAP entry """
477          
478         ldif = modlist.modifyModlist(old_attributes_dict,new_attributes_dict)
479         # Connect and bind/authenticate    
480         result = self.conn.connect() 
481         if (result['bool']): 
482             try:
483                 self.conn.ldapserv.modify_s(dn,ldif)
484                 self.conn.close()
485                 return {'bool' : True }
486             except ldap.LDAPError, error:
487                 logger.log_exc("LDAP LdapModify Error %s" %error)
488                 return {'bool' : False }
489     
490         
491     def LdapModifyUser(self, user_record, new_attributes_dict):
492         """
493         Gets the record from one user_uid_login based on record_filter 
494         and changes the attributes according to the specified new_attributes.
495         Does not use this if we need to modify the uid. Use a ModRDN 
496         #operation instead ( modify relative DN )
497         """
498         if user_record is None:
499             logger.error("LDAP \t LdapModifyUser Need user record  ")
500             return {'bool': False} 
501         
502         #Get all the attributes of the user_uid_login 
503         #person = self.LdapFindUser(record_filter,[])
504         req_ldap = self.make_ldap_filters_from_record(user_record)
505         person_list = self.LdapSearch(req_ldap,[])
506         logger.debug("LDAPapi.py \t LdapModifyUser person_list : %s" \
507                                                         %(person_list))
508         if person_list and len(person_list) > 1 :
509             logger.error("LDAP \t LdapModifyUser Too many users returned")
510             return {'bool': False}
511         if person_list is None :
512             logger.error("LDAP \t LdapModifyUser  User %s doesn't exist "\
513                         %(user_record))
514             return {'bool': False} 
515         
516         # The dn of our existing entry/object
517         #One result only from ldapSearch
518         person = person_list[0][1]
519         dn  = 'uid=' + person['uid'][0] + "," +self.baseDN  
520        
521         if new_attributes_dict:
522             old = {}
523             for k in new_attributes_dict:
524                 if k not in person:
525                     old[k] =  ''
526                 else :
527                     old[k] = person[k]
528             logger.debug(" LDAPapi.py \t LdapModifyUser  new_attributes %s"\
529                                 %( new_attributes_dict))  
530             result = self.LdapModify(dn, old,new_attributes_dict)
531             return result
532         else:
533             logger.error("LDAP \t LdapModifyUser  No new attributes given. ")
534             return {'bool': False} 
535             
536             
537             
538             
539     def LdapMarkUserAsDeleted(self, record): 
540
541         
542         new_attrs = {}
543         #Disable account
544         new_attrs['shadowExpire'] = '0'
545         logger.debug(" LDAPapi.py \t LdapMarkUserAsDeleted ")
546         ret = self.LdapModifyUser(record, new_attrs)
547         return ret
548
549             
550     def LdapResetPassword(self,record):
551         """
552         Resets password for the user whose record is the parameter and changes
553         the corresponding entry in the LDAP.
554         
555         """
556         password = self.generate_password()
557         attrs = {}
558         attrs['userPassword'] = self.encrypt_password(password)
559         logger.debug("LDAP LdapResetPassword encrypt_password %s"\
560                     %(attrs['userPassword']))
561         result = self.LdapModifyUser(record, attrs)
562         return result
563         
564         
565     def LdapSearch (self, req_ldap = None, expected_fields = None ):
566         """
567         Used to search directly in LDAP, by using ldap filters and
568         return fields. 
569         When req_ldap is None, returns all the entries in the LDAP.
570       
571         """
572         result = self.conn.connect(bind = False)
573         if (result['bool']) :
574             
575             return_fields_list = []
576             if expected_fields == None : 
577                 return_fields_list = ['mail','givenName', 'sn', 'uid', \
578                                         'sshPublicKey', 'shadowExpire']
579             else : 
580                 return_fields_list = expected_fields
581             #No specifc request specified, get the whole LDAP    
582             if req_ldap == None:
583                 req_ldap = '(cn=*)'
584                
585             logger.debug("LDAP.PY \t LdapSearch  req_ldap %s \
586                                     return_fields_list %s" \
587                                     %(req_ldap, return_fields_list))
588
589             try:
590                 msg_id = self.conn.ldapserv.search(
591                                             self.baseDN,ldap.SCOPE_SUBTREE,\
592                                             req_ldap, return_fields_list)     
593                 #Get all the results matching the search from ldap in one 
594                 #shot (1 value)
595                 result_type, result_data = \
596                                         self.conn.ldapserv.result(msg_id,1)
597
598                 self.conn.close()
599
600                 logger.debug("LDAP.PY \t LdapSearch  result_data %s"\
601                             %(result_data))
602
603                 return result_data
604             
605             except  ldap.LDAPError,error :
606                 logger.log_exc("LDAP LdapSearch Error %s" %error)
607                 return []
608             
609             else:
610                 logger.error("LDAP.PY \t Connection Failed" )
611                 return 
612         
613     def LdapFindUser(self, record = None, is_user_enabled=None, \
614             expected_fields = None):
615         """
616         Search a SFA user with a hrn. User should be already registered 
617         in Senslab LDAP. 
618         Returns one matching entry 
619         """   
620         custom_record = {}
621         if is_user_enabled: 
622           
623             custom_record['enabled'] = is_user_enabled
624         if record:  
625             custom_record.update(record)
626
627
628         req_ldap = self.make_ldap_filters_from_record(custom_record)     
629         return_fields_list = []
630         if expected_fields == None : 
631             return_fields_list = ['mail','givenName', 'sn', 'uid', \
632                                     'sshPublicKey']
633         else : 
634             return_fields_list = expected_fields
635             
636         result_data = self.LdapSearch(req_ldap, return_fields_list )
637         logger.debug("LDAP.PY \t LdapFindUser  result_data %s" %(result_data))
638            
639         if len(result_data) is 0:
640             return None
641         #Asked for a specific user
642         if record :
643             #try:
644             ldapentry = result_data[0][1]
645             logger.debug("LDAP.PY \t LdapFindUser ldapentry %s" %(ldapentry))
646             tmpname = ldapentry['uid'][0]
647
648             tmpemail = ldapentry['mail'][0]
649             if ldapentry['mail'][0] == "unknown":
650                 tmpemail = None
651                     
652             parent_hrn = None
653             peer_authority = None    
654             if 'hrn' in record:
655                 hrn = record['hrn']
656                 parent_hrn = get_authority(hrn)
657                 if parent_hrn != self.authname:
658                     peer_authority = parent_hrn
659                 #In case the user was not imported from Senslab LDAP
660                 #but from another federated site, has an account in 
661                 #senslab but currently using his hrn from federated site
662                 #then the login is different from the one found in its hrn    
663                 if tmpname != hrn.split('.')[1]:
664                     hrn = None
665             else:
666                 hrn = None
667                 
668                
669                 
670             results =  {        
671                         'type': 'user',
672                         'pkey': ldapentry['sshPublicKey'][0],
673                         #'uid': ldapentry[1]['uid'][0],
674                         'uid': tmpname ,
675                         'email':tmpemail,
676                         #'email': ldapentry[1]['mail'][0],
677                         'first_name': ldapentry['givenName'][0],
678                         'last_name': ldapentry['sn'][0],
679                         #'phone': 'none',
680                         'serial': 'none',
681                         'authority': parent_hrn,
682                         'peer_authority': peer_authority,
683                         'pointer' : -1,
684                         'hrn': hrn,
685                         }
686             #except KeyError,error:
687                 #logger.log_exc("LDAPapi \t LdaFindUser KEyError %s" \
688                                 #%error )
689                 #return
690         else:
691         #Asked for all users in ldap
692             results = []
693             for ldapentry in result_data:
694                 logger.debug(" LDAP.py LdapFindUser ldapentry name : %s " \
695                                 %(ldapentry[1]['uid'][0]))
696                 tmpname = ldapentry[1]['uid'][0]
697                 hrn=self.authname+"."+ tmpname
698                 
699                 tmpemail = ldapentry[1]['mail'][0]
700                 if ldapentry[1]['mail'][0] == "unknown":
701                     tmpemail = None
702
703         
704                 parent_hrn = get_authority(hrn)
705                 parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
706                 try:
707                     results.append(  {  
708                             'type': 'user',
709                             'pkey': ldapentry[1]['sshPublicKey'][0],
710                             #'uid': ldapentry[1]['uid'][0],
711                             'uid': tmpname ,
712                             'email':tmpemail,
713                             #'email': ldapentry[1]['mail'][0],
714                             'first_name': ldapentry[1]['givenName'][0],
715                             'last_name': ldapentry[1]['sn'][0],
716                             #'phone': 'none',
717                             'serial': 'none',
718                             'authority': self.authname,
719                             'peer_authority': '',
720                             'pointer' : -1,
721                             'hrn': hrn,
722                             } ) 
723                 except KeyError,error:
724                     logger.log_exc("LDAPapi.PY \t LdapFindUser EXCEPTION %s" \
725                                                 %(error))
726                     return
727         return results   
728