Further changes to handle federated user .
[sfa.git] / sfa / senslab / LDAPapi.py
index f0ecb58..55e3c0f 100644 (file)
@@ -4,7 +4,7 @@ from sfa.util.xrn import get_authority
 import ldap
 from sfa.util.config import Config
 from sfa.trust.hierarchy import Hierarchy
-#from sfa.trust.certificate import *
+
 import ldap.modlist as modlist
 from sfa.util.sfalogging import logger
 import os.path
@@ -12,31 +12,33 @@ import os.path
 #API for OpenLDAP
 
 
-class ldap_config():
+class LdapConfig():
     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
+        except IOError:
+            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):
-        #Senslab PROD LDAP parameters 
-        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
+        #Senslab PROD LDAP parameters
+        self.ldapserv = None
+        ldap_config = LdapConfig()
+        self.config = ldap_config
+        self.ldapHost = ldap_config.LDAP_IP_ADDRESS 
+        self.ldapPeopleDN = ldap_config.LDAP_PEOPLE_DN
+        self.ldapGroupDN = ldap_config.LDAP_GROUP_DN
+        self.ldapAdminDN = ldap_config.LDAP_WEB_DN
+        self.ldapAdminPassword = ldap_config.LDAP_WEB_PASSWORD
 
 
         self.ldapPort = ldap.PORT
@@ -69,8 +71,10 @@ class ldap_co:
             # Opens a connection after a call to ldap.open in connect:
             self.ldapserv = ldap.initialize("ldap://" + self.ldapHost)
                 
-            # Bind/authenticate with a user with apropriate rights to add objects
-            self.ldapserv.simple_bind_s(self.ldapAdminDN, self.ldapAdminPassword)
+            # Bind/authenticate with a user with apropriate 
+            #rights to add objects
+            self.ldapserv.simple_bind_s(self.ldapAdminDN, \
+                                    self.ldapAdminPassword)
 
         except ldap.LDAPError, error:
             return {'bool' : False, 'message' : error }
@@ -105,13 +109,13 @@ class LDAPapi :
         #authinfo=self.senslabauth.get_auth_info(self.authname)
         
         
