1 from unfold.loginrequired import LoginRequiredAutoLogoutView
3 from sfa.trust.credential import Credential
4 from sfa.trust.certificate import Keypair
6 from manifold.core.query import Query
7 from manifoldapi.manifoldapi import execute_query
8 from portal.actions import manifold_update_user, manifold_update_account, manifold_add_account, manifold_delete_account, sfa_update_user, sfa_get_user, clear_user_creds
10 from unfold.page import Page
11 from ui.topmenu import topmenu_items_live, the_user
13 from django.http import HttpResponse, HttpResponseRedirect
14 from django.contrib import messages
15 from django.contrib.auth.decorators import login_required
17 from myslice.theme import ThemeView
20 import json, os, re, itertools
21 from OpenSSL import crypto
22 from Crypto.PublicKey import RSA
25 class AccountView(LoginRequiredAutoLogoutView, ThemeView):
26 template_name = "account-view.html"
27 def dispatch(self, *args, **kwargs):
28 return super(AccountView, self).dispatch(*args, **kwargs)
31 def get_context_data(self, **kwargs):
32 self.template_name = self.template
33 page = Page(self.request)
34 metadata = page.get_metadata()
35 page.expose_js_metadata()
37 page.add_js_files ( [ "js/jquery.validate.js", "js/my_account.register.js", "js/my_account.edit_profile.js","js/jquery-ui.js" ] )
38 page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css" ] )
40 user_query = Query().get('local:user').select('config','email','status')
41 user_details = execute_query(self.request, user_query)
43 # not always found in user_details...
45 for user_detail in user_details:
46 # different significations of user_status
47 if user_detail['status'] == 0:
48 user_status = 'Disabled'
49 elif user_detail['status'] == 1:
50 user_status = 'Validation Pending'
51 elif user_detail['status'] == 2:
52 user_status = 'Enabled'
55 #email = user_detail['email']
56 if user_detail['config']:
57 config = json.loads(user_detail['config'])
59 platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
60 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
61 platform_details = execute_query(self.request, platform_query)
62 account_details = execute_query(self.request, account_query)
64 # initial assignment needed for users having account.config = {}
70 account_reference = ''
75 principal_acc_list = ''
77 platform_name_list = []
78 platform_name_secondary_list = []
79 platform_access_list = []
80 platform_no_access_list = []
81 total_platform_list = []
82 account_type_list = []
83 account_type_secondary_list = []
84 account_reference_list = []
85 delegation_type_list = []
86 user_cred_exp_list = []
89 slice_cred_exp_list = []
90 auth_cred_exp_list = []
94 for platform_detail in platform_details:
95 if 'sfa' in platform_detail['gateway_type']:
96 total_platform = platform_detail['platform']
97 total_platform_list.append(total_platform)
99 for account_detail in account_details:
100 if platform_detail['platform_id'] == account_detail['platform_id']:
101 platform_name = platform_detail['platform']
102 if 'config' in account_detail and account_detail['config'] is not '':
103 account_config = json.loads(account_detail['config'])
104 account_usr_hrn = account_config.get('user_hrn','N/A')
105 account_pub_key = account_config.get('user_public_key','N/A')
106 account_reference = account_config.get ('reference_platform','N/A')
107 # credentials of myslice platform
108 if 'myslice' in platform_detail['platform']:
109 acc_user_cred = account_config.get('delegated_user_credential','N/A')
110 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
111 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
113 if 'N/A' not in acc_user_cred:
114 exp_date = re.search('<expires>(.*)</expires>', acc_user_cred)
116 user_exp_date = exp_date.group(1)
117 user_cred_exp_list.append(user_exp_date)
119 my_users = [{'cred_exp': t[0]}
120 for t in zip(user_cred_exp_list)]
123 if 'N/A' not in acc_slice_cred:
124 for key, value in acc_slice_cred.iteritems():
125 slice_list.append(key)
127 exp_date = re.search('<expires>(.*)</expires>', value)
129 exp_date = exp_date.group(1)
130 slice_cred_exp_list.append(exp_date)
132 my_slices = [{'slice_name': t[0], 'cred_exp': t[1]}
133 for t in zip(slice_list, slice_cred_exp_list)]
135 if 'N/A' not in acc_auth_cred:
136 for key, value in acc_auth_cred.iteritems():
137 auth_list.append(key)
139 exp_date = re.search('<expires>(.*)</expires>', value)
141 exp_date = exp_date.group(1)
142 auth_cred_exp_list.append(exp_date)
144 my_auths = [{'auth_name': t[0], 'cred_exp': t[1]}
145 for t in zip(auth_list, auth_cred_exp_list)]
148 # for reference accounts
149 if 'reference' in account_detail['auth_type']:
150 account_type = 'Reference'
152 platform_name_secondary_list.append(platform_name)
153 account_type_secondary_list.append(account_type)
154 account_reference_list.append(account_reference)
155 ref_acc_list = [{'platform_name': t[0], 'account_type': t[1], 'account_reference': t[2]}
156 for t in zip(platform_name_secondary_list, account_type_secondary_list, account_reference_list)]
158 elif 'managed' in account_detail['auth_type']:
159 account_type = 'Principal'
160 delegation = 'Automatic'
162 account_type = 'Principal'
163 delegation = 'Manual'
164 # for principal (auth_type=user/managed) accounts
165 if 'reference' not in account_detail['auth_type']:
166 platform_name_list.append(platform_name)
167 account_type_list.append(account_type)
168 delegation_type_list.append(delegation)
169 usr_hrn_list.append(account_usr_hrn)
170 pub_key_list.append(account_pub_key)
171 user_status_list.append(user_status)
172 # combining 5 lists into 1 [to render in the template]
173 principal_acc_list = [{'platform_name': t[0], 'account_type': t[1], 'delegation_type': t[2], 'usr_hrn':t[3], 'usr_pubkey':t[4], 'user_status':t[5],}
174 for t in zip(platform_name_list, account_type_list, delegation_type_list, usr_hrn_list, pub_key_list, user_status_list)]
175 # to hide private key row if it doesn't exist
176 if 'myslice' in platform_detail['platform']:
177 account_config = json.loads(account_detail['config'])
178 account_priv_key = account_config.get('user_private_key','N/A')
179 if 'sfa' in platform_detail['gateway_type']:
180 platform_access = platform_detail['platform']
181 platform_access_list.append(platform_access)
183 # Removing the platform which already has access
184 for platform in platform_access_list:
185 total_platform_list.remove(platform)
186 # we could use zip. this one is used if columns have unequal rows
187 platform_list = [{'platform_no_access': t[0]}
188 for t in itertools.izip_longest(total_platform_list)]
191 ## check user is pi or not
192 # platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
193 # account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
194 # platform_details = execute_query(self.request, platform_query)
195 # account_details = execute_query(self.request, account_query)
196 # for platform_detail in platform_details:
197 # for account_detail in account_details:
198 # if platform_detail['platform_id'] == account_detail['platform_id']:
199 # if 'config' in account_detail and account_detail['config'] is not '':
200 # account_config = json.loads(account_detail['config'])
201 # if 'myslice' in platform_detail['platform']:
202 # acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
204 if acc_auth_cred == {} or acc_auth_cred == 'N/A':
209 # check if the user has creds or not
210 if acc_user_cred == {} or acc_user_cred == 'N/A':
211 user_cred = 'no_creds'
213 user_cred = 'has_creds'
215 context = super(AccountView, self).get_context_data(**kwargs)
216 context['principal_acc'] = principal_acc_list
217 context['ref_acc'] = ref_acc_list
218 context['platform_list'] = platform_list
219 context['my_users'] = my_users
221 context['user_cred'] = user_cred
222 context['my_slices'] = my_slices
223 context['my_auths'] = my_auths
224 context['user_status'] = user_status
225 context['person'] = self.request.user
226 context['firstname'] = config.get('firstname',"?")
227 context['lastname'] = config.get('lastname',"?")
228 context['fullname'] = context['firstname'] +' '+ context['lastname']
229 context['authority'] = config.get('authority',"Unknown Authority")
230 context['user_private_key'] = account_priv_key
232 # XXX This is repeated in all pages
233 # more general variables expected in the template
234 context['title'] = 'Platforms connected to MySlice'
235 # the menu items on the top
236 context['topmenu_items'] = topmenu_items_live('My Account', page)
237 # so we can sho who is logged
238 context['username'] = the_user(self.request)
239 context['theme'] = self.theme
240 context['section'] = "User account"
241 # context ['firstname'] = config['firstname']
242 prelude_env = page.prelude_env()
243 context.update(prelude_env)
248 #my_acc form value processing
249 def account_process(request):
250 user_query = Query().get('local:user').select('user_id','email','password','config')
251 user_details = execute_query(request, user_query)
253 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
254 account_details = execute_query(request, account_query)
256 platform_query = Query().get('local:platform').select('platform_id','platform')
257 platform_details = execute_query(request, platform_query)
259 # getting the user_id from the session
260 for user_detail in user_details:
261 user_id = user_detail['user_id']
262 user_email = user_detail['email']
264 for account_detail in account_details:
265 for platform_detail in platform_details:
266 # Add reference account to the platforms
267 if 'add_'+platform_detail['platform'] in request.POST:
268 platform_id = platform_detail['platform_id']
269 user_params = {'platform_id': platform_id, 'user_id': user_id, 'auth_type': "reference", 'config': '{"reference_platform": "myslice"}'}
270 manifold_add_account(request,user_params)
271 messages.info(request, 'Reference Account is added to the selected platform successfully!')
272 return HttpResponseRedirect("/portal/account/")
274 # Delete reference account from the platforms
275 if 'delete_'+platform_detail['platform'] in request.POST:
276 platform_id = platform_detail['platform_id']
277 user_params = {'user_id':user_id}
278 manifold_delete_account(request,platform_id, user_id, user_params)
279 messages.info(request, 'Reference Account is removed from the selected platform')
280 return HttpResponseRedirect("/portal/account/")
282 if platform_detail['platform_id'] == account_detail['platform_id']:
283 if 'myslice' in platform_detail['platform']:
284 account_config = json.loads(account_detail['config'])
285 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
286 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
291 # adding the slices and corresponding credentials to list
292 if 'N/A' not in acc_slice_cred:
295 for key, value in acc_slice_cred.iteritems():
296 slice_list.append(key)
297 slice_cred.append(value)
298 # special case: download each slice credentials separately
299 for i in range(0, len(slice_list)):
300 if 'dl_'+slice_list[i] in request.POST:
301 slice_detail = "Slice name: " + slice_list[i] +"\nSlice Credentials: \n"+ slice_cred[i]
302 response = HttpResponse(slice_detail, content_type='text/plain')
303 response['Content-Disposition'] = 'attachment; filename="slice_credential.txt"'
306 # adding the authority and corresponding credentials to list
307 if 'N/A' not in acc_auth_cred:
310 for key, value in acc_auth_cred.iteritems():
311 auth_list.append(key)
312 auth_cred.append(value)
313 # special case: download each slice credentials separately
314 for i in range(0, len(auth_list)):
315 if 'dl_'+auth_list[i] in request.POST:
316 auth_detail = "Authority: " + auth_list[i] +"\nAuthority Credentials: \n"+ auth_cred[i]
317 response = HttpResponse(auth_detail, content_type='text/plain')
318 response['Content-Disposition'] = 'attachment; filename="auth_credential.txt"'
323 if 'submit_name' in request.POST:
324 edited_first_name = request.POST['fname']
325 edited_last_name = request.POST['lname']
328 for user_config in user_details:
329 if user_config['config']:
330 config = json.loads(user_config['config'])
331 config['firstname'] = edited_first_name
332 config['lastname'] = edited_last_name
333 config['authority'] = config.get('authority','Unknown Authority')
334 updated_config = json.dumps(config)
335 user_params = {'config': updated_config}
336 else: # it's needed if the config is empty
337 user_config['config']= '{"firstname":"' + edited_first_name + '", "lastname":"'+ edited_last_name + '", "authority": "Unknown Authority"}'
338 user_params = {'config': user_config['config']}
339 # updating config local:user in manifold
340 manifold_update_user(request, request.user.email,user_params)
341 # this will be depricated, we will show the success msg in same page
342 # Redirect to same page with success message
343 messages.success(request, 'Sucess: First Name and Last Name Updated.')
344 return HttpResponseRedirect("/portal/account/")
346 elif 'submit_pass' in request.POST:
347 edited_password = request.POST['password']
349 for user_pass in user_details:
350 user_pass['password'] = edited_password
351 #updating password in local:user
352 user_params = { 'password': user_pass['password']}
353 manifold_update_user(request,request.user.email,user_params)
354 # return HttpResponse('Success: Password Changed!!')
355 messages.success(request, 'Sucess: Password Updated.')
356 return HttpResponseRedirect("/portal/account/")
358 # XXX TODO: Factorize with portal/registrationview.py
359 # XXX TODO: Factorize with portal/registrationview.py
360 # XXX TODO: Factorize with portal/joinview.py
362 elif 'generate' in request.POST:
363 for account_detail in account_details:
364 for platform_detail in platform_details:
365 if platform_detail['platform_id'] == account_detail['platform_id']:
366 if 'myslice' in platform_detail['platform']:
367 private = RSA.generate(1024)
368 private_key = json.dumps(private.exportKey())
369 public = private.publickey()
370 public_key = json.dumps(public.exportKey(format='OpenSSH'))
371 # updating manifold local:account table
372 account_config = json.loads(account_detail['config'])
373 # preserving user_hrn
374 user_hrn = account_config.get('user_hrn','N/A')
375 keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
376 #updated_config = json.dumps(account_config)
378 #user_params = { 'config': keypair, 'auth_type':'managed'}
379 #manifold_update_account(request, user_id, user_params)
381 public_key = public_key.replace('"', '');
382 user_pub_key = {'keys': public_key}
383 #sfa_update_user(request, user_hrn, user_pub_key)
384 sfa_update_user(request, user_hrn, user_pub_key)
385 result_sfa_user = sfa_get_user(request, user_hrn, public_key)
387 result_sfa_user = result_sfa_user[0]
388 if 'keys' in result_sfa_user and result_sfa_user['keys'][0] == public_key:
390 updated_config = json.dumps(account_config)
391 user_params = { 'config': keypair, 'auth_type':'managed'}
392 manifold_update_account(request, user_id, user_params)
393 messages.success(request, 'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.')
395 raise Exception,"Keys are not matching"
397 messages.error(request, 'Error: An error occured during the update of your public key at the Registry, or your public key is not matching the one stored.')
398 return HttpResponseRedirect("/portal/account/")
400 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
401 return HttpResponseRedirect("/portal/account/")
403 elif 'upload_key' in request.POST:
404 for account_detail in account_details:
405 for platform_detail in platform_details:
406 if platform_detail['platform_id'] == account_detail['platform_id']:
407 if 'myslice' in platform_detail['platform']:
408 up_file = request.FILES['pubkey']
409 file_content = up_file.read()
410 file_name = up_file.name
411 file_extension = os.path.splitext(file_name)[1]
412 allowed_extension = ['.pub','.txt']
413 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
414 account_config = json.loads(account_detail['config'])
415 # preserving user_hrn
416 user_hrn = account_config.get('user_hrn','N/A')
417 file_content = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
418 #file_content = re.sub("\r", "", file_content)
419 #file_content = re.sub("\n", "\\n",file_content)
420 file_content = ''.join(file_content.split())
421 #update manifold local:account table
422 user_params = { 'config': file_content, 'auth_type':'user'}
423 manifold_update_account(request, user_id, user_params)
425 user_pub_key = {'keys': file_content}
426 sfa_update_user(request, user_hrn, user_pub_key)
427 messages.success(request, 'Publickey uploaded! Please delegate your credentials using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
428 return HttpResponseRedirect("/portal/account/")
430 messages.error(request, 'RSA key error: Please upload a valid RSA public key [.txt or .pub].')
431 return HttpResponseRedirect("/portal/account/")
433 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
434 return HttpResponseRedirect("/portal/account/")
436 elif 'dl_pubkey' in request.POST:
437 for account_detail in account_details:
438 for platform_detail in platform_details:
439 if platform_detail['platform_id'] == account_detail['platform_id']:
440 if 'myslice' in platform_detail['platform']:
441 account_config = json.loads(account_detail['config'])
442 public_key = account_config['user_public_key']
443 response = HttpResponse(public_key, content_type='text/plain')
444 response['Content-Disposition'] = 'attachment; filename="pubkey.txt"'
448 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
449 return HttpResponseRedirect("/portal/account/")
451 elif 'dl_pkey' in request.POST:
452 for account_detail in account_details:
453 for platform_detail in platform_details:
454 if platform_detail['platform_id'] == account_detail['platform_id']:
455 if 'myslice' in platform_detail['platform']:
456 account_config = json.loads(account_detail['config'])
457 if 'user_private_key' in account_config:
458 private_key = account_config['user_private_key']
459 response = HttpResponse(private_key, content_type='text/plain')
460 response['Content-Disposition'] = 'attachment; filename="privkey.txt"'
463 messages.error(request, 'Download error: Private key is not stored in the server')
464 return HttpResponseRedirect("/portal/account/")
467 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
468 return HttpResponseRedirect("/portal/account/")
470 elif 'delete' in request.POST:
471 for account_detail in account_details:
472 for platform_detail in platform_details:
473 if platform_detail['platform_id'] == account_detail['platform_id']:
474 if 'myslice' in platform_detail['platform']:
475 account_config = json.loads(account_detail['config'])
476 if 'user_private_key' in account_config:
477 for key in account_config.keys():
478 if key == 'user_private_key':
479 del account_config[key]
481 updated_config = json.dumps(account_config)
482 user_params = { 'config': updated_config, 'auth_type':'user'}
483 manifold_update_account(request, user_id, user_params)
484 messages.success(request, 'Private Key deleted. You need to delegate credentials manually once it expires.')
485 messages.success(request, 'Once your credentials expire, Please delegate manually using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
486 return HttpResponseRedirect("/portal/account/")
488 messages.error(request, 'Delete error: Private key is not stored in the server')
489 return HttpResponseRedirect("/portal/account/")
492 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
493 return HttpResponseRedirect("/portal/account/")
495 # download identity for jfed
496 elif 'dl_identity' in request.POST:
497 for account_detail in account_details:
498 for platform_detail in platform_details:
499 if platform_detail['platform_id'] == account_detail['platform_id']:
500 if 'myslice' in platform_detail['platform']:
501 account_config = json.loads(account_detail['config'])
502 if 'user_private_key' in account_config:
503 private_key = account_config['user_private_key']
504 user_hrn = account_config.get('user_hrn','N/A')
505 registry = 'http://sfa-fed4fire.pl.sophia.inria.fr:12345/'
506 jfed_identity = user_hrn + '\n' + registry + '\n' + private_key
507 response = HttpResponse(jfed_identity, content_type='text/plain')
508 response['Content-Disposition'] = 'attachment; filename="jfed_identity.txt"'
511 messages.error(request, 'Download error: Private key is not stored in the server')
512 return HttpResponseRedirect("/portal/account/")
515 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
516 return HttpResponseRedirect("/portal/account/")
519 elif 'clear_cred' in request.POST:
521 result = clear_user_creds(request, user_email)
522 if result is not None:
523 messages.success(request, 'All Credentials cleared')
525 messages.error(request, 'Delete error: Credentials are not stored in the server')
527 print "Exception in accountview.py in clear_user_creds %s" % e
528 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
529 return HttpResponseRedirect("/portal/account/")
531 # Download delegated_user_cred
532 elif 'dl_user_cred' in request.POST:
533 if 'delegated_user_credential' in account_config:
534 user_cred = account_config['delegated_user_credential']
535 response = HttpResponse(user_cred, content_type='text/plain')
536 response['Content-Disposition'] = 'attachment; filename="user_cred.txt"'
539 messages.error(request, 'Download error: User credential is not stored in the server')
540 return HttpResponseRedirect("/portal/account/")
543 elif 'dl_user_cert' in request.POST:
544 if 'user_credential' in account_config:
545 user_cred = account_config['user_credential']
546 obj_cred = Credential(string=user_cred)
547 obj_gid = obj_cred.get_gid_object()
548 str_cert = obj_gid.save_to_string()
549 response = HttpResponse(str_cert, content_type='text/plain')
550 response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
553 elif 'delegated_user_credential' in account_config:
554 user_cred = account_config['delegated_user_credential']
555 obj_cred = Credential(string=user_cred)
556 obj_gid = obj_cred.get_gid_object()
557 str_cert = obj_gid.save_to_string()
558 response = HttpResponse(str_cert, content_type='text/plain')
559 response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
562 messages.error(request, 'Download error: User credential is not stored in the server')
563 return HttpResponseRedirect("/portal/account/")
565 # Download user p12 = private_key + Certificate
566 elif 'dl_user_p12' in request.POST:
567 if 'user_credential' in account_config and 'user_private_key' in account_config:
568 user_cred = account_config['user_credential']
569 obj_cred = Credential(string=user_cred)
570 obj_gid = obj_cred.get_gid_object()
571 str_cert = obj_gid.save_to_string()
572 cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)
574 user_private_key = account_config['user_private_key'].encode('ascii')
575 pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)
577 p12 = crypto.PKCS12()
578 p12.set_privatekey(pkey)
579 p12.set_certificate(cert)
580 pkcs12 = p12.export()
582 response = HttpResponse(pkcs12, content_type='text/plain')
583 response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
586 elif 'delegated_user_credential' in account_config and 'user_private_key' in account_config:
587 user_cred = account_config['delegated_user_credential']
588 obj_cred = Credential(string=user_cred)
589 obj_gid = obj_cred.get_gid_object()
590 str_cert = obj_gid.save_to_string()
591 cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)
593 user_private_key = account_config['user_private_key'].encode('ascii')
594 pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)
596 p12 = crypto.PKCS12()
597 p12.set_privatekey(pkey)
598 p12.set_certificate(cert)
599 pkcs12 = p12.export()
601 response = HttpResponse(pkcs12, content_type='text/plain')
602 response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
605 messages.error(request, 'Download error: User private key or credential is not stored in the server')
606 return HttpResponseRedirect("/portal/account/")
611 messages.info(request, 'Under Construction. Please try again later!')
612 return HttpResponseRedirect("/portal/account/")