Activate user email footer updated
[unfold.git] / portal / accountview.py
1 #
2 import json, os, re, itertools, time
3 from OpenSSL import crypto
4 from Crypto.PublicKey import RSA
5
6 #
7 from django.http                        import HttpResponse, HttpResponseRedirect
8 from django.contrib                     import messages
9 from django.contrib.auth.decorators     import login_required
10
11 #
12 from manifold.core.query                import Query
13 from manifoldapi.manifoldapi            import execute_query
14
15 from unfold.loginrequired               import LoginRequiredAutoLogoutView
16 from unfold.page                        import Page    
17 from ui.topmenu                         import topmenu_items_live, the_user
18
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
23
24 from myslice.settings                   import logger
25 from myslice.configengine               import ConfigEngine
26 from myslice.theme                      import ThemeView
27
28 # requires login
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)
33
34
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()
40
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" ] )
44
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)
48
49         user_query  = Query().get('local:user').select('config','email','status')
50         user_details = execute_query(self.request, user_query)
51         
52         # not always found in user_details...
53         config={}
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'
62             else:
63                 user_status = 'N/A'
64             #email = user_detail['email']
65             if user_detail['config']:
66                 config = json.loads(user_detail['config'])
67
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)
72        
73         # initial assignment needed for users having account.config = {} 
74         platform_name = ''
75         account_type = ''
76         account_usr_hrn = ''
77         account_pub_key = ''
78         account_priv_key = ''
79         account_reference = ''
80         my_users = ''
81         my_slices = ''
82         my_auths = ''
83         ref_acc_list = ''
84         principal_acc_list = ''
85         user_status_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 = []
96         slice_list = []
97         auth_list = []
98         slice_cred_exp_list = []
99         auth_cred_exp_list = []
100         usr_hrn_list = []
101         pub_key_list = []
102           
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)
107                 
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')
121
122                         if 'N/A' not in acc_user_cred:
123                             exp_date = re.search('<expires>(.*)</expires>', acc_user_cred)
124                             if exp_date:
125                                 user_exp_date = exp_date.group(1)
126                                 user_cred_exp_list.append(user_exp_date)
127
128                             my_users = [{'cred_exp': t[0]}
129                                 for t in zip(user_cred_exp_list)]
130                        
131
132                         if 'N/A' not in acc_slice_cred:
133                             for key, value in acc_slice_cred.iteritems():
134                                 slice_list.append(key)
135                                 # get cred_exp date
136                                 exp_date = re.search('<expires>(.*)</expires>', value)
137                                 if exp_date:
138                                     exp_date = exp_date.group(1)
139                                     slice_cred_exp_list.append(exp_date)
140
141                             my_slices = [{'slice_name': t[0], 'cred_exp': t[1]}
142                                 for t in zip(slice_list, slice_cred_exp_list)]
143
144                         if 'N/A' not in acc_auth_cred:
145                             for key, value in acc_auth_cred.iteritems():
146                                 auth_list.append(key)
147                                 #get cred_exp date
148                                 exp_date = re.search('<expires>(.*)</expires>', value)
149                                 if exp_date:
150                                     exp_date = exp_date.group(1)
151                                     auth_cred_exp_list.append(exp_date)
152
153                             my_auths = [{'auth_name': t[0], 'cred_exp': t[1]}
154                                 for t in zip(auth_list, auth_cred_exp_list)]
155
156
157                     # for reference accounts
158                     if 'reference' in account_detail['auth_type']:
159                         account_type = 'Reference'
160                         delegation = 'N/A'
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)]
166                        
167                     elif 'managed' in account_detail['auth_type']:
168                         account_type = 'Principal'
169                         delegation = 'Automatic'
170                     else:
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)
188                         ]
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)
196        
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)]
203
204         # check if the user has creds or not
205         if acc_user_cred == {} or acc_user_cred == 'N/A':
206             user_cred = 'no_creds'
207         else:
208             exp_date = get_expiration(acc_user_cred, 'timestamp')
209             if exp_date < time.time():
210                 user_cred = 'creds_expired'
211             else:
212                 user_cred = 'has_creds'
213
214         context = super(AccountView, self).get_context_data(**kwargs)
215         context['principal_acc'] = principal_acc_list
216         context['ref_acc'] = ref_acc_list
217         context['platform_list'] = platform_list
218         context['my_users'] = my_users
219         context['user_cred'] = user_cred
220         context['my_slices'] = my_slices
221         context['my_auths'] = my_auths
222         context['user_status'] = user_status
223         context['person']   = self.request.user
224         context['firstname'] = config.get('firstname',"?")
225         context['lastname'] = config.get('lastname',"?")
226         context['fullname'] = context['firstname'] +' '+ context['lastname']
227         context['authority'] = config.get('authority',"Unknown Authority")
228         context['user_private_key'] = account_priv_key
229         
230         # XXX This is repeated in all pages
231         # more general variables expected in the template
232         context['title'] = 'Platforms connected to MySlice'
233         # the menu items on the top
234         context['topmenu_items'] = topmenu_items_live('My Account', page)
235         # so we can sho who is logged
236         context['username'] = the_user(self.request)
237         context['theme'] = self.theme
238         context['section'] = "User account"
239 #        context ['firstname'] = config['firstname']
240
241         context['request'] = self.request
242
243         prelude_env = page.prelude_env()
244         context.update(prelude_env)
245         return context
246
247 @login_required
248 def account_process(request):
249     from sfa.trust.credential               import Credential
250     from sfa.trust.certificate              import Keypair
251
252     user_query  = Query().get('local:user').select('user_id','email','password','config')
253     user_details = execute_query(request, user_query)
254     
255     account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
256     account_details = execute_query(request, account_query)
257
258     platform_query  = Query().get('local:platform').select('platform_id','platform')
259     platform_details = execute_query(request, platform_query)
260     
261     # getting the user_id from the session                                            
262     for user_detail in user_details:                                                  
263         user_id = user_detail['user_id']                                              
264         user_email = user_detail['email']                                             
265         try:
266             if user_email == request.user.email:                                          
267                 authorize_query = True                                                    
268             else:                                                                         
269                 logger.error("SECURITY: {} tried to update {}".format(user_email, request.user.email))
270                 messages.error(request, 'You are not authorized to modify another user.') 
271                 return HttpResponseRedirect("/portal/account/")                               
272         except Exception as e:
273             logger.error("exception in account_process {}".format(e))
274
275     for account_detail in account_details:
276         for platform_detail in platform_details:
277             # Add reference account to the platforms
278             if 'add_'+platform_detail['platform'] in request.POST\
279                or request.POST['button_value'] == 'add_'+platform_detail['platform']:
280                 platform_id = platform_detail['platform_id']
281                 user_params = {'platform_id': platform_id, 'user_id': user_id,
282                                'auth_type': "reference",
283                                'config': '{"reference_platform": "myslice"}'}
284                 manifold_add_account(request,user_params)
285                 messages.info(request, 'Reference Account is added to the selected platform successfully!')
286                 return HttpResponseRedirect("/portal/account/")
287
288             # Delete reference account from the platforms
289             if 'delete_'+platform_detail['platform'] in request.POST\
290                or request.POST['button_value'] == 'delete_'+platform_detail['platform']:
291                 platform_id = platform_detail['platform_id']
292                 user_params = {'user_id':user_id}
293                 manifold_delete_account(request,platform_id, user_id, user_params)
294                 messages.info(request, 'Reference Account is removed from the selected platform')
295                 return HttpResponseRedirect("/portal/account/")
296
297             if platform_detail['platform_id'] == account_detail['platform_id']:
298                 if 'myslice' in platform_detail['platform']:
299                     account_config = json.loads(account_detail['config'])
300                     acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
301                     acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
302                 
303
304                     
305     
306     # adding the slices and corresponding credentials to list
307     if 'N/A' not in acc_slice_cred:
308         slice_list = []
309         slice_cred = [] 
310         for key, value in acc_slice_cred.iteritems():
311             slice_list.append(key)       
312             slice_cred.append(value)
313         # special case: download each slice credentials separately 
314         for i in range(0, len(slice_list)):
315             if 'dl_'+slice_list[i] in request.POST or request.POST['button_value'] == 'dl_'+slice_list[i]:
316                 slice_detail = "Slice name: " + slice_list[i] +"\nSlice Credentials: \n"+ slice_cred[i]
317                 response = HttpResponse(slice_detail, content_type='text/plain')
318                 response['Content-Disposition'] = 'attachment; filename="slice_credential.txt"'
319                 return response
320
321     # adding the authority and corresponding credentials to list
322     if 'N/A' not in acc_auth_cred:
323         auth_list = []
324         auth_cred = [] 
325         for key, value in acc_auth_cred.iteritems():
326             auth_list.append(key)       
327             auth_cred.append(value)
328         # special case: download each slice credentials separately
329         for i in range(0, len(auth_list)):
330             if 'dl_'+auth_list[i] in request.POST or request.POST['button_value'] == 'dl_'+auth_list[i]:
331                 auth_detail = "Authority: " + auth_list[i] +"\nAuthority Credentials: \n"+ auth_cred[i]
332                 response = HttpResponse(auth_detail, content_type='text/plain')
333                 response['Content-Disposition'] = 'attachment; filename="auth_credential.txt"'
334                 return response
335
336     account_detail = get_myslice_account(request)
337              
338     if 'submit_name' in request.POST:
339         edited_first_name =  request.POST['fname']
340         edited_last_name =  request.POST['lname']
341         
342         config={}
343         for user_config in user_details:
344             if user_config['config']:
345                 config = json.loads(user_config['config'])
346                 config['firstname'] = edited_first_name
347                 config['lastname'] = edited_last_name
348                 config['authority'] = config.get('authority','Unknown Authority')
349                 updated_config = json.dumps(config)
350                 user_params = {'config': updated_config}
351             else: # it's needed if the config is empty 
352                 user_config['config'] = '{{"firstname":"{}", "lastname":"{}", "authority": "Unknown Authority"}}'\
353                                         .format(edited_first_name, edited_last_name)
354                 user_params = {'config': user_config['config']} 
355         # updating config local:user in manifold       
356         manifold_update_user(request, request.user.email,user_params)
357         # this will be depricated, we will show the success msg in same page
358         # Redirect to same page with success message
359         messages.success(request, 'Sucess: First Name and Last Name Updated.')
360         return HttpResponseRedirect("/portal/account/")       
361     
362     elif 'submit_pass' in request.POST:
363         edited_password = request.POST['password']
364         
365         for user_pass in user_details:
366             user_pass['password'] = edited_password
367         #updating password in local:user
368         user_params = { 'password' : user_pass['password']}
369         manifold_update_user(request, request.user.email, user_params)
370 #        return HttpResponse('Success: Password Changed!!')
371         messages.success(request, 'Success: Password Updated.')
372         return HttpResponseRedirect("/portal/account/")
373
374 # XXX TODO: Factorize with portal/registrationview.py
375 # XXX TODO: Factorize with portal/registrationview.py
376 # XXX TODO: Factorize with portal/joinview.py
377
378     elif 'generate' in request.POST:
379         try:
380             private = RSA.generate(1024)
381             private_key = json.dumps(private.exportKey())
382             public  = private.publickey()
383             public_key = json.dumps(public.exportKey(format='OpenSSH'))
384             # updating manifold local:account table
385             account_config = json.loads(account_detail['config'])
386             # preserving user_hrn
387             user_hrn = account_config.get('user_hrn','N/A')
388             keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
389             #updated_config = json.dumps(account_config) 
390             # updating manifold
391             #user_params = { 'config': keypair, 'auth_type':'managed'}
392             #manifold_update_account(request, user_id, user_params)
393             # updating sfa
394             public_key = public_key.replace('"', '');
395             user_pub_key = {'keys': public_key}
396
397             sfa_update_user(request, user_hrn, user_pub_key)
398             result_sfa_user = sfa_get_user(request, user_hrn, public_key)
399             try:
400                 if 'keys' in result_sfa_user and result_sfa_user['keys'][0] == public_key:
401                     # updating manifold
402                     updated_config = json.dumps(account_config) 
403                     user_params = { 'config': keypair, 'auth_type':'managed'}
404                     manifold_update_account(request, user_id, user_params)
405                     messages.success(request, 'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.')
406                 else:
407                     raise Exception,"Keys are not matching"
408             except Exception as e:
409                 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.')
410                 logger.error("Exception in accountview {}".format(e))
411             return HttpResponseRedirect("/portal/account/")
412         except Exception as e:
413             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
414             return HttpResponseRedirect("/portal/account/")
415                        
416     elif 'upload_key' in request.POST:
417         try:
418             up_file = request.FILES['pubkey']
419             file_content =  up_file.read()
420             file_name = up_file.name
421             file_extension = os.path.splitext(file_name)[1] 
422             allowed_extension =  ['.pub','.txt']
423             if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
424                 account_config = json.loads(account_detail['config'])
425                 # preserving user_hrn
426                 user_hrn = account_config.get('user_hrn','N/A')
427                 file_content = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
428                 #file_content = re.sub("\r", "", file_content)
429                 #file_content = re.sub("\n", "\\n",file_content)
430                 file_content = ''.join(file_content.split())
431                 #update manifold local:account table
432                 user_params = { 'config': file_content, 'auth_type':'user'}
433                 manifold_update_account(request, user_id, user_params)
434                 # updating sfa
435                 user_pub_key = {'keys': file_content}
436                 sfa_update_user(request, user_hrn, user_pub_key)
437                 messages.success(request, 'Publickey uploaded! Please delegate your credentials using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
438                 return HttpResponseRedirect("/portal/account/")
439             else:
440                 messages.error(request, 'RSA key error: Please upload a valid RSA public key [.txt or .pub].')
441                 return HttpResponseRedirect("/portal/account/")
442
443         except Exception as e:
444             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
445             return HttpResponseRedirect("/portal/account/")
446
447     elif 'dl_pubkey' in request.POST or request.POST['button_value'] == 'dl_pubkey':
448         try:
449             account_config = json.loads(account_detail['config'])
450             public_key = account_config['user_public_key'] 
451             response = HttpResponse(public_key, content_type='text/plain')
452             response['Content-Disposition'] = 'attachment; filename="pubkey.txt"'
453             return response
454         except Exception as e:
455             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
456             return HttpResponseRedirect("/portal/account/")
457                
458     elif 'dl_pkey' in request.POST or request.POST['button_value'] == 'dl_pkey':
459         try:
460             account_config = json.loads(account_detail['config'])
461             if 'user_private_key' in account_config:
462                 private_key = account_config['user_private_key']
463                 response = HttpResponse(private_key, content_type='text/plain')
464                 response['Content-Disposition'] = 'attachment; filename="privkey.txt"'
465                 return response
466             else:
467                 messages.error(request, 'Download error: Private key is not stored in the server')
468                 return HttpResponseRedirect("/portal/account/")
469
470         except Exception as e:
471             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
472             return HttpResponseRedirect("/portal/account/")
473     
474     elif 'delete' in request.POST or request.POST['button_value'] == 'delete':
475         try:
476             account_config = json.loads(account_detail['config'])
477             if 'user_private_key' in account_config:
478                 for key in account_config.keys():
479                     if key == 'user_private_key':    
480                         del account_config[key]
481                     
482                 updated_config = json.dumps(account_config)
483                 user_params = { 'config': updated_config, 'auth_type':'user'}
484                 manifold_update_account(request, user_id, user_params)
485                 messages.success(request, 'Private Key deleted. You need to delegate credentials manually once it expires.')
486                 messages.success(request, 'Once your credentials expire, Please delegate manually using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
487                 return HttpResponseRedirect("/portal/account/")
488             else:
489                 messages.error(request, 'Delete error: Private key is not stored in the server')
490                 return HttpResponseRedirect("/portal/account/")
491                           
492         except Exception as e:
493             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')    
494             return HttpResponseRedirect("/portal/account/")
495     
496     # download identity for jfed
497     elif 'dl_identity' in request.POST or request.POST['button_value'] == 'dl_identity':
498         try:
499             jfed_identity = get_jfed_identity(request)
500             if jfed_identity is not None:
501                 response = HttpResponse(jfed_identity, content_type='text/plain')
502                 response['Content-Disposition'] = 'attachment; filename="jfed_identity.txt"'
503                 return response
504             else:
505                 messages.error(request, 'Download error: Private key is not stored in the server')
506                 return HttpResponseRedirect("/portal/account/")
507
508         except Exception as e:
509             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
510             return HttpResponseRedirect("/portal/account/")
511
512     # Download sfi_config
513     elif 'dl_sfi_config' in request.POST or request.POST['button_value'] == 'dl_sfi_config':
514         platform_detail = get_myslice_platform(request)
515         platform_config = json.loads(platform_detail['config'])
516         account_detail = get_myslice_account(request)
517         account_config = json.loads(account_detail['config'])
518
519         user_hrn = account_config.get('user_hrn','N/A')
520         t_user_hrn = user_hrn.split('.')
521         authority_hrn = t_user_hrn[0] + '.' + t_user_hrn[1]
522         registry = get_registry_url(request)
523         import socket
524         hostname = socket.gethostbyaddr(socket.gethostname())[0]
525         admin_user = platform_config.get('user','N/A')
526         manifold_host = ConfigEngine().manifold_url()
527         if 'localhost' in manifold_host:
528             manifold_host = manifold_host.replace('localhost',hostname)
529         sfi_config  = '[sfi]\n'
530         sfi_config += 'auth = '+ authority_hrn +'\n'
531         sfi_config += 'user = '+ user_hrn +'\n'
532         sfi_config += 'registry = '+ registry +'\n'
533         sfi_config += 'sm = http://sfa3.planet-lab.eu:12346/\n\n'
534         sfi_config += '[myslice]\n'
535         sfi_config += 'backend = '+ manifold_host +'\n'
536         sfi_config += 'delegate  = '+ admin_user +'\n'
537         sfi_config += 'platform  = myslice\n'
538         sfi_config += 'username  = '+ user_email +'\n'
539         response = HttpResponse(sfi_config, content_type='text/plain')
540         response['Content-Disposition'] = 'attachment; filename="sfi_config"'
541         return response
542
543     #clear all creds
544     elif 'clear_cred' in request.POST or request.POST['button_value'] == 'clear_cred':
545         try:
546             result = clear_user_creds(request, user_email)
547             if result is not None: 
548                 messages.success(request, 'All Credentials cleared')
549             else:
550                 messages.error(request, 'Delete error: Credentials are not stored in the server')
551         except Exception as e:
552             logger.error("Exception in accountview.py in clear_user_creds {}".format(e))
553             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
554         return HttpResponseRedirect("/portal/account/")
555
556     # Download delegated_user_cred
557     elif 'dl_user_cred' in request.POST or request.POST['button_value'] == 'dl_user_cred':
558         if 'delegated_user_credential' in account_config:
559             user_cred = account_config['delegated_user_credential']
560             response = HttpResponse(user_cred, content_type='text/plain')
561             response['Content-Disposition'] = 'attachment; filename="user_cred.txt"'
562             return response
563         else:
564             messages.error(request, 'Download error: User credential is not stored in the server')
565             return HttpResponseRedirect("/portal/account/")
566
567     # Download user_cert
568     elif 'dl_user_cert' in request.POST or request.POST['button_value'] == 'dl_user_cert':
569         if 'user_credential' in account_config:
570             user_cred = account_config['user_credential']
571             obj_cred = Credential(string=user_cred)
572             obj_gid = obj_cred.get_gid_object()
573             str_cert = obj_gid.save_to_string()
574             response = HttpResponse(str_cert, content_type='text/plain')
575             response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
576             return response
577
578         elif 'delegated_user_credential' in account_config:
579             user_cred = account_config['delegated_user_credential']
580             obj_cred = Credential(string=user_cred)
581             obj_gid = obj_cred.get_gid_object()
582             str_cert = obj_gid.save_to_string()
583             response = HttpResponse(str_cert, content_type='text/plain')
584             response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
585             return response
586         else:
587             messages.error(request, 'Download error: User credential is not stored in the server')
588             return HttpResponseRedirect("/portal/account/")
589
590     # Download user p12 = private_key + Certificate
591     elif 'dl_user_p12' in request.POST or request.POST['button_value'] == 'dl_user_p12':
592         if 'user_credential' in account_config and 'user_private_key' in account_config:
593             user_cred = account_config['user_credential']
594             obj_cred = Credential(string=user_cred)
595             obj_gid = obj_cred.get_gid_object()
596             str_cert = obj_gid.save_to_string()
597             cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)
598
599             user_private_key = account_config['user_private_key'].encode('ascii')
600             pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)
601
602             p12 = crypto.PKCS12()
603             p12.set_privatekey(pkey)
604             p12.set_certificate(cert)       
605             pkcs12 = p12.export()
606
607             response = HttpResponse(pkcs12, content_type='text/plain')
608             response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
609             return response
610
611         elif 'delegated_user_credential' in account_config and 'user_private_key' in account_config:
612             user_cred = account_config['delegated_user_credential']
613             obj_cred = Credential(string=user_cred)
614             obj_gid = obj_cred.get_gid_object()
615             str_cert = obj_gid.save_to_string()
616             cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)
617
618             user_private_key = account_config['user_private_key'].encode('ascii')
619             pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)
620
621             p12 = crypto.PKCS12()
622             p12.set_privatekey(pkey)
623             p12.set_certificate(cert)       
624             pkcs12 = p12.export()
625
626             response = HttpResponse(pkcs12, content_type='text/plain')
627             response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
628             return response
629         else:
630             messages.error(request, 'Download error: User private key or credential is not stored in the server')
631             return HttpResponseRedirect("/portal/account/")
632
633     else:
634         messages.info(request, 'Under Construction. Please try again later!')
635         return HttpResponseRedirect("/portal/account/")
636
637