-        self.charsPassword = [ '!','$','(',')','*','+',',','-','.',\
-                                '0','1','2','3','4','5','6','7','8','9',\
-                                'A','B','C','D','E','F','G','H','I','J',\
-                                'K','L','M','N','O','P','Q','R','S','T',\
-                                'U','V','W','X','Y','Z','_','a','b','c',\
-                                'd','e','f','g','h','i','j','k','l','m',\
-                                'n','o','p','q','r','s','t','u','v','w',\
+        self.charsPassword = [ '!','$','(',')','*','+',',','-','.', \
+                                '0','1','2','3','4','5','6','7','8','9', \
+                                'A','B','C','D','E','F','G','H','I','J', \
+                                'K','L','M','N','O','P','Q','R','S','T', \
+                                'U','V','W','X','Y','Z','_','a','b','c', \
+                                'd','e','f','g','h','i','j','k','l','m', \
+                                'n','o','p','q','r','s','t','u','v','w', \
                                 'x','y','z','\'']
         
         self.ldapShell = '/bin/bash'
@@ -123,16 +127,44 @@ class LDAPapi :
         Record contains first name and last name.
         
         """ 
-        #Remove all special characters from first_name/last name
-        lower_first_name = record['first_name'].replace('-','')\
-                                        .replace('_','').replace('[','')\
-                                        .replace(']','').replace(' ','')\
-                                        .lower()
-        lower_last_name = record['last_name'].replace('-','')\
-                                        .replace('_','').replace('[','')\
-                                        .replace(']','').replace(' ','')\
-                                        .lower()  
-        length_last_name = len(lower_last_name)
+        if 'first_name' in record and 'last_name' in record:
+            #Remove all special characters from first_name/last name
+            lower_first_name = record['first_name'].replace('-','')\
+                                            .replace('_','').replace('[','')\
+                                            .replace(']','').replace(' ','')\
+                                            .lower()
+            lower_last_name = record['last_name'].replace('-','')\
+                                            .replace('_','').replace('[','')\
+                                            .replace(']','').replace(' ','')\
+                                            .lower()  
+
+            
+        #No first name and last name 
+        #check  email    
+        else:
+            #For compatibility with other ldap func
+            if 'mail' in record and 'email' not in record:
+                record['email'] = record['mail']
+            email = record['email']
+            email = email.split('@')[0].lower()
+            lower_first_name = None
+            lower_last_name = None
+            #Assume there is first name and last name in email
+            #if there is a  separator
+            separator_list = ['.','_','-']
+            for sep in separator_list:
+                if sep in email:
+                    mail = email.split(sep)
+                    lower_first_name = mail[0]
+                    lower_last_name = mail[1]
+                    break
+            #Otherwise just take the part before the @ as the 
+            #lower_first_name  and lower_last_name
+            if lower_first_name is None:
+               lower_first_name = email
+               lower_last_name = email
+               
+        length_last_name = len(lower_last_name)  
         login_max_length = 8
         
         #Try generating a unique login based on first name and last name
@@ -140,20 +172,20 @@ class LDAPapi :
         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))
+            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 \
@@ -186,7 +218,7 @@ class LDAPapi :
             logger.debug("LDAP.API \t generate_login login %s" %(login))
             return login
                     
-        except  ldap.LDAPError,error :
+        except  ldap.LDAPError, error :
             logger.log_exc("LDAP generate_login Error %s" %error)
             return None
 
@@ -201,7 +233,7 @@ class LDAPapi :
         password = str()
         length = len(self.charsPassword)
         for index in range(self.lengthPassword):
-            char_index = random.randint(0,length-1)
+            char_index = random.randint(0, length-1)
             password += self.charsPassword[char_index]
 
         return password
@@ -213,7 +245,7 @@ class LDAPapi :
         """
         #Keep consistency with Java Senslab's LDAP API 
         #RFC2307SSHAPasswordEncryptor so set the salt size to 8 bytres
-        return lssha.encrypt(password,salt_size = 8)
+        return lssha.encrypt(password, salt_size = 8)
     
 
 
@@ -277,17 +309,7 @@ class LDAPapi :
             #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]) )
-                        
-                #login=splited_hrn[1]
-                #req_ldapdict['uid'] = login
-            
+           
 
             logger.debug("\r\n \t LDAP.PY make_ldap_filters_from_record \
                                 record %s req_ldapdict %s" \
@@ -311,17 +333,26 @@ class LDAPapi :
         """
 
         attrs = {}
-        attrs['objectClass'] = ["top", "person", "inetOrgPerson",\
-                                    "organizationalPerson", "posixAccount",\
-                                    "shadowAccount", "systemQuotas",\
+        attrs['objectClass'] = ["top", "person", "inetOrgPerson", \
+                                    "organizationalPerson", "posixAccount", \
+                                    "shadowAccount", "systemQuotas", \
                                     "ldapPublicKey"]
-        
-        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']
+       
+            
         attrs['uid'] = self.generate_login(record)   
-                    
+        try:
+            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']
+            
+        except: 
+            attrs['givenName'] = attrs['uid']
+            attrs['sn'] = attrs['uid']
+            attrs['cn'] = attrs['uid']
+            attrs['gecos'] = attrs['uid']
+            
+                     
         attrs['quota'] = self.ldapUserQuotaNFS 
         attrs['homeDirectory'] = self.ldapUserHomePath + attrs['uid']
         attrs['loginShell'] = self.ldapShell
@@ -341,7 +372,7 @@ class LDAPapi :
         #If the user wants to set his own password , he must go to the Senslab 
         #website.
         password = self.generate_password()
-        attrs['userPassword']= self.encrypt_password(password)
+        attrs['userPassword'] = self.encrypt_password(password)
         
         #Account automatically validated (no mail request to admins)
         #Set to 0 to disable the account, -1 to enable it,
@@ -361,7 +392,7 @@ class LDAPapi :
 
     def LdapAddUser(self, record) :
         """Add SFA user to LDAP if it is not in LDAP  yet. """
-        
+        logger.debug(" \r\n \t LDAP LdapAddUser \r\n\r\n =====================================================\r\n ")
         user_ldap_attrs = self.make_ldap_attributes_from_record(record)
 
         
@@ -369,8 +400,9 @@ class LDAPapi :
         filter_by = self.make_ldap_filters_from_record(user_ldap_attrs)
         user_exist = self.LdapSearch(filter_by)
         if user_exist:
-            logger.warning(" \r\n \t LDAP LdapAddUser user %s %s already exists" \
-                            %(user_ldap_attrs['sn'],user_ldap_attrs['mail'])) 
+            logger.warning(" \r\n \t LDAP LdapAddUser user %s %s \
+                        already exists" %(user_ldap_attrs['sn'], \
+                        user_ldap_attrs['mail'])) 
             return {'bool': False}
         
         #Bind to the server
@@ -400,7 +432,7 @@ class LDAPapi :
                 return {'bool' : False, 'message' : error }
         
             self.conn.close()
-            return {'bool': True}  
+            return {'bool': True, 'uid':user_ldap_attrs['uid']}  
         else: 
             return result
 
@@ -471,7 +503,8 @@ class LDAPapi :
         #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))
+        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}
@@ -625,9 +658,15 @@ class LDAPapi :
                 hrn = record['hrn']
                 parent_hrn = get_authority(hrn)
                 peer_authority = None
-                if parent_hrn is not self.authname:
+                if parent_hrn != self.authname:
                     peer_authority = parent_hrn
-
+                    
+                #In case the user was not imported from Senslab LDAP
+                #but from another federated site, has an account in 
+                #senslab but currently using his hrn from federated site
+                #then the login is different from the one found in its hrn
+                if tmpname != hrn.split('.')[1]:
+                    hrn = None
                 results =  {   
                             'type': 'user',
                             'pkey': ldapentry['sshPublicKey'][0],
@@ -682,7 +721,8 @@ class LDAPapi :
                             'hrn': hrn,
                             } ) 
                 except KeyError,error:
-                    logger.log_exc("LDAPapi.PY \t LdapFindUser EXCEPTION %s" %(error))
+                    logger.log_exc("LDAPapi.PY \t LdapFindUser EXCEPTION %s" \
+                                                %(error))
                     return
         return results