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