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",
42 "js/my_account.edit_profile.js","js/jquery-ui.js" ] )
43 page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css" ] )
45 # Execute a Query to delegate credentials if necessary
46 #sfa_user_query = Query().get('myslice:user').select('user_hrn').filter_by('user_hrn','==','$user_hrn')
47 #sfa_user_result = execute_query(self.request, sfa_user_query)
49 user_query = Query().get('local:user').select('config','email','status')
50 user_details = execute_query(self.request, user_query)
52 # not always found in user_details...
54 for user_detail in user_details:
55 # different significations of user_status
56 if user_detail['status'] == 0:
57 user_status = 'Disabled'
58 elif user_detail['status'] == 1:
59 user_status = 'Validation Pending'
60 elif user_detail['status'] == 2:
61 user_status = 'Enabled'
64 #email = user_detail['email']
65 if user_detail['config']:
66 config = json.loads(user_detail['config'])
68 platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
69 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
70 platform_details = execute_query(self.request, platform_query)
71 account_details = execute_query(self.request, account_query)
73 # initial assignment needed for users having account.config = {}
79 account_reference = ''
84 principal_acc_list = ''
86 platform_name_list = []
87 platform_name_secondary_list = []
88 platform_access_list = []
89 platform_no_access_list = []
90 total_platform_list = []
91 account_type_list = []
92 account_type_secondary_list = []
93 account_reference_list = []
94 delegation_type_list = []
95 user_cred_exp_list = []
98 slice_cred_exp_list = []
99 auth_cred_exp_list = []
103 for platform_detail in platform_details:
104 if 'sfa' in platform_detail['gateway_type']:
105 total_platform = platform_detail['platform']
106 total_platform_list.append(total_platform)
108 for account_detail in account_details:
109 if platform_detail['platform_id'] == account_detail['platform_id']:
110 platform_name = platform_detail['platform']
111 if 'config' in account_detail and account_detail['config'] is not '':
112 account_config = json.loads(account_detail['config'])
113 account_usr_hrn = account_config.get('user_hrn','N/A')
114 account_pub_key = account_config.get('user_public_key','N/A')
115 account_reference = account_config.get ('reference_platform','N/A')
116 # credentials of myslice platform
117 if 'myslice' in platform_detail['platform']:
118 acc_user_cred = account_config.get('delegated_user_credential','N/A')
119 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
120 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
122 if 'N/A' not in acc_user_cred:
123 exp_date = re.search('<expires>(.*)</expires>', acc_user_cred)
125 user_exp_date = exp_date.group(1)
126 user_cred_exp_list.append(user_exp_date)
128 my_users = [{'cred_exp': t[0]}
129 for t in zip(user_cred_exp_list)]
132 if 'N/A' not in acc_slice_cred:
133 for key, value in acc_slice_cred.iteritems():
134 slice_list.append(key)
136 exp_date = re.search('<expires>(.*)</expires>', value)
138 exp_date = exp_date.group(1)
139 slice_cred_exp_list.append(exp_date)
141 my_slices = [{'slice_name': t[0], 'cred_exp': t[1]}
142 for t in zip(slice_list, slice_cred_exp_list)]
144 if 'N/A' not in acc_auth_cred:
145 for key, value in acc_auth_cred.iteritems():
146 auth_list.append(key)
148 exp_date = re.search('<expires>(.*)</expires>', value)
150 exp_date = exp_date.group(1)
151 auth_cred_exp_list.append(exp_date)
153 my_auths = [{'auth_name': t[0], 'cred_exp': t[1]}
154 for t in zip(auth_list, auth_cred_exp_list)]
157 # for reference accounts
158 if 'reference' in account_detail['auth_type']:
159 account_type = 'Reference'
161 platform_name_secondary_list.append(platform_name)
162 account_type_secondary_list.append(account_type)
163 account_reference_list.append(account_reference)
164 ref_acc_list = [{'platform_name': t[0], 'account_type': t[1], 'account_reference': t[2]}
165 for t in zip(platform_name_secondary_list, account_type_secondary_list, account_reference_list)]
167 elif 'managed' in account_detail['auth_type']:
168 account_type = 'Principal'
169 delegation = 'Automatic'
171 account_type = 'Principal'
172 delegation = 'Manual'
173 # for principal (auth_type=user/managed) accounts
174 if 'reference' not in account_detail['auth_type']:
175 platform_name_list.append(platform_name)
176 account_type_list.append(account_type)
177 delegation_type_list.append(delegation)
178 usr_hrn_list.append(account_usr_hrn)
179 pub_key_list.append(account_pub_key)
180 user_status_list.append(user_status)
181 # combining 5 lists into 1 [to render in the template]
182 principal_acc_list = [
183 {'platform_name' : pn, 'account_type' : at,
184 'delegation_type' : dt, 'usr_hrn' : uh,
185 'usr_pubkey' : up, 'user_status' : us,}
186 for pn, at, dt, uh, up, us in zip(platform_name_list, account_type_list, delegation_type_list,
187 usr_hrn_list, pub_key_list, user_status_list)
189 # to hide private key row if it doesn't exist
190 if 'myslice' in platform_detail['platform']:
191 account_config = json.loads(account_detail['config'])
192 account_priv_key = account_config.get('user_private_key','N/A')
193 if 'sfa' in platform_detail['gateway_type']:
194 platform_access = platform_detail['platform']
195 platform_access_list.append(platform_access)
197 # Removing the platform which already has access
198 for platform in platform_access_list:
199 total_platform_list.remove(platform)
200 # we could use zip. this one is used if columns have unequal rows
201 platform_list = [{'platform_no_access': t[0]}
202 for t in itertools.izip_longest(total_platform_list)]
205 ## check user is pi or not
206 # platform_query = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
207 # account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
208 # platform_details = execute_query(self.request, platform_query)
209 # account_details = execute_query(self.request, account_query)
210 # for platform_detail in platform_details:
211 # for account_detail in account_details:
212 # if platform_detail['platform_id'] == account_detail['platform_id']:
213 # if 'config' in account_detail and account_detail['config'] is not '':
214 # account_config = json.loads(account_detail['config'])
215 # if 'myslice' in platform_detail['platform']:
216 # acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
218 if acc_auth_cred == {} or acc_auth_cred == 'N/A':
223 # check if the user has creds or not
224 if acc_user_cred == {} or acc_user_cred == 'N/A':
225 user_cred = 'no_creds'
227 exp_date = get_expiration(acc_user_cred, 'timestamp')
228 if exp_date < time.time():
229 user_cred = 'creds_expired'
231 user_cred = 'has_creds'
233 context = super(AccountView, self).get_context_data(**kwargs)
234 context['principal_acc'] = principal_acc_list
235 context['ref_acc'] = ref_acc_list
236 context['platform_list'] = platform_list
237 context['my_users'] = my_users
239 context['user_cred'] = user_cred
240 context['my_slices'] = my_slices
241 context['my_auths'] = my_auths
242 context['user_status'] = user_status
243 context['person'] = self.request.user
244 context['firstname'] = config.get('firstname',"?")
245 context['lastname'] = config.get('lastname',"?")
246 context['fullname'] = context['firstname'] +' '+ context['lastname']
247 context['authority'] = config.get('authority',"Unknown Authority")
248 context['user_private_key'] = account_priv_key
250 # XXX This is repeated in all pages
251 # more general variables expected in the template
252 context['title'] = 'Platforms connected to MySlice'
253 # the menu items on the top
254 context['topmenu_items'] = topmenu_items_live('My Account', page)
255 # so we can sho who is logged
256 context['username'] = the_user(self.request)
257 context['theme'] = self.theme
258 context['section'] = "User account"
259 # context ['firstname'] = config['firstname']
260 prelude_env = page.prelude_env()
261 context.update(prelude_env)
265 def account_process(request):
266 from sfa.trust.credential import Credential
267 from sfa.trust.certificate import Keypair
269 user_query = Query().get('local:user').select('user_id','email','password','config')
270 user_details = execute_query(request, user_query)
272 account_query = Query().get('local:account').select('user_id','platform_id','auth_type','config')
273 account_details = execute_query(request, account_query)
275 platform_query = Query().get('local:platform').select('platform_id','platform')
276 platform_details = execute_query(request, platform_query)
278 # getting the user_id from the session
279 for user_detail in user_details:
280 user_id = user_detail['user_id']
281 user_email = user_detail['email']
283 if user_email == request.user.email:
284 authorize_query = True
286 logger.error("SECURITY: {} tried to update {}".format(user_email, request.user.email))
287 messages.error(request, 'You are not authorized to modify another user.')
288 return HttpResponseRedirect("/portal/account/")
289 except Exception as e:
290 logger.error("exception in account_process {}".format(e))
292 for account_detail in account_details:
293 for platform_detail in platform_details:
294 # Add reference account to the platforms
295 if 'add_'+platform_detail['platform'] in request.POST\
296 or request.POST['button_value'] == 'add_'+platform_detail['platform']:
297 platform_id = platform_detail['platform_id']
298 user_params = {'platform_id': platform_id, 'user_id': user_id,
299 'auth_type': "reference",
300 'config': '{"reference_platform": "myslice"}'}
301 manifold_add_account(request,user_params)
302 messages.info(request, 'Reference Account is added to the selected platform successfully!')
303 return HttpResponseRedirect("/portal/account/")
305 # Delete reference account from the platforms
306 if 'delete_'+platform_detail['platform'] in request.POST\
307 or request.POST['button_value'] == 'delete_'+platform_detail['platform']:
308 platform_id = platform_detail['platform_id']
309 user_params = {'user_id':user_id}
310 manifold_delete_account(request,platform_id, user_id, user_params)
311 messages.info(request, 'Reference Account is removed from the selected platform')
312 return HttpResponseRedirect("/portal/account/")
314 if platform_detail['platform_id'] == account_detail['platform_id']:
315 if 'myslice' in platform_detail['platform']:
316 account_config = json.loads(account_detail['config'])
317 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
318 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
323 # adding the slices and corresponding credentials to list
324 if 'N/A' not in acc_slice_cred:
327 for key, value in acc_slice_cred.iteritems():
328 slice_list.append(key)
329 slice_cred.append(value)
330 # special case: download each slice credentials separately
331 for i in range(0, len(slice_list)):
332 if 'dl_'+slice_list[i] in request.POST or request.POST['button_value'] == 'dl_'+slice_list[i]:
333 slice_detail = "Slice name: " + slice_list[i] +"\nSlice Credentials: \n"+ slice_cred[i]
334 response = HttpResponse(slice_detail, content_type='text/plain')
335 response['Content-Disposition'] = 'attachment; filename="slice_credential.txt"'
338 # adding the authority and corresponding credentials to list
339 if 'N/A' not in acc_auth_cred:
342 for key, value in acc_auth_cred.iteritems():
343 auth_list.append(key)
344 auth_cred.append(value)
345 # special case: download each slice credentials separately
346 for i in range(0, len(auth_list)):
347 if 'dl_'+auth_list[i] in request.POST or request.POST['button_value'] == 'dl_'+auth_list[i]:
348 auth_detail = "Authority: " + auth_list[i] +"\nAuthority Credentials: \n"+ auth_cred[i]
349 response = HttpResponse(auth_detail, content_type='text/plain')
350 response['Content-Disposition'] = 'attachment; filename="auth_credential.txt"'
353 account_detail = get_myslice_account(request)
355 if 'submit_name' in request.POST:
356 edited_first_name = request.POST['fname']
357 edited_last_name = request.POST['lname']
360 for user_config in user_details:
361 if user_config['config']:
362 config = json.loads(user_config['config'])
363 config['firstname'] = edited_first_name
364 config['lastname'] = edited_last_name
365 config['authority'] = config.get('authority','Unknown Authority')
366 updated_config = json.dumps(config)
367 user_params = {'config': updated_config}
368 else: # it's needed if the config is empty
369 user_config['config'] = '{{"firstname":"{}", "lastname":"{}", "authority": "Unknown Authority"}}'\
370 .format(edited_first_name, edited_last_name)
371 user_params = {'config': user_config['config']}
372 # updating config local:user in manifold
373 manifold_update_user(request, request.user.email,user_params)
374 # this will be depricated, we will show the success msg in same page
375 # Redirect to same page with success message
376 messages.success(request, 'Sucess: First Name and Last Name Updated.')
377 return HttpResponseRedirect("/portal/account/")
379 elif 'submit_pass' in request.POST:
380 edited_password = request.POST['password']
382 for user_pass in user_details:
383 user_pass['password'] = edited_password
384 #updating password in local:user
385 user_params = { 'password' : user_pass['password']}
386 manifold_update_user(request, request.user.email, user_params)
387 # return HttpResponse('Success: Password Changed!!')
388 messages.success(request, 'Success: Password Updated.')
389 return HttpResponseRedirect("/portal/account/")
391 # XXX TODO: Factorize with portal/registrationview.py
392 # XXX TODO: Factorize with portal/registrationview.py
393 # XXX TODO: Factorize with portal/joinview.py
395 elif 'generate' in request.POST:
397 private = RSA.generate(1024)
398 private_key = json.dumps(private.exportKey())
399 public = private.publickey()
400 public_key = json.dumps(public.exportKey(format='OpenSSH'))
401 # updating manifold local:account table
402 account_config = json.loads(account_detail['config'])
403 # preserving user_hrn
404 user_hrn = account_config.get('user_hrn','N/A')
405 keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
406 #updated_config = json.dumps(account_config)
408 #user_params = { 'config': keypair, 'auth_type':'managed'}
409 #manifold_update_account(request, user_id, user_params)
411 public_key = public_key.replace('"', '');
412 user_pub_key = {'keys': public_key}
414 sfa_update_user(request, user_hrn, user_pub_key)
415 result_sfa_user = sfa_get_user(request, user_hrn, public_key)
417 if 'keys' in result_sfa_user and result_sfa_user['keys'][0] == public_key:
419 updated_config = json.dumps(account_config)
420 user_params = { 'config': keypair, 'auth_type':'managed'}
421 manifold_update_account(request, user_id, user_params)
422 messages.success(request, 'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.')
424 raise Exception,"Keys are not matching"
425 except Exception as e:
426 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.')
427 logger.error("Exception in accountview {}".format(e))
428 return HttpResponseRedirect("/portal/account/")
429 except Exception as e:
430 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
431 return HttpResponseRedirect("/portal/account/")
433 elif 'upload_key' in request.POST:
435 up_file = request.FILES['pubkey']
436 file_content = up_file.read()
437 file_name = up_file.name
438 file_extension = os.path.splitext(file_name)[1]
439 allowed_extension = ['.pub','.txt']
440 if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
441 account_config = json.loads(account_detail['config'])
442 # preserving user_hrn
443 user_hrn = account_config.get('user_hrn','N/A')
444 file_content = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
445 #file_content = re.sub("\r", "", file_content)
446 #file_content = re.sub("\n", "\\n",file_content)
447 file_content = ''.join(file_content.split())
448 #update manifold local:account table
449 user_params = { 'config': file_content, 'auth_type':'user'}
450 manifold_update_account(request, user_id, user_params)
452 user_pub_key = {'keys': file_content}
453 sfa_update_user(request, user_hrn, user_pub_key)
454 messages.success(request, 'Publickey uploaded! Please delegate your credentials using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
455 return HttpResponseRedirect("/portal/account/")
457 messages.error(request, 'RSA key error: Please upload a valid RSA public key [.txt or .pub].')
458 return HttpResponseRedirect("/portal/account/")
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_pubkey' in request.POST or request.POST['button_value'] == 'dl_pubkey':
466 account_config = json.loads(account_detail['config'])
467 public_key = account_config['user_public_key']
468 response = HttpResponse(public_key, content_type='text/plain')
469 response['Content-Disposition'] = 'attachment; filename="pubkey.txt"'
471 except Exception as e:
472 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
473 return HttpResponseRedirect("/portal/account/")
475 elif 'dl_pkey' in request.POST or request.POST['button_value'] == 'dl_pkey':
477 account_config = json.loads(account_detail['config'])
478 if 'user_private_key' in account_config:
479 private_key = account_config['user_private_key']
480 response = HttpResponse(private_key, content_type='text/plain')
481 response['Content-Disposition'] = 'attachment; filename="privkey.txt"'
484 messages.error(request, 'Download error: Private key is not stored in the server')
485 return HttpResponseRedirect("/portal/account/")
487 except Exception as e:
488 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
489 return HttpResponseRedirect("/portal/account/")
491 elif 'delete' in request.POST or request.POST['button_value'] == 'delete':
493 account_config = json.loads(account_detail['config'])
494 if 'user_private_key' in account_config:
495 for key in account_config.keys():
496 if key == 'user_private_key':
497 del account_config[key]
499 updated_config = json.dumps(account_config)
500 user_params = { 'config': updated_config, 'auth_type':'user'}
501 manifold_update_account(request, user_id, user_params)
502 messages.success(request, 'Private Key deleted. You need to delegate credentials manually once it expires.')
503 messages.success(request, 'Once your credentials expire, Please delegate manually using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
504 return HttpResponseRedirect("/portal/account/")
506 messages.error(request, 'Delete error: Private key is not stored in the server')
507 return HttpResponseRedirect("/portal/account/")
509 except Exception as e:
510 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
511 return HttpResponseRedirect("/portal/account/")
513 # download identity for jfed
514 elif 'dl_identity' in request.POST or request.POST['button_value'] == 'dl_identity':
516 jfed_identity = get_jfed_identity(request)
517 if jfed_identity is not None:
518 response = HttpResponse(jfed_identity, content_type='text/plain')
519 response['Content-Disposition'] = 'attachment; filename="jfed_identity.txt"'
522 messages.error(request, 'Download error: Private key is not stored in the server')
523 return HttpResponseRedirect("/portal/account/")
525 except Exception as e:
526 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
527 return HttpResponseRedirect("/portal/account/")
529 # Download sfi_config
530 elif 'dl_sfi_config' in request.POST or request.POST['button_value'] == 'dl_sfi_config':
531 platform_detail = get_myslice_platform(request)
532 platform_config = json.loads(platform_detail['config'])
533 account_detail = get_myslice_account(request)
534 account_config = json.loads(account_detail['config'])
536 user_hrn = account_config.get('user_hrn','N/A')
537 t_user_hrn = user_hrn.split('.')
538 authority_hrn = t_user_hrn[0] + '.' + t_user_hrn[1]
539 registry = get_registry_url(request)
541 hostname = socket.gethostbyaddr(socket.gethostname())[0]
542 admin_user = platform_config.get('user','N/A')
543 manifold_host = ConfigEngine().manifold_url()
544 if 'localhost' in manifold_host:
545 manifold_host = manifold_host.replace('localhost',hostname)
546 sfi_config = '[sfi]\n'
547 sfi_config += 'auth = '+ authority_hrn +'\n'
548 sfi_config += 'user = '+ user_hrn +'\n'
549 sfi_config += 'registry = '+ registry +'\n'
550 sfi_config += 'sm = http://sfa3.planet-lab.eu:12346/\n\n'
551 sfi_config += '[myslice]\n'
552 sfi_config += 'backend = '+ manifold_host +'\n'
553 sfi_config += 'delegate = '+ admin_user +'\n'
554 sfi_config += 'platform = myslice\n'
555 sfi_config += 'username = '+ user_email +'\n'
556 response = HttpResponse(sfi_config, content_type='text/plain')
557 response['Content-Disposition'] = 'attachment; filename="sfi_config"'
561 elif 'clear_cred' in request.POST or request.POST['button_value'] == 'clear_cred':
563 result = clear_user_creds(request, user_email)
564 if result is not None:
565 messages.success(request, 'All Credentials cleared')
567 messages.error(request, 'Delete error: Credentials are not stored in the server')
568 except Exception as e:
569 logger.error("Exception in accountview.py in clear_user_creds {}".format(e))
570 messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
571 return HttpResponseRedirect("/portal/account/")
573 # Download delegated_user_cred
574 elif 'dl_user_cred' in request.POST or request.POST['button_value'] == 'dl_user_cred':
575 if 'delegated_user_credential' in account_config:
576 user_cred = account_config['delegated_user_credential']
577 response = HttpResponse(user_cred, content_type='text/plain')
578 response['Content-Disposition'] = 'attachment; filename="user_cred.txt"'
581 messages.error(request, 'Download error: User credential is not stored in the server')
582 return HttpResponseRedirect("/portal/account/")
585 elif 'dl_user_cert' in request.POST or request.POST['button_value'] == 'dl_user_cert':
586 if 'user_credential' in account_config:
587 user_cred = account_config['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 response = HttpResponse(str_cert, content_type='text/plain')
592 response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
595 elif 'delegated_user_credential' in account_config:
596 user_cred = account_config['delegated_user_credential']
597 obj_cred = Credential(string=user_cred)
598 obj_gid = obj_cred.get_gid_object()
599 str_cert = obj_gid.save_to_string()
600 response = HttpResponse(str_cert, content_type='text/plain')
601 response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
604 messages.error(request, 'Download error: User credential is not stored in the server')
605 return HttpResponseRedirect("/portal/account/")
607 # Download user p12 = private_key + Certificate
608 elif 'dl_user_p12' in request.POST or request.POST['button_value'] == 'dl_user_p12':
609 if 'user_credential' in account_config and 'user_private_key' in account_config:
610 user_cred = account_config['user_credential']
611 obj_cred = Credential(string=user_cred)
612 obj_gid = obj_cred.get_gid_object()
613 str_cert = obj_gid.save_to_string()
614 cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)
616 user_private_key = account_config['user_private_key'].encode('ascii')
617 pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)
619 p12 = crypto.PKCS12()
620 p12.set_privatekey(pkey)
621 p12.set_certificate(cert)
622 pkcs12 = p12.export()
624 response = HttpResponse(pkcs12, content_type='text/plain')
625 response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
628 elif 'delegated_user_credential' in account_config and 'user_private_key' in account_config:
629 user_cred = account_config['delegated_user_credential']
630 obj_cred = Credential(string=user_cred)
631 obj_gid = obj_cred.get_gid_object()
632 str_cert = obj_gid.save_to_string()
633 cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)
635 user_private_key = account_config['user_private_key'].encode('ascii')
636 pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)
638 p12 = crypto.PKCS12()
639 p12.set_privatekey(pkey)
640 p12.set_certificate(cert)
641 pkcs12 = p12.export()
643 response = HttpResponse(pkcs12, content_type='text/plain')
644 response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
647 messages.error(request, 'Download error: User private key or credential is not stored in the server')
648 return HttpResponseRedirect("/portal/account/")
651 messages.info(request, 'Under Construction. Please try again later!')
652 return HttpResponseRedirect("/portal/account/")