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