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, get_myslice_account, get_myslice_platform, get_registry_url, get_jfed_identity )
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 account_process(request):
260 from sfa.trust.credential import Credential
261 from sfa.trust.certificate import Keypair
263 user_query = Query().get('local:user').select('user_id','email','password','config')
264 user_details = execute_query(request, user_query)
266 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
267 account_details = execute_query(request, account_query)
269 platform_query = Query().get('local:platform').select('platform_id','platform')
270 platform_details = execute_query(request, platform_query)
272 # getting the user_id from the session
273 for user_detail in user_details:
274 user_id = user_detail['user_id']
275 user_email = user_detail['email']
277 if user_email == request.user.email:
278 authorize_query = True
280 logger.error("SECURITY: {} tried to update {}".format(user_email, request.user.email))
281 messages.error(request, 'You are not authorized to modify another user.')
282 return HttpResponseRedirect("/portal/account/")
283 except Exception as e:
284 logger.error("exception in account_process {}".format(e))
286 for account_detail in account_details:
287 for platform_detail in platform_details:
288 # Add reference account to the platforms
289 if 'add_'+platform_detail['platform'] in request.POST or request.POST['button_value'] == 'add_'+platform_detail['platform']:
290 platform_id = platform_detail['platform_id']
291 user_params = {'platform_id': platform_id, 'user_id': user_id, 'auth_type': "reference", 'config': '{"reference_platform": "myslice"}'}
292 manifold_add_account(request,user_params)
293 messages.info(request, 'Reference Account is added to the selected platform successfully!')
294 return HttpResponseRedirect("/portal/account/")
296 # Delete reference account from the platforms
297 if 'delete_'+platform_detail['platform'] in request.POST or request.POST['button_value'] == 'delete_'+platform_detail['platform']:
298 platform_id = platform_detail['platform_id']
299 user_params = {'user_id':user_id}
300 manifold_delete_account(request,platform_id, user_id, user_params)
301 messages.info(request, 'Reference Account is removed from the selected platform')
302 return HttpResponseRedirect("/portal/account/")
304 if platform_detail['platform_id'] == account_detail['platform_id']:
305 if 'myslice' in platform_detail['platform']:
306 account_config = json.loads(account_detail['config'])
307 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
308 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
313 # adding the slices and corresponding credentials to list
314 if 'N/A' not in acc_slice_cred:
317 for key, value in acc_slice_cred.iteritems():
318 slice_list.append(key)
319 slice_cred.append(value)
320 # special case: download each slice credentials separately
321 for i in range(0, len(slice_list)):
322 if 'dl_'+slice_list[i] in request.POST or request.POST['button_value'] == 'dl_'+slice_list[i]:
323 slice_detail = "Slice name: " + slice_list[i] +"\nSlice Credentials: \n"+ slice_cred[i]
324 response = HttpResponse(slice_detail, content_type='text/plain')
325 response['Content-Disposition'] = 'attachment; filename="slice_credential.txt"'
328 # adding the authority and corresponding credentials to list
329 if 'N/A' not in acc_auth_cred:
332 for key, value in acc_auth_cred.iteritems():
333 auth_list.append(key)
334 auth_cred.append(value)
335 # special case: download each slice credentials separately
336 for i in range(0, len(auth_list)):
337 if 'dl_'+auth_list[i] in request.POST or request.POST['button_value'] == 'dl_'+auth_list[i]:
338 auth_detail = "Authority: " + auth_list[i] +"\nAuthority Credentials: \n"+ auth_cred[i]
339 response = HttpResponse(auth_detail, content_type='text/plain')
340 response['Content-Disposition'] = 'attachment; filename="auth_credential.txt"'
343 account_detail = get_myslice_account(request)
345 if 'submit_name' in request.POST:
346 edited_first_name = request.POST['fname']
347 edited_last_name = request.POST['lname']
350 for user_config in user_details:
351 if user_config['config']:
352 config = json.loads(user_config['config'])
353 config['firstname'] = edited_first_name
354 config['lastname'] = edited_last_name
355 config['authority'] = config.get('authority','Unknown Authority')
356 updated_config = json.dumps(config)
357 user_params = {'config': updated_config}
358 else: # it's needed if the config is empty
359 user_config['config']= '{"firstname":"' + edited_first_name + '", "lastname":"'+ edited_last_name + '", "authority": "Unknown Authority"}'
360 user_params = {'config': user_config['config']}
361 # updating config local:user in manifold
362 manifold_update_user(request, request.user.email,user_params)
363 # this will be depricated, we will show the success msg in same page
364 # Redirect to same page with success message
365 messages.success(request, 'Sucess: First Name and Last Name Updated.')
366 return HttpResponseRedirect("/portal/account/")
368 elif 'submit_pass' in request.POST:
369 edited_password = request.POST['password']
371 for user_pass in user_details:
372 user_pass['password'] = edited_password
373 #updating password in local:user
374 user_params = { 'password': user_pass['password']}
375 manifold_update_user(request,request.user.email,user_params)
376 # return HttpResponse('Success: Password Changed!!')
377 messages.success(request, 'Sucess: Password Updated.')
378 return HttpResponseRedirect("/portal/account/")
380 # XXX TODO: Factorize with portal/registrationview.py
381 # XXX TODO: Factorize with portal/registrationview.py
382 # XXX TODO: Factorize with portal/joinview.py
384 elif 'generate' in request.POST:
386 private = RSA.generate(1024)
387 private_key = json.dumps(private.exportKey())
388 public = private.publickey()
389 public_key = json.dumps(public.exportKey(format='OpenSSH'))
390 # updating manifold local:account table
391 account_config = json.loads(account_detail['config'])
392 # preserving user_hrn
393 user_hrn = account_config.get('user_hrn','N/A')
394 keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
395 #updated_config = json.dumps(account_config)
397 #user_params = { 'config': keypair, 'auth_type':'managed'}
398 #manifold_update_account(request, user_id, user_params)
400 public_key = public_key.replace('"', '');
401 user_pub_key = {'keys': public_key}
403 sfa_update_user(request, user_hrn, user_pub_key)
404 result_sfa_user = sfa_get_user(request, user_hrn, public_key)
406 if 'keys' in result_sfa_user and result_sfa_user['keys'][0] == public_key:
408 updated_config = json.dumps(account_config)
409 user_params = { 'config': keypair, 'auth_type':'managed'}
410 manifold_update_account(request, user_id, user_params)
411 messages.success(request, 'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.')
413 raise Exception,"Keys are not matching"
414 except Exception as e:
415 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.')
416 logger.error("Exception in accountview {}".format(e))
417 return HttpResponseRedirect("/portal/account/")
418 except Exception as e:
419 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
420 return HttpResponseRedirect("/portal/account/")
422 elif 'upload_key' in request.POST:
424 up_file = request.FILES['pubkey']
425 file_content = up_file.read()
426 file_name = up_file.name
427 file_extension = os.path.splitext(file_name)[1]
428 allowed_extension = ['.pub','.txt']
429 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
430 account_config = json.loads(account_detail['config'])
431 # preserving user_hrn
432 user_hrn = account_config.get('user_hrn','N/A')
433 file_content = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
434 #file_content = re.sub("\r", "", file_content)
435 #file_content = re.sub("\n", "\\n",file_content)
436 file_content = ''.join(file_content.split())
437 #update manifold local:account table
438 user_params = { 'config': file_content, 'auth_type':'user'}
439 manifold_update_account(request, user_id, user_params)
441 user_pub_key = {'keys': file_content}
442 sfa_update_user(request, user_hrn, user_pub_key)
443 messages.success(request, 'Publickey uploaded! Please delegate your credentials using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
444 return HttpResponseRedirect("/portal/account/")
446 messages.error(request, 'RSA key error: Please upload a valid RSA public key [.txt or .pub].')
447 return HttpResponseRedirect("/portal/account/")
449 except Exception as e:
450 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
451 return HttpResponseRedirect("/portal/account/")
453 elif 'dl_pubkey' in request.POST or request.POST['button_value'] == 'dl_pubkey':
455 account_config = json.loads(account_detail['config'])
456 public_key = account_config['user_public_key']
457 response = HttpResponse(public_key, content_type='text/plain')
458 response['Content-Disposition'] = 'attachment; filename="pubkey.txt"'
460 except Exception as e:
461 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
462 return HttpResponseRedirect("/portal/account/")
464 elif 'dl_pkey' in request.POST or request.POST['button_value'] == 'dl_pkey':
466 account_config = json.loads(account_detail['config'])
467 if 'user_private_key' in account_config:
468 private_key = account_config['user_private_key']
469 response = HttpResponse(private_key, content_type='text/plain')
470 response['Content-Disposition'] = 'attachment; filename="privkey.txt"'
473 messages.error(request, 'Download error: Private key is not stored in the server')
474 return HttpResponseRedirect("/portal/account/")
476 except Exception as e:
477 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
478 return HttpResponseRedirect("/portal/account/")
480 elif 'delete' in request.POST or request.POST['button_value'] == 'delete':
482 account_config = json.loads(account_detail['config'])
483 if 'user_private_key' in account_config:
484 for key in account_config.keys():
485 if key == 'user_private_key':
486 del account_config[key]
488 updated_config = json.dumps(account_config)
489 user_params = { 'config': updated_config, 'auth_type':'user'}
490 manifold_update_account(request, user_id, user_params)
491 messages.success(request, 'Private Key deleted. You need to delegate credentials manually once it expires.')
492 messages.success(request, 'Once your credentials expire, Please delegate manually using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
493 return HttpResponseRedirect("/portal/account/")
495 messages.error(request, 'Delete error: Private key is not stored in the server')
496 return HttpResponseRedirect("/portal/account/")
498 except Exception as e:
499 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
500 return HttpResponseRedirect("/portal/account/")
502 # download identity for jfed
503 elif 'dl_identity' in request.POST or request.POST['button_value'] == 'dl_identity':
505 jfed_identity = get_jfed_identity(request)
506 if jfed_identity is not None:
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/")
514 except Exception as e:
515 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
516 return HttpResponseRedirect("/portal/account/")
518 # Download sfi_config
519 elif 'dl_sfi_config' in request.POST or request.POST['button_value'] == 'dl_sfi_config':
520 platform_detail = get_myslice_platform(request)
521 platform_config = json.loads(platform_detail['config'])
522 account_detail = get_myslice_account(request)
523 account_config = json.loads(account_detail['config'])
525 user_hrn = account_config.get('user_hrn','N/A')
526 t_user_hrn = user_hrn.split('.')
527 authority_hrn = t_user_hrn[0] + '.' + t_user_hrn[1]
528 registry = get_registry_url(request)
530 hostname = socket.gethostbyaddr(socket.gethostname())[0]
531 admin_user = platform_config.get('user','N/A')
532 manifold_host = ConfigEngine().manifold_url()
533 if 'localhost' in manifold_host:
534 manifold_host = manifold_host.replace('localhost',hostname)
535 sfi_config = '[sfi]\n'
536 sfi_config += 'auth = '+ authority_hrn +'\n'
537 sfi_config += 'user = '+ user_hrn +'\n'
538 sfi_config += 'registry = '+ registry +'\n'
539 sfi_config += 'sm = http://sfa3.planet-lab.eu:12346/\n\n'
540 sfi_config += '[myslice]\n'
541 sfi_config += 'backend = '+ manifold_host +'\n'
542 sfi_config += 'delegate = '+ admin_user +'\n'
543 sfi_config += 'platform = myslice\n'
544 sfi_config += 'username = '+ user_email +'\n'
545 response = HttpResponse(sfi_config, content_type='text/plain')
546 response['Content-Disposition'] = 'attachment; filename="sfi_config"'
550 elif 'clear_cred' in request.POST or request.POST['button_value'] == 'clear_cred':
552 result = clear_user_creds(request, user_email)
553 if result is not None:
554 messages.success(request, 'All Credentials cleared')
556 messages.error(request, 'Delete error: Credentials are not stored in the server')
557 except Exception as e:
558 logger.error("Exception in accountview.py in clear_user_creds {}".format(e))
559 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
560 return HttpResponseRedirect("/portal/account/")
562 # Download delegated_user_cred
563 elif 'dl_user_cred' in request.POST or request.POST['button_value'] == 'dl_user_cred':
564 if 'delegated_user_credential' in account_config:
565 user_cred = account_config['delegated_user_credential']
566 response = HttpResponse(user_cred, content_type='text/plain')
567 response['Content-Disposition'] = 'attachment; filename="user_cred.txt"'
570 messages.error(request, 'Download error: User credential is not stored in the server')
571 return HttpResponseRedirect("/portal/account/")
574 elif 'dl_user_cert' in request.POST or request.POST['button_value'] == 'dl_user_cert':
575 if 'user_credential' in account_config:
576 user_cred = account_config['user_credential']
577 obj_cred = Credential(string=user_cred)
578 obj_gid = obj_cred.get_gid_object()
579 str_cert = obj_gid.save_to_string()
580 response = HttpResponse(str_cert, content_type='text/plain')
581 response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
584 elif 'delegated_user_credential' in account_config:
585 user_cred = account_config['delegated_user_credential']
586 obj_cred = Credential(string=user_cred)
587 obj_gid = obj_cred.get_gid_object()
588 str_cert = obj_gid.save_to_string()
589 response = HttpResponse(str_cert, content_type='text/plain')
590 response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
593 messages.error(request, 'Download error: User credential is not stored in the server')
594 return HttpResponseRedirect("/portal/account/")
596 # Download user p12 = private_key + Certificate
597 elif 'dl_user_p12' in request.POST or request.POST['button_value'] == 'dl_user_p12':
598 if 'user_credential' in account_config and 'user_private_key' in account_config:
599 user_cred = account_config['user_credential']
600 obj_cred = Credential(string=user_cred)
601 obj_gid = obj_cred.get_gid_object()
602 str_cert = obj_gid.save_to_string()
603 cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)
605 user_private_key = account_config['user_private_key'].encode('ascii')
606 pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)
608 p12 = crypto.PKCS12()
609 p12.set_privatekey(pkey)
610 p12.set_certificate(cert)
611 pkcs12 = p12.export()
613 response = HttpResponse(pkcs12, content_type='text/plain')
614 response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
617 elif 'delegated_user_credential' in account_config and 'user_private_key' in account_config:
618 user_cred = account_config['delegated_user_credential']
619 obj_cred = Credential(string=user_cred)
620 obj_gid = obj_cred.get_gid_object()
621 str_cert = obj_gid.save_to_string()
622 cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)
624 user_private_key = account_config['user_private_key'].encode('ascii')
625 pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)
627 p12 = crypto.PKCS12()
628 p12.set_privatekey(pkey)
629 p12.set_certificate(cert)
630 pkcs12 = p12.export()
632 response = HttpResponse(pkcs12, content_type='text/plain')
633 response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
636 messages.error(request, 'Download error: User private key or credential is not stored in the server')
637 return HttpResponseRedirect("/portal/account/")
640 messages.info(request, 'Under Construction. Please try again later!')
641 return HttpResponseRedirect("/portal/account/")