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