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