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