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