2 import json, os, re, itertools, time
3 from OpenSSL import crypto
4 from Crypto.PublicKey import RSA
7 from django.http import HttpResponse, HttpResponseRedirect
8 from django.contrib import messages
9 from django.contrib.auth.decorators import login_required
12 from manifold.core.query import Query
13 from manifoldapi.manifoldapi import execute_query
15 from unfold.loginrequired import LoginRequiredAutoLogoutView
16 from unfold.page import Page
17 from ui.topmenu import topmenu_items_live, the_user
19 from portal.actions import (
20 manifold_update_user, manifold_update_account, manifold_add_account,
21 manifold_delete_account, sfa_update_user, sfa_get_user, clear_user_creds )
22 from portal.account import Account, get_expiration
24 from myslice.settings import logger
25 from myslice.configengine import ConfigEngine
26 from myslice.theme import ThemeView
29 class AccountView(LoginRequiredAutoLogoutView, ThemeView):
30 template_name = "account-view.html"
31 def dispatch(self, *args, **kwargs):
32 return super(AccountView, self).dispatch(*args, **kwargs)
35 def get_context_data(self, **kwargs):
36 self.template_name = self.template
37 page = Page(self.request)
38 metadata = page.get_metadata()
39 page.expose_js_metadata()
41 page.add_js_files ( [ "js/jquery.validate.js", "js/my_account.register.js", "js/my_account.edit_profile.js","js/jquery-ui.js" ] )
42 page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css" ] )
44 # Execute a Query to delegate credentials if necessary
45 #sfa_user_query = Query().get('myslice:user').select('user_hrn').filter_by('user_hrn','==','$user_hrn')
46 #sfa_user_result = execute_query(self.request, sfa_user_query)
48 user_query = Query().get('local:user').select('config','email','status')
49 user_details = execute_query(self.request, user_query)
51 # not always found in user_details...
53 for user_detail in user_details:
54 # different significations of user_status
55 if user_detail['status'] == 0:
56 user_status = 'Disabled'
57 elif user_detail['status'] == 1:
58 user_status = 'Validation Pending'
59 elif user_detail['status'] == 2:
60 user_status = 'Enabled'
63 #email = user_detail['email']
64 if user_detail['config']:
65 config = json.loads(user_detail['config'])
67 platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
68 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
69 platform_details = execute_query(self.request, platform_query)
70 account_details = execute_query(self.request, account_query)
72 # initial assignment needed for users having account.config = {}
78 account_reference = ''
83 principal_acc_list = ''
85 platform_name_list = []
86 platform_name_secondary_list = []
87 platform_access_list = []
88 platform_no_access_list = []
89 total_platform_list = []
90 account_type_list = []
91 account_type_secondary_list = []
92 account_reference_list = []
93 delegation_type_list = []
94 user_cred_exp_list = []
97 slice_cred_exp_list = []
98 auth_cred_exp_list = []
102 for platform_detail in platform_details:
103 if 'sfa' in platform_detail['gateway_type']:
104 total_platform = platform_detail['platform']
105 total_platform_list.append(total_platform)
107 for account_detail in account_details:
108 if platform_detail['platform_id'] == account_detail['platform_id']:
109 platform_name = platform_detail['platform']
110 if 'config' in account_detail and account_detail['config'] is not '':
111 account_config = json.loads(account_detail['config'])
112 account_usr_hrn = account_config.get('user_hrn','N/A')
113 account_pub_key = account_config.get('user_public_key','N/A')
114 account_reference = account_config.get ('reference_platform','N/A')
115 # credentials of myslice platform
116 if 'myslice' in platform_detail['platform']:
117 acc_user_cred = account_config.get('delegated_user_credential','N/A')
118 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
119 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
121 if 'N/A' not in acc_user_cred:
122 exp_date = re.search('<expires>(.*)</expires>', acc_user_cred)
124 user_exp_date = exp_date.group(1)
125 user_cred_exp_list.append(user_exp_date)
127 my_users = [{'cred_exp': t[0]}
128 for t in zip(user_cred_exp_list)]
131 if 'N/A' not in acc_slice_cred:
132 for key, value in acc_slice_cred.iteritems():
133 slice_list.append(key)
135 exp_date = re.search('<expires>(.*)</expires>', value)
137 exp_date = exp_date.group(1)
138 slice_cred_exp_list.append(exp_date)
140 my_slices = [{'slice_name': t[0], 'cred_exp': t[1]}
141 for t in zip(slice_list, slice_cred_exp_list)]
143 if 'N/A' not in acc_auth_cred:
144 for key, value in acc_auth_cred.iteritems():
145 auth_list.append(key)
147 exp_date = re.search('<expires>(.*)</expires>', value)
149 exp_date = exp_date.group(1)
150 auth_cred_exp_list.append(exp_date)
152 my_auths = [{'auth_name': t[0], 'cred_exp': t[1]}
153 for t in zip(auth_list, auth_cred_exp_list)]
156 # for reference accounts
157 if 'reference' in account_detail['auth_type']:
158 account_type = 'Reference'
160 platform_name_secondary_list.append(platform_name)
161 account_type_secondary_list.append(account_type)
162 account_reference_list.append(account_reference)
163 ref_acc_list = [{'platform_name': t[0], 'account_type': t[1], 'account_reference': t[2]}
164 for t in zip(platform_name_secondary_list, account_type_secondary_list, account_reference_list)]
166 elif 'managed' in account_detail['auth_type']:
167 account_type = 'Principal'
168 delegation = 'Automatic'
170 account_type = 'Principal'
171 delegation = 'Manual'
172 # for principal (auth_type=user/managed) accounts
173 if 'reference' not in account_detail['auth_type']:
174 platform_name_list.append(platform_name)
175 account_type_list.append(account_type)
176 delegation_type_list.append(delegation)
177 usr_hrn_list.append(account_usr_hrn)
178 pub_key_list.append(account_pub_key)
179 user_status_list.append(user_status)
180 # combining 5 lists into 1 [to render in the template]
181 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],}
182 for t in zip(platform_name_list, account_type_list, delegation_type_list, usr_hrn_list, pub_key_list, user_status_list)]
183 # to hide private key row if it doesn't exist
184 if 'myslice' in platform_detail['platform']:
185 account_config = json.loads(account_detail['config'])
186 account_priv_key = account_config.get('user_private_key','N/A')
187 if 'sfa' in platform_detail['gateway_type']:
188 platform_access = platform_detail['platform']
189 platform_access_list.append(platform_access)
191 # Removing the platform which already has access
192 for platform in platform_access_list:
193 total_platform_list.remove(platform)
194 # we could use zip. this one is used if columns have unequal rows
195 platform_list = [{'platform_no_access': t[0]}
196 for t in itertools.izip_longest(total_platform_list)]
199 ## check user is pi or not
200 # platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
201 # account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
202 # platform_details = execute_query(self.request, platform_query)
203 # account_details = execute_query(self.request, account_query)
204 # for platform_detail in platform_details:
205 # for account_detail in account_details:
206 # if platform_detail['platform_id'] == account_detail['platform_id']:
207 # if 'config' in account_detail and account_detail['config'] is not '':
208 # account_config = json.loads(account_detail['config'])
209 # if 'myslice' in platform_detail['platform']:
210 # acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
212 if acc_auth_cred == {} or acc_auth_cred == 'N/A':
217 # check if the user has creds or not
218 if acc_user_cred == {} or acc_user_cred == 'N/A':
219 user_cred = 'no_creds'
221 exp_date = get_expiration(acc_user_cred, 'timestamp')
222 if exp_date < time.time():
223 user_cred = 'creds_expired'
225 user_cred = 'has_creds'
227 context = super(AccountView, self).get_context_data(**kwargs)
228 context['principal_acc'] = principal_acc_list
229 context['ref_acc'] = ref_acc_list
230 context['platform_list'] = platform_list
231 context['my_users'] = my_users
233 context['user_cred'] = user_cred
234 context['my_slices'] = my_slices
235 context['my_auths'] = my_auths
236 context['user_status'] = user_status
237 context['person'] = self.request.user
238 context['firstname'] = config.get('firstname',"?")
239 context['lastname'] = config.get('lastname',"?")
240 context['fullname'] = context['firstname'] +' '+ context['lastname']
241 context['authority'] = config.get('authority',"Unknown Authority")
242 context['user_private_key'] = account_priv_key
244 # XXX This is repeated in all pages
245 # more general variables expected in the template
246 context['title'] = 'Platforms connected to MySlice'
247 # the menu items on the top
248 context['topmenu_items'] = topmenu_items_live('My Account', page)
249 # so we can sho who is logged
250 context['username'] = the_user(self.request)
251 context['theme'] = self.theme
252 context['section'] = "User account"
253 # context ['firstname'] = config['firstname']
254 prelude_env = page.prelude_env()
255 context.update(prelude_env)
259 def get_myslice_platform(request):
260 platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled','config').filter_by('platform','==','myslice')
261 platform_details = execute_query(request, platform_query)
262 for platform_detail in platform_details:
263 return platform_detail
266 def get_myslice_account(request):
267 platform_myslice = get_myslice_platform(request)
268 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config').filter_by('platform_id','==',platform_myslice['platform_id'])
269 account_details = execute_query(request, account_query)
270 for account_detail in account_details:
271 return account_detail
274 #my_acc form value processing
275 def account_process(request):
276 from sfa.trust.credential import Credential
277 from sfa.trust.certificate import Keypair
279 user_query = Query().get('local:user').select('user_id','email','password','config')
280 user_details = execute_query(request, user_query)
282 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
283 account_details = execute_query(request, account_query)
285 platform_query = Query().get('local:platform').select('platform_id','platform')
286 platform_details = execute_query(request, platform_query)
288 # getting the user_id from the session
289 for user_detail in user_details:
290 user_id = user_detail['user_id']
291 user_email = user_detail['email']
293 if user_email == request.user.email:
294 authorize_query = True
296 logger.error("SECURITY: {} tried to update {}".format(user_email, request.user.email))
297 messages.error(request, 'You are not authorized to modify another user.')
298 return HttpResponseRedirect("/portal/account/")
299 except Exception as e:
300 logger.error("exception in account_process {}".format(e))
302 for account_detail in account_details:
303 for platform_detail in platform_details:
304 # Add reference account to the platforms
305 if 'add_'+platform_detail['platform'] in request.POST or request.POST['button_value'] == 'add_'+platform_detail['platform']:
306 platform_id = platform_detail['platform_id']
307 user_params = {'platform_id': platform_id, 'user_id': user_id, 'auth_type': "reference", 'config': '{"reference_platform": "myslice"}'}
308 manifold_add_account(request,user_params)
309 messages.info(request, 'Reference Account is added to the selected platform successfully!')
310 return HttpResponseRedirect("/portal/account/")
312 # Delete reference account from the platforms
313 if 'delete_'+platform_detail['platform'] in request.POST or request.POST['button_value'] == 'delete_'+platform_detail['platform']:
314 platform_id = platform_detail['platform_id']
315 user_params = {'user_id':user_id}
316 manifold_delete_account(request,platform_id, user_id, user_params)
317 messages.info(request, 'Reference Account is removed from the selected platform')
318 return HttpResponseRedirect("/portal/account/")
320 if platform_detail['platform_id'] == account_detail['platform_id']:
321 if 'myslice' in platform_detail['platform']:
322 account_config = json.loads(account_detail['config'])
323 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
324 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
329 # adding the slices and corresponding credentials to list
330 if 'N/A' not in acc_slice_cred:
333 for key, value in acc_slice_cred.iteritems():
334 slice_list.append(key)
335 slice_cred.append(value)
336 # special case: download each slice credentials separately
337 for i in range(0, len(slice_list)):
338 if 'dl_'+slice_list[i] in request.POST or request.POST['button_value'] == 'dl_'+slice_list[i]:
339 slice_detail = "Slice name: " + slice_list[i] +"\nSlice Credentials: \n"+ slice_cred[i]
340 response = HttpResponse(slice_detail, content_type='text/plain')
341 response['Content-Disposition'] = 'attachment; filename="slice_credential.txt"'
344 # adding the authority and corresponding credentials to list
345 if 'N/A' not in acc_auth_cred:
348 for key, value in acc_auth_cred.iteritems():
349 auth_list.append(key)
350 auth_cred.append(value)
351 # special case: download each slice credentials separately
352 for i in range(0, len(auth_list)):
353 if 'dl_'+auth_list[i] in request.POST or request.POST['button_value'] == 'dl_'+auth_list[i]:
354 auth_detail = "Authority: " + auth_list[i] +"\nAuthority Credentials: \n"+ auth_cred[i]
355 response = HttpResponse(auth_detail, content_type='text/plain')
356 response['Content-Disposition'] = 'attachment; filename="auth_credential.txt"'
361 if 'submit_name' in request.POST:
362 edited_first_name = request.POST['fname']
363 edited_last_name = request.POST['lname']
366 for user_config in user_details:
367 if user_config['config']:
368 config = json.loads(user_config['config'])
369 config['firstname'] = edited_first_name
370 config['lastname'] = edited_last_name
371 config['authority'] = config.get('authority','Unknown Authority')
372 updated_config = json.dumps(config)
373 user_params = {'config': updated_config}
374 else: # it's needed if the config is empty
375 user_config['config']= '{"firstname":"' + edited_first_name + '", "lastname":"'+ edited_last_name + '", "authority": "Unknown Authority"}'
376 user_params = {'config': user_config['config']}
377 # updating config local:user in manifold
378 manifold_update_user(request, request.user.email,user_params)
379 # this will be depricated, we will show the success msg in same page
380 # Redirect to same page with success message
381 messages.success(request, 'Sucess: First Name and Last Name Updated.')
382 return HttpResponseRedirect("/portal/account/")
384 elif 'submit_pass' in request.POST:
385 edited_password = request.POST['password']
387 for user_pass in user_details:
388 user_pass['password'] = edited_password
389 #updating password in local:user
390 user_params = { 'password': user_pass['password']}
391 manifold_update_user(request,request.user.email,user_params)
392 # return HttpResponse('Success: Password Changed!!')
393 messages.success(request, 'Sucess: Password Updated.')
394 return HttpResponseRedirect("/portal/account/")
396 # XXX TODO: Factorize with portal/registrationview.py
397 # XXX TODO: Factorize with portal/registrationview.py
398 # XXX TODO: Factorize with portal/joinview.py
400 elif 'generate' in request.POST:
401 for account_detail in account_details:
402 for platform_detail in platform_details:
403 if platform_detail['platform_id'] == account_detail['platform_id']:
404 if 'myslice' in platform_detail['platform']:
405 private = RSA.generate(1024)
406 private_key = json.dumps(private.exportKey())
407 public = private.publickey()
408 public_key = json.dumps(public.exportKey(format='OpenSSH'))
409 # updating manifold local:account table
410 account_config = json.loads(account_detail['config'])
411 # preserving user_hrn
412 user_hrn = account_config.get('user_hrn','N/A')
413 keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
414 #updated_config = json.dumps(account_config)
416 #user_params = { 'config': keypair, 'auth_type':'managed'}
417 #manifold_update_account(request, user_id, user_params)
419 public_key = public_key.replace('"', '');
420 user_pub_key = {'keys': public_key}
422 sfa_update_user(request, user_hrn, user_pub_key)
423 result_sfa_user = sfa_get_user(request, user_hrn, public_key)
425 if 'keys' in result_sfa_user and result_sfa_user['keys'][0] == public_key:
427 updated_config = json.dumps(account_config)
428 user_params = { 'config': keypair, 'auth_type':'managed'}
429 manifold_update_account(request, user_id, user_params)
430 messages.success(request, 'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.')
432 raise Exception,"Keys are not matching"
433 except Exception as e:
434 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.')
435 logger.error("Exception in accountview {}".format(e))
436 return HttpResponseRedirect("/portal/account/")
438 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
439 return HttpResponseRedirect("/portal/account/")
441 elif 'upload_key' in request.POST:
442 for account_detail in account_details:
443 for platform_detail in platform_details:
444 if platform_detail['platform_id'] == account_detail['platform_id']:
445 if 'myslice' in platform_detail['platform']:
446 up_file = request.FILES['pubkey']
447 file_content = up_file.read()
448 file_name = up_file.name
449 file_extension = os.path.splitext(file_name)[1]
450 allowed_extension = ['.pub','.txt']
451 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
452 account_config = json.loads(account_detail['config'])
453 # preserving user_hrn
454 user_hrn = account_config.get('user_hrn','N/A')
455 file_content = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
456 #file_content = re.sub("\r", "", file_content)
457 #file_content = re.sub("\n", "\\n",file_content)
458 file_content = ''.join(file_content.split())
459 #update manifold local:account table
460 user_params = { 'config': file_content, 'auth_type':'user'}
461 manifold_update_account(request, user_id, user_params)
463 user_pub_key = {'keys': file_content}
464 sfa_update_user(request, user_hrn, user_pub_key)
465 messages.success(request, 'Publickey uploaded! Please delegate your credentials using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
466 return HttpResponseRedirect("/portal/account/")
468 messages.error(request, 'RSA key error: Please upload a valid RSA public key [.txt or .pub].')
469 return HttpResponseRedirect("/portal/account/")
471 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
472 return HttpResponseRedirect("/portal/account/")
474 elif 'dl_pubkey' in request.POST or request.POST['button_value'] == 'dl_pubkey':
475 for account_detail in account_details:
476 for platform_detail in platform_details:
477 if platform_detail['platform_id'] == account_detail['platform_id']:
478 if 'myslice' in platform_detail['platform']:
479 account_config = json.loads(account_detail['config'])
480 public_key = account_config['user_public_key']
481 response = HttpResponse(public_key, content_type='text/plain')
482 response['Content-Disposition'] = 'attachment; filename="pubkey.txt"'
486 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
487 return HttpResponseRedirect("/portal/account/")
489 elif 'dl_pkey' in request.POST or request.POST['button_value'] == 'dl_pkey':
490 for account_detail in account_details:
491 for platform_detail in platform_details:
492 if platform_detail['platform_id'] == account_detail['platform_id']:
493 if 'myslice' in platform_detail['platform']:
494 account_config = json.loads(account_detail['config'])
495 if 'user_private_key' in account_config:
496 private_key = account_config['user_private_key']
497 response = HttpResponse(private_key, content_type='text/plain')
498 response['Content-Disposition'] = 'attachment; filename="privkey.txt"'
501 messages.error(request, 'Download error: Private key is not stored in the server')
502 return HttpResponseRedirect("/portal/account/")
505 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
506 return HttpResponseRedirect("/portal/account/")
508 elif 'delete' in request.POST or request.POST['button_value'] == 'delete':
509 for account_detail in account_details:
510 for platform_detail in platform_details:
511 if platform_detail['platform_id'] == account_detail['platform_id']:
512 if 'myslice' in platform_detail['platform']:
513 account_config = json.loads(account_detail['config'])
514 if 'user_private_key' in account_config:
515 for key in account_config.keys():
516 if key == 'user_private_key':
517 del account_config[key]
519 updated_config = json.dumps(account_config)
520 user_params = { 'config': updated_config, 'auth_type':'user'}
521 manifold_update_account(request, user_id, user_params)
522 messages.success(request, 'Private Key deleted. You need to delegate credentials manually once it expires.')
523 messages.success(request, 'Once your credentials expire, Please delegate manually using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
524 return HttpResponseRedirect("/portal/account/")
526 messages.error(request, 'Delete error: Private key is not stored in the server')
527 return HttpResponseRedirect("/portal/account/")
530 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
531 return HttpResponseRedirect("/portal/account/")
533 # download identity for jfed
534 elif 'dl_identity' in request.POST or request.POST['button_value'] == 'dl_identity':
535 for account_detail in account_details:
536 for platform_detail in platform_details:
537 if platform_detail['platform_id'] == account_detail['platform_id']:
538 if 'myslice' in platform_detail['platform']:
539 account_config = json.loads(account_detail['config'])
540 if 'user_private_key' in account_config:
541 private_key = account_config['user_private_key']
542 user_hrn = account_config.get('user_hrn','N/A')
543 registry = 'http://sfa-fed4fire.pl.sophia.inria.fr:12345/'
544 jfed_identity = user_hrn + '\n' + registry + '\n' + private_key
545 response = HttpResponse(jfed_identity, content_type='text/plain')
546 response['Content-Disposition'] = 'attachment; filename="jfed_identity.txt"'
549 messages.error(request, 'Download error: Private key is not stored in the server')
550 return HttpResponseRedirect("/portal/account/")
553 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
554 return HttpResponseRedirect("/portal/account/")
556 # Download sfi_config
557 elif 'dl_sfi_config' in request.POST or request.POST['button_value'] == 'dl_sfi_config':
558 platform_detail = get_myslice_platform(request)
559 platform_config = json.loads(platform_detail['config'])
560 account_detail = get_myslice_account(request)
561 account_config = json.loads(account_detail['config'])
563 user_hrn = account_config.get('user_hrn','N/A')
564 t_user_hrn = user_hrn.split('.')
565 authority_hrn = t_user_hrn[0] + '.' + t_user_hrn[1]
567 hostname = socket.gethostbyaddr(socket.gethostname())[0]
568 registry = platform_config.get('registry','N/A')
569 admin_user = platform_config.get('user','N/A')
570 if 'localhost' in registry:
571 port = registry.split(':')[-1:][0]
572 registry = "http://" + hostname +':'+ port
573 manifold_host = ConfigEngine().manifold_url()
574 if 'localhost' in manifold_host:
575 manifold_host = manifold_host.replace('localhost',hostname)
576 sfi_config = '[sfi]\n'
577 sfi_config += 'auth = '+ authority_hrn +'\n'
578 sfi_config += 'user = '+ user_hrn +'\n'
579 sfi_config += 'registry = '+ registry +'\n'
580 sfi_config += 'sm = http://sfa3.planet-lab.eu:12346/\n\n'
581 sfi_config += '[myslice]\n'
582 sfi_config += 'backend = '+ manifold_host +'\n'
583 sfi_config += 'delegate = '+ admin_user +'\n'
584 sfi_config += 'platform = myslice\n'
585 sfi_config += 'username = '+ user_email +'\n'
586 response = HttpResponse(sfi_config, content_type='text/plain')
587 response['Content-Disposition'] = 'attachment; filename="sfi_config"'
591 elif 'clear_cred' in request.POST or request.POST['button_value'] == 'clear_cred':
593 result = clear_user_creds(request, user_email)
594 if result is not None:
595 messages.success(request, 'All Credentials cleared')
597 messages.error(request, 'Delete error: Credentials are not stored in the server')
598 except Exception as e:
599 logger.error("Exception in accountview.py in clear_user_creds {}".format(e))
600 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
601 return HttpResponseRedirect("/portal/account/")
603 # Download delegated_user_cred
604 elif 'dl_user_cred' in request.POST or request.POST['button_value'] == 'dl_user_cred':
605 if 'delegated_user_credential' in account_config:
606 user_cred = account_config['delegated_user_credential']
607 response = HttpResponse(user_cred, content_type='text/plain')
608 response['Content-Disposition'] = 'attachment; filename="user_cred.txt"'
611 messages.error(request, 'Download error: User credential is not stored in the server')
612 return HttpResponseRedirect("/portal/account/")
615 elif 'dl_user_cert' in request.POST or request.POST['button_value'] == 'dl_user_cert':
616 if 'user_credential' in account_config:
617 user_cred = account_config['user_credential']
618 obj_cred = Credential(string=user_cred)
619 obj_gid = obj_cred.get_gid_object()
620 str_cert = obj_gid.save_to_string()
621 response = HttpResponse(str_cert, content_type='text/plain')
622 response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
625 elif 'delegated_user_credential' in account_config:
626 user_cred = account_config['delegated_user_credential']
627 obj_cred = Credential(string=user_cred)
628 obj_gid = obj_cred.get_gid_object()
629 str_cert = obj_gid.save_to_string()
630 response = HttpResponse(str_cert, content_type='text/plain')
631 response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
634 messages.error(request, 'Download error: User credential is not stored in the server')
635 return HttpResponseRedirect("/portal/account/")
637 # Download user p12 = private_key + Certificate
638 elif 'dl_user_p12' in request.POST or request.POST['button_value'] == 'dl_user_p12':
639 if 'user_credential' in account_config and 'user_private_key' in account_config:
640 user_cred = account_config['user_credential']
641 obj_cred = Credential(string=user_cred)
642 obj_gid = obj_cred.get_gid_object()
643 str_cert = obj_gid.save_to_string()
644 cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)
646 user_private_key = account_config['user_private_key'].encode('ascii')
647 pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)
649 p12 = crypto.PKCS12()
650 p12.set_privatekey(pkey)
651 p12.set_certificate(cert)
652 pkcs12 = p12.export()
654 response = HttpResponse(pkcs12, content_type='text/plain')
655 response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
658 elif 'delegated_user_credential' in account_config and 'user_private_key' in account_config:
659 user_cred = account_config['delegated_user_credential']
660 obj_cred = Credential(string=user_cred)
661 obj_gid = obj_cred.get_gid_object()
662 str_cert = obj_gid.save_to_string()
663 cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)
665 user_private_key = account_config['user_private_key'].encode('ascii')
666 pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)
668 p12 = crypto.PKCS12()
669 p12.set_privatekey(pkey)
670 p12.set_certificate(cert)
671 pkcs12 = p12.export()
673 response = HttpResponse(pkcs12, content_type='text/plain')
674 response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
677 messages.error(request, 'Download error: User private key or credential is not stored in the server')
678 return HttpResponseRedirect("/portal/account/")
681 messages.info(request, 'Under Construction. Please try again later!')
682 return HttpResponseRedirect("/portal/account/")