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
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
13 from myslice.theme import ThemeView
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
25 # Get the list of authorities
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
34 # raise Exception, "Authority not found: %s" % authority_hrn
36 #return result['pi_users']
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
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', '')
48 # the above doesn't work
49 return ['support@onelab.eu']
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]
56 #clear user credentials
57 def clear_user_creds(request, user_email):
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)
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']
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)
70 platform_query = Query().get('local:platform').select('platform_id','platform')
71 platform_details = execute_admin_query(request, platform_query)
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)
92 print "Exception in actions.py in clear_user_creds %s" % e
95 def is_pi(wsgi_request, user_hrn, authority_hrn):
96 # XXX could be done in a single query !
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)
105 user_authority_hrns = result.get('pi_authorities', [])
106 return authority_hrn in user_authority_hrns
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
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)
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
128 raise Exception, "Could not create %s. Already exists ?" % authority_params['hrn']
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'
141 raise Exception, "Could not create %s. Already exists ?" % slice_params['hrn']
146 def manifold_add_user(wsgi_request, request):
147 """Add a Manifold user corresponding to a user request.
150 wsgi_request: a WSGIRequest instance
151 request (dict): a dictionary containing the user request built from the
155 The user_id of the inserted user.
161 USER_CONFIG = '{"firstname": "%(first_name)s", "lastname": "%(last_name)s", "authority": "%(authority_hrn)s"}'
164 'email' : request['email'],
165 'password' : request['password'],
166 'config' : USER_CONFIG % request,
170 query = Query.create('local:user').set(user_params).select('email')
171 results = execute_admin_query(request, query)
173 raise Exception, "Failed creating manifold user: %s" % user_params['email']
175 return result['email']
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
184 # raise Exception, "Failed updating manifold user: %s" % user_params['email']
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)
192 raise Exception, "Failed creating manifold account on platform %s for user: %s" % (account_params['platform'], account_params['user'])
194 return result['user_id']
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)
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)
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)
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)
219 raise Exception, "Failed creating manifold platform %s for user: %s" % (platform_params['platform'], platform_params['user'])
221 return result['platform_id']
224 def make_request_user(user):
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
239 def make_request_slice(slice):
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
252 def make_request_authority(authority):
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
273 def make_requests(pending_users, pending_slices, pending_authorities):
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))
283 def get_request_by_id(ids):
284 sorted_ids = { 'user': [], 'slice': [], 'authority': [] }
286 type, id = type__id.split('__')
287 sorted_ids[type].append(id)
290 pending_users = PendingUser.objects.all()
291 pending_slices = PendingSlice.objects.all()
292 pending_authorities = PendingAuthority.objects.all()
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()
298 return make_requests(pending_users, pending_slices, pending_authorities)
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()
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()
312 return make_requests(pending_users, pending_slices, pending_authorities)
314 # XXX Is it in sync with the form fields ?
316 def portal_validate_request(wsgi_request, request_ids):
319 if not isinstance(request_ids, list):
320 request_ids = [request_ids]
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
331 if request['type'] == 'user':
334 create_user(wsgi_request, request)
335 request_status['SFA user'] = {'status': True }
336 PendingUser.objects.get(id=request['id']).delete()
338 request_status['SFA user'] = {'status': False, 'description': str(e)}
340 # user_params = {'status':2}
341 # manifold_update_user(request, request['email'], user_params)
343 # MANIFOLD user should be added beforehand, during registration
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)}
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 }
356 elif request['type'] == 'slice':
358 create_slice(wsgi_request, request)
359 request_status['SFA slice'] = {'status': True }
360 PendingSlice.objects.get(id=request['id']).delete()
363 request_status['SFA slice'] = {'status': False, 'description': str(e)}
365 elif request['type'] == 'authority':
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()
373 # Only hrn is required for Manifold Query
374 sfa_authority_params = {
375 'authority_hrn' : hrn,
376 #'authority_urn' : urn,
377 #'type' : request['type'],
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()
387 request_status['SFA authority'] = {'status': False, 'description': str(e)}
389 # XXX Remove from Pendings in database
391 status['%s__%s' % (request['type'], request['id'])] = request_status
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")
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")
409 def portal_reject_request(wsgi_request, request_ids):
412 current_site = Site.objects.get_current()
413 current_site = current_site.domain
416 if not isinstance(request_ids, list):
417 request_ids = [request_ids]
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
428 if request['type'] == 'user':
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
439 'first_name' : first_name,
440 'last_name' : last_name,
441 'portal_url' : current_site,
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', '')
452 subject = 'User request denied.'
454 msg = EmailMultiAlternatives(subject, text_content, sender, [user_email])
455 msg.attach_alternative(html_content, "text/html")
458 print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
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) \
470 user = execute_admin_query(wsgi_request, user_query)
471 user_id = user[0]['user_id']
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)
481 # removing manifold user
482 user_params = {'user_id':user_id}
483 manifold_delete_user(request, user_id, user_params)
485 request_status['SFA authority'] = {'status': False, 'description': str(e)}
487 elif request['type'] == 'slice':
488 request_status['SFA slice'] = {'status': True }
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
499 'slice_name': slice_name,
502 'portal_url': current_site,
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', '')
513 subject = 'Slice request denied.'
515 msg = EmailMultiAlternatives(subject, text_content, sender, [user_email])
516 msg.attach_alternative(html_content, "text/html")
519 print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
521 PendingSlice.objects.get(id=request['id']).delete()
523 elif request['type'] == 'authority':
524 request_status['SFA authority'] = {'status': True }
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
537 'site_name': site_name,
538 'short_name': short_name,
542 'portal_url' : current_site,
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")
558 print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
560 PendingAuthority.objects.get(id=request['id']).delete()
562 status['%s__%s' % (request['type'], request['id'])] = request_status
567 # http://djangosnippets.org/snippets/942/
571 #-------------------------------------------------------------------------------
573 #-------------------------------------------------------------------------------
575 def create_slice(wsgi_request, request):
578 wsgi_request (~ WSGIRequest) :
579 request (dict) : the slice request in our own dict format
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()
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()
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']
600 # XXX LOIC Quick fix because this is totally inconsistent
601 if not 'number_of_nodes' in request:
602 request['number_of_nodes']=""
604 # XXX We should create a slice with Manifold terminology
608 'slice_type' : request['type'],
609 'url' : request['number_of_nodes'],
611 'slice_enabled' : True
613 # ignored in request: id, timestamp, number_of_nodes, type_of_nodes, purpose
615 query = Query.create('myslice:slice').set(slice_params).select('slice_hrn')
616 results = execute_query(wsgi_request, query)
618 raise Exception, "Could not create %s. Already exists ?" % slice_params['hrn']
620 clear_user_creds(wsgi_request,user_email)
622 activity.slice.validate(request, { "slice" : hrn })
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)
629 theme.template_name = 'email_default_sender.txt'
630 sender = render_to_string(theme.template, request)
631 sender = sender.replace('\n', '')
633 subject = 'Slice request validated'
635 msg = EmailMultiAlternatives(subject, text_content, sender, [user_email])
636 msg.attach_alternative(html_content, "text/html")
639 print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
643 def create_pending_slice(wsgi_request, request, email):
647 # Insert an entry in the PendingSlice table
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
659 # Send an email: the recipients are the PI of the authority
660 recipients = authority_get_pi_emails(wsgi_request, request['authority_hrn'])
662 theme.template_name = 'slice_request_email.txt'
663 text_content = render_to_string(theme.template, request)
665 theme.template_name = 'slice_request_email.html'
666 html_content = render_to_string(theme.template, request)
668 theme.template_name = 'slice_request_email_subject.txt'
669 subject = render_to_string(theme.template, request)
670 subject = subject.replace('\n', '')
673 msg = EmailMultiAlternatives(subject, text_content, sender, recipients)
674 msg.attach_alternative(html_content, "text/html")
677 print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
679 #-------------------------------------------------------------------------------
681 #-------------------------------------------------------------------------------
683 def manifold_add_reference_user_accounts(wsgi_request, request):
684 """When a new user is created, add reference accounts to the reference platform.
686 # XXX XXX XXX The rest of this function has to be checked XXX XXX XXX
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)
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)
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)
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'] + '"}',
723 manifold_add_account(wsgi_request, manifold_account_params)
725 def sfa_create_user(wsgi_request, request, namespace = None, as_admin = False):
728 wsgi_request (~ WSGIRequest) :
729 request (dict) : the user request in our own dict format
734 from sfa.util.xrn import Xrn
736 auth_pi = request.get('pi', None)
737 auth_pi = list([auth_pi]) if auth_pi else list()
739 # We create a user request with Manifold terminology
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
752 if namespace is not None:
753 query = Query.create('%s:user' % namespace).set(sfa_user_params).select('user_hrn')
755 query = Query.create('user').set(sfa_user_params).select('user_hrn')
758 results = execute_admin_query(wsgi_request, query)
760 results = execute_query(wsgi_request, query)
763 raise Exception, "Could not create %s. Already exists ?" % sfa_user_params['user_hrn']
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)
771 theme.template_name = 'email_default_sender.txt'
772 sender = render_to_string(theme.template, request)
773 sender = sender.replace('\n', '')
776 subject = 'User validated'
778 msg = EmailMultiAlternatives(subject, text_content, sender, [request['email']])
779 msg.attach_alternative(html_content, "text/html")
782 print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
786 def iotlab_create_user (wsgi_request, request, namespace = None, as_admin=False):
790 from requests.auth import HTTPBasicAuth
792 URL_REST = 'https://devgrenoble.senslab.info/rest/admin/users'
794 PASSWORD_ADMIN = "k,mfg1+Q"
796 auth = HTTPBasicAuth(LOGIN_ADMIN,PASSWORD_ADMIN)
797 headers = {'content-type': 'application/json'}
799 for user in PendingUser.objects.raw('SELECT * FROM portal_pendinguser WHERE email = %s', [request['email']]):
800 password= user.password
803 iotlab_user_params = {
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'],
813 "sshPublicKey" : request['public_key'],
814 "motivations" : "SFA federation",
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
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
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
829 # Add the user to the SFA registry
830 sfa_create_user(wsgi_request, request, namespace, as_admin)
832 # Update Manifold user status
833 manifold_update_user(wsgi_request, request['email'], {'status': USER_STATUS_ENABLED})
835 # Add reference accounts for platforms
836 manifold_add_reference_user_accounts(wsgi_request, request)
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)
842 def create_pending_user(wsgi_request, request, user_detail):
846 # Insert an entry in the PendingUser table
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'],
857 email_hash = request['email_hash'],
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'])
875 msg = EmailMultiAlternatives(subject, text_content, sender, recipient)
876 msg.attach_alternative(html_content, "text/html")
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'])
882 # Creating a manifold user
883 user_id = manifold_add_user(wsgi_request, request)
885 # Creating a Manifold account on the MySlice platform
886 # Note the JSON representation of public and private keys already includes quotes
888 'user_hrn' : request['user_hrn'],
889 'user_public_key' : request['public_key'],
891 if request['private_key']:
892 account_config['user_private_key'] = request['private_key']
894 user_id = user_detail['user_id'] + 1 # the user_id for the newly created user in local:user
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 !!
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)
907 reg_platform_id = reg_platform[0]['platform_id']
909 'platform_id' : reg_platform_id, # XXX ALERT !!
911 'auth_type' : request['auth_type'],
912 'config' : json.dumps(account_config),
914 manifold_add_account(wsgi_request, account_params)
916 print "Failed creating manifold account on platform %s for user: %s" % ('myslice', request['email'])
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'])
923 theme.template_name = 'user_request_email.html'
924 html_content = render_to_string(theme.template, request)
926 theme.template_name = 'user_request_email.txt'
927 text_content = render_to_string(theme.template, request)
929 theme.template_name = 'user_request_email_subject.txt'
930 subject = render_to_string(theme.template, request)
931 subject = subject.replace('\n', '')
933 theme.template_name = 'email_default_sender.txt'
934 sender = render_to_string(theme.template, request)
935 sender = sender.replace('\n', '')
937 msg = EmailMultiAlternatives(subject, text_content, sender, recipients)
938 msg.attach_alternative(html_content, "text/html")
941 print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
943 traceback.print_exc()