Merge branch 'onelab' of ssh://git.onelab.eu/git/myslice into onelab
[myslice.git] / portal / actions.py
1 from django.http                import HttpResponse
2 from manifold.core.query        import Query
3 from manifoldapi.manifoldapi    import execute_query,execute_admin_query
4 from portal.models              import PendingUser, PendingSlice, PendingAuthority
5 import json
6
7 from django.contrib.auth.models  import User
8 from django.contrib.sites.models import Site
9 from django.contrib.auth        import get_user_model
10 from django.template.loader     import render_to_string
11 from django.core.mail           import EmailMultiAlternatives, send_mail
12
13 from myslice.theme              import ThemeView
14 from myslice.configengine       import ConfigEngine
15
16
17 theme = ThemeView()
18
19 import activity.slice
20
21 # Thierry: moving this right into the code so 
22 # most people can use myslice without having to install sfa
23 # XXX tmp sfa dependency, should be moved to SFA gateway
24 #from sfa.util.xrn                import Xrn 
25
26
27 # Get the list of pis in a given authority
28 def authority_get_pis(request, authority_hrn):
29
30     # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
31     query = Query.get('authority').filter_by('authority_hrn', '==', authority_hrn).select('pi_users')
32     results = execute_admin_query(request, query)
33     print "authority_get_pis = %s" % results
34     # NOTE: temporarily commented. Because results is giving empty list. 
35     # Needs more debugging
36     #if not results:
37     #    raise Exception, "Authority not found: %s" % authority_hrn
38     #result, = results
39     #return result['pi_users']
40     return results
41
42 #check the user is pi or not in the registry
43 def authority_check_pis(request, user_email):
44     try:
45         user_query  = Query().get('local:user').filter_by('email', '==', user_email).select('user_id','email','password','config')
46         user_details = execute_admin_query(request, user_query)
47     
48         # getting the authority_hrn
49         for user_detail in user_details:
50             user_id = user_detail['user_id']
51             if user_detail['config']:
52                 config = json.loads(user_detail['config'])
53                 authority_hrn = config.get('authority','Unknown Authority')
54  
55         account_query  = Query().get('local:account').filter_by('user_id', '==', user_id).select('user_id','platform_id','auth_type','config')
56         account_details = execute_admin_query(request, account_query)
57     
58         platform_query  = Query().get('local:platform').select('platform_id','platform')
59         platform_details = execute_admin_query(request, platform_query)
60     
61         for account_detail in account_details:
62             for platform_detail in platform_details:
63                 if platform_detail['platform_id'] == account_detail['platform_id']:
64                     if 'myslice' in platform_detail['platform']:
65                         account_config = json.loads(account_detail['config'])
66                         user_hrn = account_config.get('user_hrn','N/A')
67
68         pi_status = False
69         pis = authority_get_pis (request, authority_hrn)
70         for pi in pis:
71             pi_list = pi['pi_users']
72
73         if user_hrn in pi_list:
74             pi_status = True
75         return pi_status
76
77     except Exception,e:
78         print "Exception in actions.py in authority_check_pis %s" % e
79         return None
80
81
82 def authority_add_pis(request, authority_hrn,user_hrn):
83
84     # getting pis of the authority of the user
85     pis = authority_get_pis (request, authority_hrn)
86     for pi in pis:
87         pi_list = pi['pi_users']
88    
89     updated_pi_list = pi_list.append(user_hrn) 
90     query = Query.update('authority').filter_by('authority_hrn', '==', authority_hrn).set({'pi_users':pi_list})
91     results = execute_admin_query(request,query)
92     newpis = authority_get_pis (request, authority_hrn)
93     return newpis
94
95 def authority_remove_pis(request, authority_hrn,user_hrn):
96
97     # getting pis of the authority of the user
98     pis = authority_get_pis (request, authority_hrn)
99     for pi in pis:
100         pi_list = pi['pi_users']
101  
102     updated_pi_list = pi_list.remove(user_hrn) 
103     query = Query.update('authority').filter_by('authority_hrn', '==', authority_hrn).set({'pi_users':pi_list})
104     results = execute_admin_query(request,query)
105     newpis = authority_get_pis (request, authority_hrn)
106     return newpis
107
108
109 def authority_get_pi_emails(request, authority_hrn):
110     pi_users = authority_get_pis(request,authority_hrn)
111     print "pi_users = %s" % pi_users
112
113     if any(pi['pi_users'] == None or not pi['pi_users']  for pi in pi_users):
114         #theme.template_name = 'email_default_recipients.txt' 
115         #default_email = render_to_string(theme.template, request)
116         #default_email = default_email.replace('\n', '')
117         #return default_email
118         # the above doesn't work
119         return ['support@onelab.eu']
120     else:
121         pi_user_hrns = [ hrn for x in pi_users for hrn in x['pi_users'] ]
122
123         # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
124         query = Query.get('myslice:user').filter_by('user_hrn', 'included', pi_user_hrns).select('user_email')
125         results = execute_admin_query(request, query)
126         return [result['user_email'] for result in results]
127
128 #clear user credentials
129 def clear_user_creds(request, user_email):
130     try:
131         user_query  = Query().get('local:user').filter_by('email', '==', user_email).select('user_id','email','password','config')
132         user_details = execute_admin_query(request, user_query)
133     
134         # getting the user_id from the session
135         for user_detail in user_details:
136             user_id = user_detail['user_id']
137             user_email = user_detail['email']
138     
139         account_query  = Query().get('local:account').filter_by('user_id', '==', user_id).select('user_id','platform_id','auth_type','config')
140         account_details = execute_admin_query(request, account_query)
141     
142         platform_query  = Query().get('local:platform').select('platform_id','platform')
143         platform_details = execute_admin_query(request, platform_query)
144     
145         for account_detail in account_details:
146             for platform_detail in platform_details:
147                 if platform_detail['platform_id'] == account_detail['platform_id']:
148                     if 'myslice' in platform_detail['platform']:
149                         account_config = json.loads(account_detail['config'])
150                         #user_cred = account_config.get('delegated_user_credential','N/A')
151                         user_cred = account_config.get('user_credential','N/A')
152                         if 'N/A' not in user_cred:
153                             user_hrn = account_config.get('user_hrn','N/A')
154                             user_pub_key = json.dumps(account_config.get('user_public_key','N/A'))
155                             user_priv_key = json.dumps(account_config.get('user_private_key','N/A'))
156                             updated_config = '{"user_public_key":'+ user_pub_key + ', "user_private_key":'+ user_priv_key + ', "user_hrn":"'+ user_hrn + '"}'
157                             user_params = { 'config': updated_config}
158                             manifold_update_account(request, user_id,user_params)
159                             return user_email
160                         else:
161                             return None
162
163     except Exception,e:
164         print "Exception in actions.py in clear_user_creds %s" % e
165         return None
166
167 def is_pi(wsgi_request, user_hrn, authority_hrn):
168     # XXX could be done in a single query !
169
170     # seauthorities from user where user_hrn == "ple.upmc.jordan_auge"
171
172     # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
173     query = Query.get('myslice:user').filter_by('user_hrn', '==', user_hrn).select('pi_authorities')
174     results = execute_admin_query(wsgi_request, query)
175     if not results:
176         # XXX Warning ?
177         return False
178     result = results[0]
179     user_authority_hrns = result.get('pi_authorities', [])
180     return authority_hrn in user_authority_hrns
181     
182 # SFA get record
183
184 def sfa_get_user(request, user_hrn, pub):
185
186     # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
187     query_sfa_user = Query.get('myslice:user').filter_by('user_hrn', '==', user_hrn)
188     result_sfa_user = execute_admin_query(request, query_sfa_user)
189     return result_sfa_user                        
190
191 def sfa_update_user(request, user_hrn, user_params):
192     # user_params: keys [public_key] 
193     if 'email' in user_params:
194         user_params['user_email'] = user_params['email']
195
196     # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
197     query = Query.update('myslice:user').filter_by('user_hrn', '==', user_hrn).set(user_params).select('user_hrn')
198     results = execute_admin_query(request,query)
199     return results
200
201 def sfa_add_authority(request, authority_params):
202
203     # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
204     query = Query.create('authority').set(authority_params).select('authority_hrn')
205     results = execute_query(request, query)
206     print "sfa_add_auth results=",results
207     if not results:
208         raise Exception, "Could not create %s. Already exists ?" % authority_params['hrn']
209     return results
210
211 def sfa_add_user_to_slice(request, user_hrn, slice_params):
212 # UPDATE myslice:slice SET researcher=['ple.upmc.jordan_auge','ple.inria.thierry_parmentelat','ple.upmc.loic_baron','ple.upmc.ciro_scognamiglio','ple.upmc.mohammed-yasin_rahman','ple.upmc.azerty'] where slice_hrn=='ple.upmc.myslicedemo'
213
214     # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
215     query_current_users = Query.get('myslice:slice').select('user').filter_by('slice_hrn','==',slice_params['hrn'])
216     results_current_users = execute_query(request, query_current_users)
217     slice_params['researcher'] = slice_params['researcher'] | results_current_users
218
219     # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
220     query = Query.update('myslice:slice').filter_by('user_hrn', '==', user_hrn).set(slice_params).select('slice_hrn')
221     results = execute_query(request, query)
222 # Also possible but not supported yet
223 # UPDATE myslice:user SET slice=['ple.upmc.agent','ple.upmc.myslicedemo','ple.upmc.tophat'] where user_hrn=='ple.upmc.azerty'
224     if not results:
225         raise Exception, "Could not create %s. Already exists ?" % slice_params['hrn']
226     return results
227
228 # Propose hrn
229
230 def manifold_add_user(wsgi_request, request):
231     """Add a Manifold user corresponding to a user request.
232
233     Args:
234         wsgi_request: a WSGIRequest instance
235         request (dict): a dictionary containing the user request built from the
236             form.
237
238     Returns:
239         The user_id of the inserted user.
240
241     Raises:
242         ?
243     
244     """
245     USER_CONFIG = '{"firstname": "%(first_name)s", "lastname": "%(last_name)s", "authority": "%(authority_hrn)s"}'
246
247     user_params = {
248         'email'     : request['email'],
249         'password'  : request['password'],
250         'config'    : USER_CONFIG % request,
251         'status'    : 1,
252     }
253
254     query = Query.create('local:user').set(user_params).select('email')
255     results = execute_admin_query(request, query)
256     if not results:
257         raise Exception, "Failed creating manifold user: %s" % user_params['email']
258     result = results[0]
259     return result['email']
260
261 def manifold_update_user(request, email, user_params):
262     # user_params: password, config e.g., 
263     query = Query.update('local:user').filter_by('email', '==', email).set(user_params).select('email')
264     results = execute_admin_query(request,query)
265     # NOTE: results remains empty and goes to Exception. However, it updates the manifold DB.
266     # That's why I commented the exception part. -- Yasin 
267     #if not results:
268     #    raise Exception, "Failed updating manifold user: %s" % user_params['email']
269     #result, = results
270     return results
271
272 def manifold_add_account(request, account_params):
273     query = Query.create('local:account').set(account_params).select(['user', 'platform'])
274     results = execute_admin_query(request,query)
275     if not results:
276         raise Exception, "Failed creating manifold account on platform %s for user: %s" % (account_params['platform'], account_params['user'])
277     result, = results
278     return result['user_id']
279
280 def manifold_update_account(request,user_id,account_params):
281     # account_params: config
282     query = Query.update('local:account').filter_by('platform', '==', 'myslice').filter_by('user_id', '==', user_id).set(account_params).select('user_id')
283     results = execute_admin_query(request,query)
284     return results
285
286 #explicitly mention the platform_id
287 def manifold_delete_account(request, platform_id, user_id, account_params):
288     query = Query.delete('local:account').filter_by('platform_id', '==', platform_id).filter_by('user_id', '==', user_id).set(account_params).select('user_id')
289     results = execute_admin_query(request,query)
290     return results
291
292 def manifold_delete_user(request, user_id, user_params):
293     query = Query.delete('local:user').filter_by('user_id', '==', user_id).set(user_params).select('user_id')
294     results = execute_admin_query(request,query)
295     return results
296
297
298 #not tested
299 def manifold_add_platform(request, platform_params):
300     query = Query.create('local:platform').set(platform_params).select(['user', 'platform'])
301     results = execute_admin_query(request,query)
302     if not results:
303         raise Exception, "Failed creating manifold platform %s for user: %s" % (platform_params['platform'], platform_params['user'])
304     result, = results
305     return result['platform_id']
306
307
308 def make_request_user(user):
309     request = {}
310     request['type']          = 'user'
311     request['id']            = user.id
312     request['timestamp']     = user.created # XXX in DB ?
313     request['authority_hrn'] = user.authority_hrn
314     request['first_name']    = user.first_name
315     request['last_name']     = user.last_name
316     request['email']         = user.email
317     request['login']         = user.login
318     request['user_hrn']      = user.user_hrn
319     request['public_key']    = user.public_key
320     request['private_key']   = user.private_key
321     return request
322
323 def make_request_slice(slice):
324     request = {}
325     request['type'] = 'slice'
326     request['id'] = slice.id
327     request['user_hrn'] = slice.user_hrn
328     request['timestamp'] = slice.created
329     request['authority_hrn'] = slice.authority_hrn
330     request['slice_name'] = slice.slice_name
331     request['number_of_nodes'] = slice.number_of_nodes
332     request['type_of_nodes'] = slice.type_of_nodes
333     request['purpose'] = slice.purpose
334     return request
335
336 def make_request_authority(authority):
337     request = {}
338     request['type']                  = 'authority'
339     request['id']                    = authority.id
340     request['site_name']             = authority.site_name
341     request['site_latitude']         = authority.site_latitude
342     request['site_longitude']        = authority.site_longitude
343     request['site_url']              = authority.site_url
344     request['site_authority']        = authority.site_authority
345     request['site_abbreviated_name'] = authority.site_abbreviated_name
346     request['address_line1']         = authority.address_line1
347     request['address_line2']         = authority.address_line2
348     request['address_line3']         = authority.address_line3
349     request['address_city']          = authority.address_city
350     request['address_postalcode']    = authority.address_postalcode
351     request['address_state']         = authority.address_state
352     request['address_country']       = authority.address_country
353     request['authority_hrn']         = authority.authority_hrn
354     request['timestamp']             = authority.created
355     return request
356
357 def make_requests(pending_users, pending_slices, pending_authorities):
358     requests = []
359     for user in pending_users:
360         requests.append(make_request_user(user))
361     for slice in pending_slices:
362         requests.append(make_request_slice(slice))
363     for authority in pending_authorities:
364         requests.append(make_request_authority(authority))
365     return requests   
366
367 def get_request_by_id(ids):
368     sorted_ids = { 'user': [], 'slice': [], 'authority': [] }
369     for type__id in ids:
370         type, id = type__id.split('__')
371         sorted_ids[type].append(id)
372         
373     if not ids:
374         pending_users  = PendingUser.objects.all()
375         pending_slices = PendingSlice.objects.all()
376         pending_authorities = PendingAuthority.objects.all()
377     else:
378         pending_users  = PendingUser.objects.filter(id__in=sorted_ids['user']).all()
379         pending_slices = PendingSlice.objects.filter(id__in=sorted_ids['slice']).all()
380         pending_authorities = PendingAuthority.objects.filter(id__in=sorted_ids['authority']).all()
381
382     return make_requests(pending_users, pending_slices, pending_authorities)
383
384 def get_requests(authority_hrns=None):
385     print "get_request_by_authority auth_hrns = ", authority_hrns
386     if not authority_hrns:
387         ## get those pending users who have confirmed their emails
388         pending_users  = PendingUser.objects.filter(status__iexact = 'True')
389         pending_slices = PendingSlice.objects.all()
390         pending_authorities = PendingAuthority.objects.all()
391     else:
392         pending_users  = PendingUser.objects
393         pending_slices = PendingSlice.objects
394         pending_authorities = PendingAuthority.objects
395         from django.db.models import Q
396         list_user_Q = list()
397         list_slice_Q = list()
398         list_auth_Q = list()
399         for hrn in authority_hrns:
400             list_user_Q.append(Q(authority_hrn__startswith=hrn, status__iexact = 'True'))
401             list_slice_Q.append(Q(authority_hrn__startswith=hrn))
402             list_auth_Q.append(Q(site_authority__startswith=hrn))
403             print "startswith hrn = ",hrn
404         from operator import __or__ as OR
405         pending_users        = pending_users.filter(reduce(OR, list_user_Q))
406         pending_slices       = pending_slices.filter(reduce(OR, list_slice_Q))
407         pending_authorities  = pending_authorities.filter(reduce(OR, list_auth_Q))
408         #pending_authorities  = pending_authorities.all() #filter(reduce(OR, list_Q))
409
410     return make_requests(pending_users, pending_slices, pending_authorities)
411
412 # XXX Is it in sync with the form fields ?
413
414 def portal_validate_request(wsgi_request, request_ids):
415     status = {}
416
417     if not isinstance(request_ids, list):
418         request_ids = [request_ids]
419
420     requests = get_request_by_id(request_ids)
421     for request in requests:
422         # type, id, timestamp, details, allowed -- MISSING: authority_hrn
423         # CAREFUL about details
424         # user  : first name, last name, email, password, keypair
425         # slice : number of nodes, type of nodes, purpose
426         
427         request_status = {}
428
429         if request['type'] == 'user':
430
431             try:
432                 create_user(wsgi_request, request)
433                 request_status['SFA user'] = {'status': True }
434                 PendingUser.objects.get(id=request['id']).delete()
435             except Exception, e:
436                  request_status['SFA user'] = {'status': False, 'description': str(e)}
437                        
438 #            user_params = {'status':2}
439 #            manifold_update_user(request, request['email'], user_params)
440
441             # MANIFOLD user should be added beforehand, during registration
442             #try:
443             #    manifold_user_params = { key: request[key] for key in MANIFOLD_USER_KEYS }
444             #    # XXX # manifold_add_user(manifold_user_params)
445             #    request_status['MySlice user'] = {'status': True }
446             #except Exception, e:
447             #    request_status['MySlice user'] = {'status': False, 'description': str(e)}
448
449             # XXX
450             #manifold_account_params = { key: request[key] for key in MANIFOLD_ACCOUNT_KEYS }
451             #manifold_add_account(manifold_account_params)
452             #request_status['MySlice testbed accounts'] = {'status': False }
453
454         elif request['type'] == 'slice':
455             try:
456                 create_slice(wsgi_request, request)
457                 request_status['SFA slice'] = {'status': True }
458                 PendingSlice.objects.get(id=request['id']).delete()
459
460             except Exception, e:
461                 request_status['SFA slice'] = {'status': False, 'description': str(e)}
462
463         elif request['type'] == 'authority':
464             try:
465                 #hrn = "%s.%s" % (request['authority_hrn'], request['site_authority'])
466                 hrn = request['site_authority']
467                 # XXX tmp sfa dependency
468                 from sfa.util.xrn import Xrn 
469                 urn = Xrn(hrn, request['type']).get_urn()
470                 
471                 # Only hrn is required for Manifold Query 
472                 sfa_authority_params = {
473                     'authority_hrn'        : hrn,
474                     #'authority_urn'        : urn,
475                     #'type'       : request['type'],
476                     #'pi'        : None,
477                     #'enabled'    : True
478                 }
479                 print "ADD Authority"
480                 sfa_add_authority(wsgi_request, sfa_authority_params)
481                 request_status['SFA authority'] = {'status': True }
482                 PendingAuthority.objects.get(id=request['id']).delete()
483
484             except Exception, e:
485                 request_status['SFA authority'] = {'status': False, 'description': str(e)}
486
487         # XXX Remove from Pendings in database
488
489         status['%s__%s' % (request['type'], request['id'])] = request_status
490
491     return status
492
493 def validate_action(request, **kwargs):
494     ids = filter(None, kwargs['id'].split('/'))
495     status = portal_validate_request(request, ids)
496     json_answer = json.dumps(status)
497     return HttpResponse (json_answer, mimetype="application/json")
498
499
500 def reject_action(request, **kwargs):
501     ids = filter(None, kwargs['id'].split('/'))
502     status = portal_reject_request(request, ids)
503     json_answer = json.dumps(status)
504     return HttpResponse (json_answer, mimetype="application/json")
505
506
507 def portal_reject_request(wsgi_request, request_ids):
508     status = {}
509     # get the domain url    
510     current_site = Site.objects.get_current()
511     current_site = current_site.domain
512
513
514     if not isinstance(request_ids, list):
515         request_ids = [request_ids]
516
517     requests = get_request_by_id(request_ids)
518     for request in requests:
519         # type, id, timestamp, details, allowed -- MISSING: authority_hrn
520         # CAREFUL about details
521         # user  : first name, last name, email, password, keypair
522         # slice : number of nodes, type of nodes, purpose
523         
524         request_status = {}
525
526         if request['type'] == 'user':
527             try:
528                 request_status['SFA user'] = {'status': True }
529                 # getting user email based on id 
530                 ## RAW SQL queries on Django DB- https://docs.djangoproject.com/en/dev/topics/db/sql/
531                 for user in PendingUser.objects.raw('SELECT * FROM portal_pendinguser WHERE id = %s', [request['id']]):
532                     user_email= user.email
533                     first_name = user.first_name
534                     last_name = user.last_name
535
536                 ctx = {
537                     'first_name'    : first_name, 
538                     'last_name'     : last_name, 
539                     'portal_url'    : current_site,
540                     }
541                 try:
542                     theme.template_name = 'user_request_denied.txt'
543                     text_content = render_to_string(theme.template, ctx)
544                     theme.template_name = 'user_request_denied.html'
545                     html_content = render_to_string(theme.template, ctx)
546                     theme.template_name = 'email_default_sender.txt'
547                     sender =  render_to_string(theme.template, ctx)
548                     sender = sender.replace('\n', '')
549                                
550                     subject = 'User request denied.'
551
552                     msg = EmailMultiAlternatives(subject, text_content, sender, [user_email])
553                     msg.attach_alternative(html_content, "text/html")
554                     msg.send()
555                 except Exception, e:
556                     print "Failed to send email, please check the mail templates and the SMTP configuration of your server"   
557             
558                 # removing from Django auth_user
559                 UserModel = get_user_model()
560                 UserModel._default_manager.filter(email__iexact = user_email).delete()
561                 # removing from Django portal_pendinguser
562                 PendingUser.objects.get(id=request['id']).delete()
563                 # removing from manifold
564                 # removing manifold account
565                 user_query = Query().get('local:user') \
566                     .filter_by('email', '==', user_email)           \
567                     .select('user_id')
568                 user = execute_admin_query(wsgi_request, user_query)
569                 user_id = user[0]['user_id']
570         
571                 platform_query = Query().get('local:platform') \
572                     .filter_by('platform', '==', 'myslice')           \
573                     .select('platform_id')
574                 platform = execute_admin_query(wsgi_request, platform_query)
575                 platform_id = platform[0]['platform_id']
576                 account_params = {'user_id':user_id}
577                 manifold_delete_account(request, platform_id, user_id, account_params)           
578              
579                 # removing manifold user
580                 user_params = {'user_id':user_id}
581                 manifold_delete_user(request, user_id, user_params)
582             except Exception, e:
583                 request_status['SFA authority'] = {'status': False, 'description': str(e)}
584                       
585         elif request['type'] == 'slice':
586             request_status['SFA slice'] = {'status': True } 
587
588             # getting user email based on id 
589             ## RAW SQL queries on Django DB- https://docs.djangoproject.com/en/dev/topics/db/sql/
590             for user in PendingSlice.objects.raw('SELECT * FROM portal_pendingslice WHERE id = %s', [request['id']]):
591                 user_email= user.type_of_nodes # XXX type_of_nodes field contains the email [shd be renamed in DB]
592                 slice_name = user.slice_name
593                 purpose = user.purpose
594                 url = user.number_of_nodes
595
596             ctx = {
597                 'slice_name': slice_name,
598                 'purpose': purpose,
599                 'url': url,
600                 'portal_url': current_site,
601                 }
602             try:
603                 theme.template_name = 'slice_request_denied.txt'
604                 text_content = render_to_string(theme.template, ctx)
605                 theme.template_name = 'slice_request_denied.html'
606                 html_content = render_to_string(theme.template, ctx)
607                 theme.template_name = 'email_default_sender.txt'
608                 sender =  render_to_string(theme.template, ctx)
609                 sender = sender.replace('\n', '')
610                                
611                 subject = 'Slice request denied.'
612
613                 msg = EmailMultiAlternatives(subject, text_content, sender, [user_email])
614                 msg.attach_alternative(html_content, "text/html")
615                 msg.send()
616             except Exception, e:
617                 print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
618                       
619             PendingSlice.objects.get(id=request['id']).delete()
620
621         elif request['type'] == 'authority':
622             request_status['SFA authority'] = {'status': True }
623             
624             # getting user email based on id 
625             ## RAW SQL queries on Django DB- https://docs.djangoproject.com/en/dev/topics/db/sql/
626             for user in PendingAuthority.objects.raw('SELECT * FROM portal_pendingauthority WHERE id = %s', [request['id']]):
627                 user_email= user.address_line1 # XXX address_line1 field contains the email [shd be renamed in DB]
628                 site_name = user.site_name
629                 city = user.address_city
630                 country = user.address_country
631                 short_name = user.site_abbreviated_name
632                 url = user.site_url
633
634             ctx = { 
635                 'site_name': site_name,
636                 'short_name': short_name,
637                 'url': url,
638                 'city': city,
639                 'country': country,                          
640                 'portal_url'    : current_site,
641                 }
642                 
643             try:
644                 theme.template_name = 'authority_request_denied.txt'
645                 text_content = render_to_string(theme.template, ctx)
646                 theme.template_name = 'authority_request_denied.html'
647                 html_content = render_to_string(theme.template, ctx)
648                 theme.template_name = 'email_default_sender.txt'
649                 sender =  render_to_string(theme.template, ctx)
650                 sender = sender.replace('\n', '')
651                 subject = 'Authority request denied.'
652                 msg = EmailMultiAlternatives(subject, text_content, sender, [user_email])
653                 msg.attach_alternative(html_content, "text/html")
654                 msg.send()
655             except Exception, e:
656                 print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
657
658             PendingAuthority.objects.get(id=request['id']).delete()
659
660         status['%s__%s' % (request['type'], request['id'])] = request_status
661
662     return status
663
664 # Django and ajax
665 # http://djangosnippets.org/snippets/942/
666
667
668
669 #-------------------------------------------------------------------------------
670 # REQUESTS - Slices
671 #-------------------------------------------------------------------------------
672
673 def create_slice(wsgi_request, request):
674     """
675     Arguments:
676         wsgi_request (~ WSGIRequest) : 
677         request (dict) : the slice request in our own dict format
678
679     Raises:
680         Exception
681     """
682     hrn = "%s.%s" % (request['authority_hrn'], request['slice_name'])
683     # XXX tmp sfa dependency
684     from sfa.util.xrn import Xrn 
685     urn = Xrn(hrn, request['type']).get_urn()
686     
687     # Add User to Slice if we have the user_hrn in pendingslice table
688     user_hrn = request.get('user_hrn', None)
689     user_hrns = list([user_hrn]) if user_hrn else list()
690     
691     # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
692     user_query  = Query().get('myslice:user').select('user_hrn','user_email').filter_by('user_hrn','==',user_hrn)
693     user_details_sfa = execute_admin_query(wsgi_request, user_query)
694     if not user_details_sfa:
695         raise Exception, "User %s doesn't exist, validate user before validating slice" % user_hrn
696     for user in user_details_sfa:
697         user_email = user['user_email']
698
699     # XXX LOIC Quick fix because this is totally inconsistent
700     if not 'number_of_nodes' in request:
701         request['number_of_nodes']=""
702
703     # XXX We should create a slice with Manifold terminology
704     slice_params = {
705         'slice_hrn'        : hrn, 
706         'slice_urn'        : urn,
707         'slice_type'       : request['type'],
708         'url'              : request['number_of_nodes'],
709         'users'            : user_hrns,
710         'slice_enabled'    : True
711     }
712     # ignored in request: id, timestamp,  number_of_nodes, type_of_nodes, purpose
713
714     # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
715     query = Query.create('myslice:slice').set(slice_params).select('slice_hrn')
716     results = execute_query(wsgi_request, query)
717     if not results:
718         raise Exception, "Could not create %s. Already exists ?" % slice_params['hrn']
719     else:
720         clear_user_creds(wsgi_request,user_email)
721         # log user activity
722         activity.slice.validate(request, { "slice" : hrn })
723         try:
724             theme.template_name = 'slice_request_validated.txt'
725             text_content = render_to_string(theme.template, request)
726             theme.template_name = 'slice_request_validated.html'
727             html_content = render_to_string(theme.template, request)
728         
729             theme.template_name = 'email_default_sender.txt'
730             sender =  render_to_string(theme.template, request)
731             sender = sender.replace('\n', '')
732
733             subject = 'Slice request validated'
734
735             msg = EmailMultiAlternatives(subject, text_content, sender, [user_email])
736             msg.attach_alternative(html_content, "text/html")
737             msg.send()
738         except Exception, e:
739             print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
740        
741     return results
742
743 def create_pending_slice(wsgi_request, request, email):
744     """
745     """
746
747     # Insert an entry in the PendingSlice table
748     s = PendingSlice(
749         slice_name      = request['slice_name'],
750         user_hrn        = request['user_hrn'],
751         authority_hrn   = request['authority_hrn'],
752         number_of_nodes = request['url'], # field needs to be renamed
753         purpose         = request['purpose'],
754         type_of_nodes   = request['email'] # field needs to be renamed 
755     )
756     s.save()
757
758     try:
759         # Send an email: the recipients are the PI of the authority
760         recipients = authority_get_pi_emails(wsgi_request, request['authority_hrn'])
761
762         theme.template_name = 'slice_request_email.txt' 
763         text_content = render_to_string(theme.template, request)
764     
765         theme.template_name = 'slice_request_email.html' 
766         html_content = render_to_string(theme.template, request)
767     
768         theme.template_name = 'slice_request_email_subject.txt'
769         subject = render_to_string(theme.template, request)
770         subject = subject.replace('\n', '')
771     
772         sender = email
773         msg = EmailMultiAlternatives(subject, text_content, sender, recipients)
774         msg.attach_alternative(html_content, "text/html")
775         msg.send()
776     except Exception, e:
777         print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
778
779 #-------------------------------------------------------------------------------
780 # REQUESTS - Users
781 #-------------------------------------------------------------------------------
782
783 def manifold_add_reference_user_accounts(wsgi_request, request):
784     """When a new user is created, add reference accounts to the reference platform.
785     """
786     # XXX XXX XXX The rest of this function has to be checked XXX XXX XXX
787
788     # Retrieve user information
789     user_query  = Query().get('local:user')             \
790         .select('user_id', 'config', 'email', 'status') \
791         .filter_by('email', '==', request['email'])
792     user_details = execute_admin_query(wsgi_request, user_query)
793
794     # USER MAIN ACCOUNT != reference
795     #print 'USER MAIN ACCOUNT != reference'
796     list_accounts_query = Query().get('local:account')              \
797         .select('user_id', 'platform_id', 'auth_type', 'config')    \
798         .filter_by('user_id', '==', user_details[0]['user_id'])     \
799         .filter_by('auth_type', '!=', 'reference')
800     list_accounts = execute_admin_query(wsgi_request, list_accounts_query)
801
802     # XXX main_platform is being erased several times ???
803     for account in list_accounts:
804         main_platform_query = Query().get('local:platform')         \
805             .select('platform_id', 'platform')                      \
806             .filter_by('platform_id', '==', account['platform_id'])
807         main_platform = execute_admin_query(wsgi_request, main_platform_query)
808
809     # Add reference accounts on SFA enabled platforms
810     platforms_query = Query().get('local:platform') \
811         .filter_by('disabled', '==', '0')           \
812         .filter_by('gateway_type', '==', 'sfa')     \
813         .select('platform_id', 'gateway_type')
814     platforms = execute_admin_query(wsgi_request, platforms_query)
815     for platform in platforms:
816         #print "add reference to platform ",platform
817         manifold_account_params = {
818             'user_id'       : user_details[0]['user_id'],
819             'platform_id'   : platform['platform_id'],
820             'auth_type'     : 'reference',
821             'config'        : '{"reference_platform": "' + main_platform[0]['platform'] + '"}',
822         }
823         manifold_add_account(wsgi_request, manifold_account_params)
824
825 def sfa_create_user(wsgi_request, request, namespace = None, as_admin = False):
826     """
827     Arguments:
828         wsgi_request (~ WSGIRequest) : 
829         request (dict) : the user request in our own dict format
830
831     Raises:
832         Exception
833     """
834     from sfa.util.xrn import Xrn 
835
836     auth_pi = request.get('pi', None)
837     auth_pi = list([auth_pi]) if auth_pi else list()
838
839     # We create a user request with Manifold terminology
840     sfa_user_params = {
841         'user_hrn'          : request['user_hrn'],
842         'user_email'        : request['email'],
843         'user_urn'          : Xrn(request['user_hrn'], request['type']).get_urn(),
844         'user_type'         : request['type'],
845         'keys'              : request['public_key'],
846         'user_first_name'   : request['first_name'],
847         'user_last_name'    : request['last_name'],
848         'pi_authorities'    : auth_pi,
849         'user_enabled'      : True
850     }
851
852     if namespace is not None:
853         query = Query.create('%s:user' % namespace).set(sfa_user_params).select('user_hrn')
854     else:
855         # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
856         query = Query.create('myslice:user').set(sfa_user_params).select('user_hrn')
857
858     if as_admin:
859         results = execute_admin_query(wsgi_request, query)
860     else:
861         results = execute_query(wsgi_request, query)
862
863     if not results:
864         raise Exception, "Could not create %s. Already exists ?" % sfa_user_params['user_hrn']
865     else:
866         try:
867             theme.template_name = 'user_request_validated.txt'
868             text_content = render_to_string(theme.template, request)
869             theme.template_name = 'user_request_validated.html'
870             html_content = render_to_string(theme.template, request)
871         
872             theme.template_name = 'email_default_sender.txt'
873             sender =  render_to_string(theme.template, request)
874             sender = sender.replace('\n', '')
875
876
877             subject = 'User validated'
878
879             msg = EmailMultiAlternatives(subject, text_content, sender, [request['email']])
880             msg.attach_alternative(html_content, "text/html")
881             msg.send()
882         except Exception, e:
883             print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
884
885     return results
886
887 def iotlab_create_user (wsgi_request, request, namespace = None, as_admin=False):
888    
889     import requests
890     import time
891     from requests.auth import HTTPBasicAuth
892     
893     URL_REST = ConfigEngine.default_iotlab_url
894     LOGIN_ADMIN = ConfigEngine.default_iotlab_admin_user
895     PASSWORD_ADMIN = ConfigEngine.default_iotlab_admin_password
896
897     auth = HTTPBasicAuth(LOGIN_ADMIN,PASSWORD_ADMIN)
898     headers = {'content-type': 'application/json'}
899
900     for user in PendingUser.objects.raw('SELECT * FROM portal_pendinguser WHERE email = %s', [request['email']]):
901         password= user.password
902
903
904     iotlab_user_params = {
905         "type"          : "SA",
906         #"login"         : request['email'], #auto generated by iotlab
907         "password"      : password,
908         "firstName"     : request['first_name'],
909         "lastName"      : request['last_name'],
910         "email"         : request['email'],
911         "structure"     : request['authority_hrn'],
912         "city"          : "N/A",
913         "country"       : "N/A",
914         "sshPublicKey"  : request['public_key'],
915         "motivations"   : "SFA federation",
916     }    
917    
918     iotlab_user_params1 = json.dumps(iotlab_user_params)
919     r=requests.post(url=URL_REST, data=iotlab_user_params1, headers=headers, auth=auth)
920     print 'Create iotlab user : ', r.status_code, r.text
921     return r.text
922
923 def create_user(wsgi_request, request, namespace = None, as_admin = False):
924     # XXX This has to be stored centrally
925     USER_STATUS_ENABLED = 2
926
927     # NOTE : if we were to create a user directly (just like we create slices,
928     # we would have to perform the steps in create_pending_user too
929
930     # Add the user to the SFA registry
931     sfa_create_user(wsgi_request, request, namespace, as_admin)
932
933     # Update Manifold user status
934     manifold_update_user(wsgi_request, request['email'], {'status': USER_STATUS_ENABLED})
935
936     # Add reference accounts for platforms
937     manifold_add_reference_user_accounts(wsgi_request, request)
938
939     # Add the user to iotlab portal if theme is set to onelab
940     if theme.theme == 'onelab':
941         iotlab_create_user (wsgi_request, request)
942
943 def create_pending_user(wsgi_request, request, user_detail):
944     """
945     """
946
947     # Insert an entry in the PendingUser table
948     b = PendingUser(
949         first_name    = request['first_name'],
950         last_name     = request['last_name'],
951         authority_hrn = request['authority_hrn'],
952         email         = request['email'],
953         password      = request['password'],
954         public_key    = request['public_key'],
955         private_key   = request['private_key'],
956         user_hrn      = request['user_hrn'],
957         pi            = request['pi'],
958         email_hash    = request['email_hash'],
959         status        = 'False',
960     )
961     b.save()
962     # sends email to user to activate the email
963     theme.template_name = 'activate_user.html'
964     html_content = render_to_string(theme.template, request)
965     theme.template_name = 'activate_user.txt'
966     text_content = render_to_string(theme.template, request)
967     theme.template_name = 'activate_user_email_subject.txt'
968     subject = render_to_string(theme.template, request)
969     subject = subject.replace('\n', '')
970     theme.template_name = 'email_default_sender.txt'
971     sender =  render_to_string(theme.template, request)
972     sender = sender.replace('\n', '')
973     recipient = [request['email']]
974     #recipient = recipient.append(request['email'])
975
976     msg = EmailMultiAlternatives(subject, text_content, sender, recipient)
977     msg.attach_alternative(html_content, "text/html")
978     msg.send()
979    
980     # saves the user to django auth_user table [needed for password reset]
981     user = User.objects.create_user(request['email'], request['email'], request['password'])
982
983     # Creating a manifold user
984     user_id = manifold_add_user(wsgi_request, request)
985
986     # Creating a Manifold account on the MySlice platform
987     # Note the JSON representation of public and private keys already includes quotes
988     account_config = {
989         'user_hrn'          : request['user_hrn'],
990         'user_public_key'   : request['public_key'],
991     }
992     if request['private_key']:
993         account_config['user_private_key'] = request['private_key']
994
995     user_id = user_detail['user_id'] + 1 # the user_id for the newly created user in local:user
996
997     # XXX TODO: Require a myslice platform
998     # ALERT: this will disapear with ROUTERV2 of Manifold
999     # We have to consider the case where several registries can be used
1000     # Removed hardcoded platform = 5
1001     # This platform == 'myslice' is a TMP FIX !!
1002     try:
1003         reg_platform_query = Query().get('local:platform') \
1004             .filter_by('platform', '==', 'myslice')           \
1005             .select('platform_id')
1006         reg_platform = execute_admin_query(wsgi_request, reg_platform_query)
1007
1008         reg_platform_id = reg_platform[0]['platform_id']
1009         account_params = {
1010             'platform_id'   : reg_platform_id, # XXX ALERT !!
1011             'user_id'       : user_id, 
1012             'auth_type'     : request['auth_type'], 
1013             'config'        : json.dumps(account_config),
1014         }
1015         manifold_add_account(wsgi_request, account_params)
1016     except Exception, e:
1017         print "Failed creating manifold account on platform %s for user: %s" % ('myslice', request['email'])
1018
1019     try:
1020         # Send an email: the recipients are the PI of the authority
1021         # If No PI is defined for this Authority, send to a default email (different for each theme)
1022         recipients = authority_get_pi_emails(wsgi_request, request['authority_hrn'])
1023         
1024         theme.template_name = 'user_request_email.html'
1025         html_content = render_to_string(theme.template, request)
1026  
1027         theme.template_name = 'user_request_email.txt'
1028         text_content = render_to_string(theme.template, request)
1029     
1030         theme.template_name = 'user_request_email_subject.txt'
1031         subject = render_to_string(theme.template, request)
1032         subject = subject.replace('\n', '')
1033     
1034         theme.template_name = 'email_default_sender.txt'
1035         sender =  render_to_string(theme.template, request)
1036         sender = sender.replace('\n', '')
1037     
1038         msg = EmailMultiAlternatives(subject, text_content, sender, recipients)
1039         msg.attach_alternative(html_content, "text/html")
1040         msg.send()
1041     except Exception, e:
1042         print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
1043         import traceback
1044         traceback.print_exc()