Rmoved parse_filter in GetPersons.
[sfa.git] / sfa / senslab / LDAPapi.py
1
2 import string
3 from sfa.util.xrn import Xrn,get_authority 
4 import ldap
5 from sfa.util.config import *
6 from sfa.trust.gid import *
7 from sfa.trust.hierarchy import *
8 from sfa.trust.auth import *
9 from sfa.trust.certificate import *
10 import ldap.modlist as modlist
11
12 class ldap_co:
13     def __init__(self):
14     #def __init__(self, param, level):
15         """
16         Constructeur permettant l'initialisation des attributs de la classe
17         :param param: Parametres de connexion au serveur LDAP
18         :type param: dictionnary.
19         :param level: Niveau de criticite de l'execution de l'objet ('critical, warning')
20         :type level: string.
21         """
22
23         self.__level = 'warning'
24         #self.__param = param
25         #self.__level = level
26         self.login = 'cn=admin,dc=senslab,dc=info'
27     
28         self.passwd='sfa'  
29         print "\r\n INIT OK !"
30     
31     def connect(self, bind = True):
32         """
33         Methode permettant la connexion a un serveur LDAP
34         @param bool bind : Force ou non l'authentification au serveur
35         @return array : Retour d'un tableau
36         """
37         try:
38             self.ldapserv = ldap.open("192.168.0.251")
39         except ldap.LDAPError, e:
40             return {'bool' : False, 'message' : e }
41         
42         # Bind non anonyme avec authentification
43         if(bind): 
44             return self.bind()
45         
46         else:     
47             return {'bool': True}
48     
49     
50     def bind(self):
51         """
52         Methode permettant l'authentification a un serveur LDAP
53         @return array : Retour d'un tableau
54         """
55         try:
56             print "\r\n BIND ??!"
57             # Open a connection
58             self.ldapserv = ldap.initialize("ldap://192.168.0.251")    
59             ## Bind/authenticate with a user with apropriate rights to add objects
60             self.ldapserv.simple_bind_s(self.login, self.passwd)
61             print "\r\n BIND ???"
62         except ldap.LDAPError, e:
63             return {'bool' : False, 'message' : e }
64         
65         print "\r\n BIND OK !"
66         return {'bool': True}
67     
68     def close(self):
69         """
70         Methode permettant la deconnexion a un serveur LDAP
71         """
72         # Fermeture de la connexion
73         try:
74             self.ldapserv.unbind_s()
75         except ldap.LDAPError, e:
76             pass
77             
78         
79 class LDAPapi :
80         def __init__(self, record_filter = None):
81                 self.senslabauth=Hierarchy()
82                 config=Config()
83                 self.authname=config.SFA_REGISTRY_ROOT_AUTH
84                 authinfo=self.senslabauth.get_auth_info(self.authname)
85         
86         
87                 self.auth=Auth()
88                 gid=authinfo.get_gid_object()
89                 self.ldapdictlist = ['type',
90                                 'pkey',
91                                 'uid',
92                                 'serial',
93                                 'authority',
94                                 'peer_authority',
95                                 'pointer' ,
96                                 'hrn']
97                 self.baseDN = "ou=people,dc=senslab,dc=info"
98                 self.conn =  ldap_co()    
99                           
100         #def connect (self):
101            #self.ldapserv=ldap.open("192.168.0.251")
102            
103         #def authenticate(self):
104             #self.l = ldap.initialize("ldaps://192.168.0.251:636/")
105             #login = 'cn=admin,dc=senslab,dc=info'
106     
107             #passwd='sfa-ldap'  
108             ## Bind/authenticate with a user with apropriate rights to add objects
109             #self.l = simple_bind_s(login,passwd)
110                               
111         def ldapAdd(self, recordix = None) :
112             attrs = {'cn': ['Bruce Wayne'], 'objectClass': ['top', 'inetOrgPerson', 'posixAccount', 'systemQuotas', 'ldapPublicKey'], 'loginShell': '/senslab/users/.ssh/welcome.sh', 'sshPublicKey': '', 'quota': '/dev/sda3:2000000:2500000:0:0', 'gidNumber': '2000', 'sn': 'Wayne', 'homeDirectory': '/senslab/users/batman', 'mail': 'bw@gotham.com', 'givenName': 'Bruce', 'uid': 'batman','description' :'SFA USER FROM OUTSIDE SENSLAB'}
113             result = self.conn.connect()
114             if(result['bool']):
115                 # The dn of our new entry/object
116                 dn = self.baseDN  
117                 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t  ldapAdd  attrs %s " %(attrs)
118                 # A dict to help build the "body" of the object
119                 #attrs = {}
120                 #attrs['objectclass'] = ['top','inetOrgPerson','posixAccount', 'systemQuotas','ldapPuclicKey']
121                 #attrs['cn'] = str(record['first_name'])+' ' + str(record['last_name'])
122                 #attrs['sn'] = str(record['last_name'])
123                 #attrs['givenName'] = str(record['first_name'])
124                 #attrs['gidNumber'] = '2000'
125                 #loginslab =str(record['first_name'])+ str(record['last_name'])
126                 #loginslab= loginslab.lower()
127                 ##loginslab  = loginslab[0:12]
128                 #attrs['uid']= loginslab
129                 #attrs['mail'] = record['mail']
130                 #attrs['quota'] = '/dev/sda3:2000000:2500000:0:0'
131                 #attrs['homeDirectory'] = '/senslab/users/' + loginslab
132                 #attrs['loginShell'] = '/senslab/users/.ssh/welcome.sh'
133                 #attrs['sshPublicKey'] = ''
134                 #attrs['description'] = 'SFA USER FROM OUTSIDE SENSLAB'
135                 category ="ou=people, dc=senslab, dc=info"   
136                 try:
137                         ldif = modlist.addModlist(attrs)
138                         print " \r\n \r\n LDAPTEST.PY add attrs %s \r\n  ldif %s  " %(attrs,ldif)
139                         self.conn.ldapserv.add_s('%s,%s' %(dn, category),ldif)
140                 except ldap.LDAPError, e:
141                     return {'bool' : False, 'message' : e }
142             
143                 self.close()
144                 return {'bool': True}  
145             else: 
146                 return result
147                 return  
148          
149          
150         def ldapModify(self, record_filter, new_fileds):
151             person = self.ldapSearch(record_filter)
152             if person:
153                 result = self.conn.connect()
154                 if(result['bool']):
155                     req_ldap = self.parse_record(record_filter)
156               
157         #TODO Handle OR filtering in the ldap query when 
158         #dealing with a list of records instead of doing a for loop in GetPersons                                  
159         def parse_record(self, record=None):
160             
161             req_ldapdict = {}
162             if record :
163                 if 'first_name' in record  and 'last_name' in record:
164                     req_ldapdict['cn'] = str(record['first_name'])+" "+str(record['last_name'])
165                 if 'email' in record :
166                     req_ldapdict['mail'] = record['email']
167                 if 'hrn' in record :
168                     splited_hrn = record['hrn'].split(".")
169                     if splited_hrn[0] != self.authname :
170                             print >>sys.stderr,"i know nothing about",record['hrn'], " my authname is ", self.authname, " not ", splited_hrn[0]
171                     login=splited_hrn[1]
172                     if login == 'avakian':
173                         login = 'savakian'
174                     req_ldapdict['uid'] = login
175                 
176                 req_ldap=''
177                 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t   parse_record record %s req_ldapdict %s" %(record,req_ldapdict)
178                 for k in req_ldapdict:
179                     req_ldap += '('+str(k)+'='+str(req_ldapdict[k])+')'
180                 if  len(req_ldapdict.keys()) >1 :
181                     req_ldap = req_ldap[:0]+"(&"+req_ldap[0:]
182                     size = len(req_ldap)
183                     req_ldap= req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
184             else:
185                 req_ldap = "(cn*)"
186             
187             return req_ldap
188
189             
190             
191         #Returns one matching entry                                
192         def ldapSearch (self, record = None ):
193             
194             self.conn.connect(bind = False)
195             #self.connect()
196             req_ldap = self.parse_record(record)
197             print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapSearch  req_ldap %s" %(req_ldap)
198             try:
199                 msg_id=self.conn.ldapserv.search(self.baseDN,ldap.SCOPE_SUBTREE,req_ldap, ['mail','givenName', 'sn', 'uid','sshPublicKey'])     
200                 #Get all the results matching the search from ldap in one shot (1 value)
201                 result_type, result_data = self.conn.ldapserv.result(msg_id,1)
202                 #results = []
203                 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapSearch  result_data %s" %(result_data) 
204                 
205                 #Asked for a specific user
206                 if record:
207                     ldapentry = result_data[0][1]
208                     print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapSearch  ldapentry %s" %(ldapentry) 
209                     tmpname = ldapentry['uid'][0]
210                     
211                     if ldapentry['uid'][0] == "savakian":
212                         tmpname = 'avakian'
213     
214                     tmpemail = ldapentry['mail'][0]
215                     if ldapentry['mail'][0] == "unknown":
216                         tmpemail = None
217                         
218                     hrn = record['hrn']
219                     parent_hrn = get_authority(hrn)
220                     peer_authority = None
221                     if parent_hrn is not self.authname:
222                         peer_authority = parent_hrn
223                             
224                     #results.append(  { 
225                                     #'type': 'user',
226                                     #'pkey': ldapentry['sshPublicKey'][0],
227                                     ##'uid': ldapentry[1]['uid'][0],
228                                     #'uid': tmpname ,
229                                     #'email':tmpemail,
230                                     ##'email': ldapentry[1]['mail'][0],
231                                     #'first_name': ldapentry['givenName'][0],
232                                     #'last_name': ldapentry['sn'][0],
233     ##                          'phone': 'none',
234                                     #'serial': 'none',
235                                     #'authority': parent_hrn,
236                                     #'peer_authority': peer_authority,
237                                     #'pointer' : -1,
238                                     #'hrn': hrn,
239                                     #} )
240                                     
241                     results=  { 
242                                 'type': 'user',
243                                 'pkey': ldapentry['sshPublicKey'][0],
244                                 #'uid': ldapentry[1]['uid'][0],
245                                 'uid': tmpname ,
246                                 'email':tmpemail,
247                                 #'email': ldapentry[1]['mail'][0],
248                                 'first_name': ldapentry['givenName'][0],
249                                 'last_name': ldapentry['sn'][0],
250                                 #'phone': 'none',
251                                 'serial': 'none',
252                                 'authority': parent_hrn,
253                                 'peer_authority': peer_authority,
254                                 'pointer' : -1,
255                                 'hrn': hrn,
256                                 } 
257                 else:
258                 #Asked for all users in ldap
259                     results = []
260                     for ldapentry in result_data[1]:
261                          
262                         tmpname = ldapentry[1]['uid'][0]
263                         
264                         if ldapentry[1]['uid'][0] == "savakian":
265                             tmpname = 'avakian'
266
267                         hrn=self.authname+"."+ tmpname
268                         
269                         tmpemail = ldapentry[1]['mail'][0]
270                         if ldapentry[1]['mail'][0] == "unknown":
271                             tmpemail = None
272
273                 
274                         parent_hrn = get_authority(hrn)
275                         parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
276
277                         results.append(  {      
278                                 'type': 'user',
279                                 'pkey': ldapentry[1]['sshPublicKey'][0],
280                                 #'uid': ldapentry[1]['uid'][0],
281                                 'uid': tmpname ,
282                                 'email':tmpemail,
283                                 #'email': ldapentry[1]['mail'][0],
284                                 'first_name': ldapentry[1]['givenName'][0],
285                                 'last_name': ldapentry[1]['sn'][0],
286 #                               'phone': 'none',
287                                 'serial': 'none',
288                                 'authority': self.authname,
289                                 'peer_authority': '',
290                                 'pointer' : -1,
291                                 'hrn': hrn,
292                                 } )   
293                 return results
294
295             
296             except  ldap.LDAPError,e :
297                 print >>sys.stderr, "ERROR LDAP %s" %(e)
298                
299         
300
301         
302         def ldapFindHrn(self, record_filter = None):        
303         #def ldapFindHrn(self, record_filter = None, columns=None):
304
305                 results = [] 
306                 self.conn.connect(bind = False)
307                 #self.connect()
308                 if 'authority' in record_filter:
309                 # ask for authority
310                         if record_filter['authority']==self.authname:
311                                 # which is SFA_REGISTRY_ROOT_AUTH
312                                 # request all records which are under our authority, ie all ldap entries
313                                 ldapfilter="cn=*"
314                         else:
315                                 #which is NOT SFA_REGISTRY_ROOT_AUTH
316                                 return []
317                 else :
318                         if not 'hrn' in record_filter:
319                                 print >>sys.stderr,"find : don't know how to handle filter ",record_filter
320                                 return []
321                         else:
322                                 hrns=[]
323                                 h=record_filter['hrn']
324                                 if  isinstance(h,list):
325                                         hrns=h
326                                 else : 
327                                         hrns.append(h)
328         
329                                 ldapfilter="(|"
330                                 for hrn in hrns:
331                                         splited_hrn=hrn.split(".")
332                                         if splited_hrn[0] != self.authname :
333                                                 print >>sys.stderr,"i know nothing about",hrn, " my authname is ", self.authname, " not ", splited_hrn[0]
334                                         else :
335                                                 login=splited_hrn[1]
336                                                 ldapfilter+="(uid="
337                                                 ldapfilter+=login
338                                                 ldapfilter+=")"
339                                 ldapfilter+=")"
340         
341                 rindex=self.conn.ldapserv.search(self.baseDN,ldap.SCOPE_SUBTREE,ldapfilter, ['mail','givenName', 'sn', 'uid','sshPublicKey'])
342                 #rindex=self.ldapserv.search(self.baseDN,ldap.SCOPE_SUBTREE,ldapfilter, ['mail','givenName', 'sn', 'uid','sshPublicKey'])
343                 ldapresponse=self.conn.ldapserv.result(rindex,1)
344                 for ldapentry in ldapresponse[1]:
345                          
346                         tmpname = ldapentry[1]['uid'][0]
347                         
348                         if ldapentry[1]['uid'][0] == "savakian":
349                             tmpname = 'avakian'
350
351                         hrn=self.authname+"."+ tmpname
352                         
353                         tmpemail = ldapentry[1]['mail'][0]
354                         if ldapentry[1]['mail'][0] == "unknown":
355                             tmpemail = None
356 #                       uuid=create_uuid() 
357                 
358 #                       RSA_KEY_STRING=ldapentry[1]['sshPublicKey'][0]
359                 
360 #                       pkey=convert_public_key(RSA_KEY_STRING)
361                 
362 #                       gid=self.senslabauth.create_gid("urn:publicid:IDN+"+self.authname+"+user+"+ldapentry[1]['uid'][0], uuid, pkey, CA=False)
363                 
364                         parent_hrn = get_authority(hrn)
365                         parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
366
367                         results.append(  {      
368                                 'type': 'user',
369                                 'pkey': ldapentry[1]['sshPublicKey'][0],
370                                 #'uid': ldapentry[1]['uid'][0],
371                                 'uid': tmpname ,
372                                 'email':tmpemail,
373                                 #'email': ldapentry[1]['mail'][0],
374                                 'first_name': ldapentry[1]['givenName'][0],
375                                 'last_name': ldapentry[1]['sn'][0],
376 #                               'phone': 'none',
377                                 'serial': 'none',
378                                 'authority': self.authname,
379                                 'peer_authority': '',
380                                 'pointer' : -1,
381                                 'hrn': hrn,
382                                 } )
383                 return results