Added function DeletePerson in SlabDriver:
[sfa.git] / sfa / senslab / LDAPapi.py
index 28b2b06..30ce8b6 100644 (file)
@@ -1,12 +1,10 @@
-
-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.hierarchy import Hierarchy
-from sfa.trust.certificate import *
+#from sfa.trust.certificate import *
 import ldap.modlist as modlist
 from sfa.util.sfalogging import logger
 import os.path
@@ -24,7 +22,7 @@ class ldap_config():
             self.config_file = config_file
             # path to configuration data
             self.config_path = os.path.dirname(config_file)
-        except IOError, e:
+        except IOError, error:
             raise IOError, "Could not find or load the configuration file: %s" % config_file
         
 class ldap_co:
@@ -35,16 +33,15 @@ class ldap_co:
         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.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.ldapPort = ldap.PORT
+        self.ldapVersion  = ldap.VERSION3
+        self.ldapSearchScope = ldap.SCOPE_SUBTREE
 
 
     def connect(self, bind = True):
@@ -56,8 +53,8 @@ class ldap_co:
         """
         try:
             self.ldapserv = ldap.open(self.ldapHost)
-        except ldap.LDAPError, e:
-            return {'bool' : False, 'message' : e }
+        except ldap.LDAPError, error:
+            return {'bool' : False, 'message' : error }
         
         # Bind with authentification
         if(bind): 
@@ -75,8 +72,8 @@ class ldap_co:
             # Bind/authenticate with a user with apropriate rights to add objects
             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}
     
@@ -84,18 +81,18 @@ 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() 
+        logger.setLevelDebug() 
         #SFA related config
-        self.senslabauth=Hierarchy()
-        config=Config()
+        self.senslabauth = Hierarchy()
+        config = Config()
         
-        self.authname=config.SFA_REGISTRY_ROOT_AUTH
+        self.authname = config.SFA_REGISTRY_ROOT_AUTH
 
         self.conn =  ldap_co() 
         self.ldapUserQuotaNFS = self.conn.config.LDAP_USER_QUOTA_NFS 
@@ -103,7 +100,7 @@ class LDAPapi :
         self.ldapUserGidNumber = self.conn.config.LDAP_USER_GID_NUMBER 
         self.ldapUserHomePath = self.conn.config.LDAP_USER_HOME_PATH 
         
-        self.lengthPassword = 8
+        self.lengthPassword = 8
         self.baseDN = self.conn.ldapPeopleDN
         #authinfo=self.senslabauth.get_auth_info(self.authname)
         
@@ -142,7 +139,7 @@ class LDAPapi :
         getAttrs = ['uid']
         if length_last_name >= login_max_length :
             login = lower_last_name[0:login_max_length]
-            index = 0;
+            index = 0
             logger.debug("login : %s index : %s" %(login,index))
         elif length_last_name >= 4 :
             login = lower_last_name
@@ -168,11 +165,11 @@ class LDAPapi :
                             impossible to generate unique login for %s %s" \
                             %(lower_first_name,lower_last_name))
             
-        filter = '(uid=' + login + ')'
+        login_filter = '(uid=' + login + ')'
         
         try :
             #Check if login already in use
-            while (len(self.LdapSearch(filter, getAttrs)) is not 0 ):
+            while (len(self.LdapSearch(login_filter, getAttrs)) is not 0 ):
             
                 index += 1
                 if index >= 9:
@@ -182,15 +179,15 @@ class LDAPapi :
                     try:
                         login = lower_first_name[0:index] + \
                                     lower_last_name[0:login_max_length-index]
-                        filter = '(uid='+ login+ ')'
+                        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
 
         
@@ -210,13 +207,13 @@ class LDAPapi :
         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)
     
 
 
@@ -229,9 +226,9 @@ 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
@@ -244,19 +241,21 @@ class LDAPapi :
             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 'A REMPLIR '
          
          
-    #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:
@@ -266,6 +265,11 @@ 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 
@@ -284,17 +288,17 @@ class LDAPapi :
                 #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=*)"
         
@@ -389,9 +393,9 @@ class LDAPapi :
                         %(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}  
@@ -411,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}
         
     
@@ -423,7 +427,7 @@ class LDAPapi :
         #Find uid of the  person 
         person = self.LdapFindUser(record_filter,[])
         logger.debug("LDAPapi.py \t LdapDeleteUser record %s person %s" \
-        %(record_filter,person))
+        %(record_filter, person))
 
         if person:
             dn = 'uid=' + person['uid'] + "," +self.baseDN 
@@ -445,8 +449,8 @@ class LDAPapi :
                 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 }
     
         
@@ -471,7 +475,7 @@ class LDAPapi :
             return {'bool': False}
         if person_list is None :
             logger.error("LDAP \t LdapModifyUser  User %s doesn't exist "\
-                        %(user_uid_login))
+                        %(user_record))
             return {'bool': False} 
         
         # The dn of our existing entry/object
@@ -495,6 +499,19 @@ class LDAPapi :
             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
@@ -522,20 +539,22 @@ class LDAPapi :
             
             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, gert the whole LDAP    
+            #No specifc request specified, get the whole LDAP    
             if req_ldap == None:
-               req_ldap = '(cn=*)'
+                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 = \
@@ -548,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:
@@ -615,9 +644,9 @@ class LDAPapi :
                             'pointer' : -1,
                             'hrn': hrn,
                             }
-            except KeyError,e:
+            except KeyError,error:
                 logger.log_exc("LDAPapi \t LdaFindUser KEyError %s" \
-                                %e )
+                                %error )
                 return
         else:
         #Asked for all users in ldap
@@ -652,8 +681,8 @@ class LDAPapi :
                             'pointer' : -1,
                             'hrn': hrn,
                             } ) 
-                except KeyError,e:
-                    logger.log_exc("LDAPapi.PY \t LdapFindUser EXCEPTION %s" %(e))
+                except KeyError,error:
+                    logger.log_exc("LDAPapi.PY \t LdapFindUser EXCEPTION %s" %(error))
                     return
         return results