suggestions for nicer layout in a handful portal modules
[unfold.git] / portal / accountview.py
1 #
2 import json, os, re, itertools, time
3 from OpenSSL import crypto
4 from Crypto.PublicKey import RSA
5
6 #
7 from django.http                        import HttpResponse, HttpResponseRedirect
8 from django.contrib                     import messages
9 from django.contrib.auth.decorators     import login_required
10
11 #
12 from manifold.core.query                import Query
13 from manifoldapi.manifoldapi            import execute_query
14
15 from unfold.loginrequired               import LoginRequiredAutoLogoutView
16 from unfold.page                        import Page    
17 from ui.topmenu                         import topmenu_items_live, the_user
18
19 from portal.actions                     import (
20     manifold_update_user, manifold_update_account, manifold_add_account,
21     manifold_delete_account, sfa_update_user, sfa_get_user, clear_user_creds )
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 get_myslice_platform(request):
266     platform_query  = Query().get('local:platform')\
267                              .select('platform_id','platform','gateway_type','disabled','config')\
268                              .filter_by('platform','==','myslice')
269     platform_details = execute_query(request, platform_query)
270     for platform_detail in platform_details:
271         return platform_detail
272
273 @login_required
274 def get_myslice_account(request):
275     platform_myslice = get_myslice_platform(request)
276     account_query  = Query().get('local:account')\
277                             .select('user_id','platform_id','auth_type','config')\
278                             .filter_by('platform_id','==',platform_myslice['platform_id'])
279     account_details = execute_query(request, account_query)
280     for account_detail in account_details:
281         return account_detail
282
283 @login_required
284 #my_acc form value processing
285 def account_process(request):
286     from sfa.trust.credential               import Credential
287     from sfa.trust.certificate              import Keypair
288
289     user_query  = Query().get('local:user').select('user_id','email','password','config')
290     user_details = execute_query(request, user_query)
291     
292     account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
293     account_details = execute_query(request, account_query)
294
295     platform_query  = Query().get('local:platform').select('platform_id','platform')
296     platform_details = execute_query(request, platform_query)
297     
298     # getting the user_id from the session                                            
299     for user_detail in user_details:                                                  
300         user_id = user_detail['user_id']                                              
301         user_email = user_detail['email']                                             
302         try:
303             if user_email == request.user.email:                                          
304                 authorize_query = True                                                    
305             else:                                                                         
306                 logger.error("SECURITY: {} tried to update {}".format(user_email, request.user.email))
307                 messages.error(request, 'You are not authorized to modify another user.') 
308                 return HttpResponseRedirect("/portal/account/")                               
309         except Exception as e:
310             logger.error("exception in account_process {}".format(e))
311
312     for account_detail in account_details:
313         for platform_detail in platform_details:
314             # Add reference account to the platforms
315             if 'add_'+platform_detail['platform'] in request.POST\
316                or request.POST['button_value'] == 'add_'+platform_detail['platform']:
317                 platform_id = platform_detail['platform_id']
318                 user_params = {'platform_id': platform_id, 'user_id': user_id,
319                                'auth_type': "reference",
320                                'config': '{"reference_platform": "myslice"}'}
321                 manifold_add_account(request,user_params)
322                 messages.info(request, 'Reference Account is added to the selected platform successfully!')
323                 return HttpResponseRedirect("/portal/account/")
324
325             # Delete reference account from the platforms
326             if 'delete_'+platform_detail['platform'] in request.POST\
327                or request.POST['button_value'] == 'delete_'+platform_detail['platform']:
328                 platform_id = platform_detail['platform_id']
329                 user_params = {'user_id':user_id}
330                 manifold_delete_account(request,platform_id, user_id, user_params)
331                 messages.info(request, 'Reference Account is removed from the selected platform')
332                 return HttpResponseRedirect("/portal/account/")
333
334             if platform_detail['platform_id'] == account_detail['platform_id']:
335                 if 'myslice' in platform_detail['platform']:
336                     account_config = json.loads(account_detail['config'])
337                     acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
338                     acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
339                 
340
341                     
342     
343     # adding the slices and corresponding credentials to list
344     if 'N/A' not in acc_slice_cred:
345         slice_list = []
346         slice_cred = [] 
347         for key, value in acc_slice_cred.iteritems():
348             slice_list.append(key)       
349             slice_cred.append(value)
350         # special case: download each slice credentials separately 
351         for i in range(0, len(slice_list)):
352             if 'dl_'+slice_list[i] in request.POST or request.POST['button_value'] == 'dl_'+slice_list[i]:
353                 slice_detail = "Slice name: " + slice_list[i] +"\nSlice Credentials: \n"+ slice_cred[i]
354                 response = HttpResponse(slice_detail, content_type='text/plain')
355                 response['Content-Disposition'] = 'attachment; filename="slice_credential.txt"'
356                 return response
357
358     # adding the authority and corresponding credentials to list
359     if 'N/A' not in acc_auth_cred:
360         auth_list = []
361         auth_cred = [] 
362         for key, value in acc_auth_cred.iteritems():
363             auth_list.append(key)       
364             auth_cred.append(value)
365         # special case: download each slice credentials separately
366         for i in range(0, len(auth_list)):
367             if 'dl_'+auth_list[i] in request.POST or request.POST['button_value'] == 'dl_'+auth_list[i]:
368                 auth_detail = "Authority: " + auth_list[i] +"\nAuthority Credentials: \n"+ auth_cred[i]
369                 response = HttpResponse(auth_detail, content_type='text/plain')
370                 response['Content-Disposition'] = 'attachment; filename="auth_credential.txt"'
371                 return response
372
373
374              
375     if 'submit_name' in request.POST:
376         edited_first_name =  request.POST['fname']
377         edited_last_name =  request.POST['lname']
378         
379         config={}
380         for user_config in user_details:
381             if user_config['config']:
382                 config = json.loads(user_config['config'])
383                 config['firstname'] = edited_first_name
384                 config['lastname'] = edited_last_name
385                 config['authority'] = config.get('authority','Unknown Authority')
386                 updated_config = json.dumps(config)
387                 user_params = {'config': updated_config}
388             else: # it's needed if the config is empty 
389                 user_config['config'] = '{{"firstname":"{}", "lastname":"{}", "authority": "Unknown Authority"}}'\
390                                         .format(edited_first_name, edited_last_name)
391                 user_params = {'config': user_config['config']} 
392         # updating config local:user in manifold       
393         manifold_update_user(request, request.user.email,user_params)
394         # this will be depricated, we will show the success msg in same page
395         # Redirect to same page with success message
396         messages.success(request, 'Sucess: First Name and Last Name Updated.')
397         return HttpResponseRedirect("/portal/account/")       
398     
399     elif 'submit_pass' in request.POST:
400         edited_password = request.POST['password']
401         
402         for user_pass in user_details:
403             user_pass['password'] = edited_password
404         #updating password in local:user
405         user_params = { 'password' : user_pass['password']}
406         manifold_update_user(request, request.user.email, user_params)
407 #        return HttpResponse('Success: Password Changed!!')
408         messages.success(request, 'Success: Password Updated.')
409         return HttpResponseRedirect("/portal/account/")
410
411 # XXX TODO: Factorize with portal/registrationview.py
412 # XXX TODO: Factorize with portal/registrationview.py
413 # XXX TODO: Factorize with portal/joinview.py
414
415     elif 'generate' in request.POST:
416         for account_detail in account_details:
417             for platform_detail in platform_details:
418                 if platform_detail['platform_id'] == account_detail['platform_id']:
419                     if 'myslice' in platform_detail['platform']:
420                         private = RSA.generate(1024)
421                         private_key = json.dumps(private.exportKey())
422                         public  = private.publickey()
423                         public_key = json.dumps(public.exportKey(format='OpenSSH'))
424                         # updating manifold local:account table
425                         account_config = json.loads(account_detail['config'])
426                         # preserving user_hrn
427                         user_hrn = account_config.get('user_hrn','N/A')
428                         keypair = '{{"user_public_key":{}, "user_private_key":{}, "user_hrn":"{}"}}'\
429                                   .format(public_key, private_key, user_hrn)
430                         #updated_config = json.dumps(account_config) 
431                         # updating manifold
432                         #user_params = { 'config': keypair, 'auth_type':'managed'}
433                         #manifold_update_account(request, user_id, user_params)
434                         # updating sfa
435                         public_key = public_key.replace('"', '');
436                         user_pub_key = {'keys': public_key}
437
438                         sfa_update_user(request, user_hrn, user_pub_key)
439                         result_sfa_user = sfa_get_user(request, user_hrn, public_key)
440                         try:
441                             if 'keys' in result_sfa_user and result_sfa_user['keys'][0] == public_key:
442                                 # updating manifold
443                                 updated_config = json.dumps(account_config) 
444                                 user_params = {'config' : keypair, 'auth_type' : 'managed'}
445                                 manifold_update_account(request, user_id, user_params)
446                                 messages.success(request,
447                                                  'Success: New Keypair Generated! '
448                                                  'Delegation of your credentials will be automatic.')
449                             else:
450                                 raise Exception,"Keys are not matching"
451                         except Exception as e:
452                             messages.error(request,
453                                            'Error: An error occured during the update '
454                                            'of your public key at the Registry, or your '
455                                            'public key is not matching the one stored.')
456                             logger.error("Exception in accountview {}".format(e))
457                         return HttpResponseRedirect("/portal/account/")
458         else:
459             messages.error(request,
460                            'Account error: You need an account in '
461                            'myslice platform to perform this action')
462             return HttpResponseRedirect("/portal/account/")
463                        
464     elif 'upload_key' in request.POST:
465         for account_detail in account_details:
466             for platform_detail in platform_details:
467                 if platform_detail['platform_id'] == account_detail['platform_id']:
468                     if 'myslice' in platform_detail['platform']:
469                         up_file = request.FILES['pubkey']
470                         file_content =  up_file.read()
471                         file_name = up_file.name
472                         file_extension = os.path.splitext(file_name)[1] 
473                         allowed_extension =  ['.pub','.txt']
474                         if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
475                             account_config = json.loads(account_detail['config'])
476                             # preserving user_hrn
477                             user_hrn = account_config.get('user_hrn','N/A')
478                             file_content = '{"user_public_key":"{}", "user_hrn":"{}"}'\
479                                            .format(file_content, user_hrn)
480                             #file_content = re.sub("\r", "", file_content)
481                             #file_content = re.sub("\n", "\\n",file_content)
482                             file_content = ''.join(file_content.split())
483                             #update manifold local:account table
484                             user_params = {'config' : file_content, 'auth_type':'user'}
485                             manifold_update_account(request, user_id, user_params)
486                             # updating sfa
487                             user_pub_key = {'keys': file_content}
488                             sfa_update_user(request, user_hrn, user_pub_key)
489                             messages.success(request,
490                                              'Publickey uploaded! Please delegate your '
491                                              'credentials using SFA: '
492                                              'http://trac.myslice.info/wiki/DelegatingCredentials')
493                             return HttpResponseRedirect("/portal/account/")
494                         else:
495                             messages.error(request,
496                                            'RSA key error: Please upload '
497                                            'a valid RSA public key [.txt or .pub].')
498                             return HttpResponseRedirect("/portal/account/")
499         else:
500             messages.error(request,
501                            'Account error: You need an account '
502                            'in myslice platform to perform this action')
503             return HttpResponseRedirect("/portal/account/")
504
505     elif 'dl_pubkey' in request.POST or request.POST['button_value'] == 'dl_pubkey':
506         for account_detail in account_details:
507             for platform_detail in platform_details:
508                 if platform_detail['platform_id'] == account_detail['platform_id']:
509                     if 'myslice' in platform_detail['platform']:
510                         account_config = json.loads(account_detail['config'])
511                         public_key = account_config['user_public_key'] 
512                         response = HttpResponse(public_key, content_type='text/plain')
513                         response['Content-Disposition'] = 'attachment; filename="pubkey.txt"'
514                         return response
515                         break
516         else:
517             messages.error(request,
518                            'Account error: You need an account '
519                            'in myslice platform to perform this action')
520             return HttpResponseRedirect("/portal/account/")
521                
522     elif 'dl_pkey' in request.POST or request.POST['button_value'] == 'dl_pkey':
523         for account_detail in account_details:
524             for platform_detail in platform_details:
525                 if platform_detail['platform_id'] == account_detail['platform_id']:
526                     if 'myslice' in platform_detail['platform']:
527                         account_config = json.loads(account_detail['config'])
528                         if 'user_private_key' in account_config:
529                             private_key = account_config['user_private_key']
530                             response = HttpResponse(private_key, content_type='text/plain')
531                             response['Content-Disposition'] = 'attachment; filename="privkey.txt"'
532                             return response
533                         else:
534                             messages.error(request,
535                                            'Download error: '
536                                            'Private key is not stored in the server')
537                             return HttpResponseRedirect("/portal/account/")
538
539         else:
540             messages.error(request,
541                            'Account error: You need an account '
542                            'in myslice platform to perform this action')
543             return HttpResponseRedirect("/portal/account/")
544     
545     elif 'delete' in request.POST or request.POST['button_value'] == 'delete':
546         for account_detail in account_details:
547             for platform_detail in platform_details:
548                 if platform_detail['platform_id'] == account_detail['platform_id']:
549                     if 'myslice' in platform_detail['platform']:
550                         account_config = json.loads(account_detail['config'])
551                         if 'user_private_key' in account_config:
552                             for key in account_config.keys():
553                                 if key == 'user_private_key':    
554                                     del account_config[key]
555                                 
556                             updated_config = json.dumps(account_config)
557                             user_params = { 'config': updated_config, 'auth_type':'user'}
558                             manifold_update_account(request, user_id, user_params)
559                             messages.success(request,
560                                              'Private Key deleted. You need to delegate '
561                                              'credentials manually once it expires.')
562                             messages.success(request,
563                                              'Once your credentials expire, Please delegate '
564                                              'manually using SFA: '
565                                              'http://trac.myslice.info/wiki/DelegatingCredentials')
566                             return HttpResponseRedirect("/portal/account/")
567                         else:
568                             messages.error(request, 'Delete error: Private key is not stored in the server')
569                             return HttpResponseRedirect("/portal/account/")
570                            
571         else:
572             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')    
573             return HttpResponseRedirect("/portal/account/")
574     
575     # download identity for jfed
576     elif 'dl_identity' in request.POST or request.POST['button_value'] == 'dl_identity':
577         for account_detail in account_details:
578             for platform_detail in platform_details:
579                 if platform_detail['platform_id'] == account_detail['platform_id']:
580                     if 'myslice' in platform_detail['platform']:
581                         account_config = json.loads(account_detail['config'])
582                         if 'user_private_key' in account_config:
583                             private_key = account_config['user_private_key']
584                             user_hrn = account_config.get('user_hrn','N/A')
585                             registry = 'http://sfa-fed4fire.pl.sophia.inria.fr:12345/'
586                             jfed_identity = user_hrn + '\n' + registry + '\n' + private_key 
587                             response = HttpResponse(jfed_identity, content_type='text/plain')
588                             response['Content-Disposition'] = 'attachment; filename="jfed_identity.txt"'
589                             return response
590                         else:
591                             messages.error(request, 'Download error: Private key is not stored in the server')
592                             return HttpResponseRedirect("/portal/account/")
593
594         else:
595             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
596             return HttpResponseRedirect("/portal/account/")
597
598     # Download sfi_config
599     elif 'dl_sfi_config' in request.POST or request.POST['button_value'] == 'dl_sfi_config':
600         platform_detail = get_myslice_platform(request)
601         platform_config = json.loads(platform_detail['config'])
602         account_detail = get_myslice_account(request)
603         account_config = json.loads(account_detail['config'])
604
605         user_hrn = account_config.get('user_hrn','N/A')
606         t_user_hrn = user_hrn.split('.')
607         authority_hrn = t_user_hrn[0] + '.' + t_user_hrn[1]
608         import socket
609         hostname = socket.gethostbyaddr(socket.gethostname())[0]
610         registry = platform_config.get('registry','N/A')
611         admin_user = platform_config.get('user','N/A')
612         if 'localhost' in registry:
613             port = registry.split(':')[-1:][0]
614             registry = "http://" + hostname +':'+ port
615         manifold_host = ConfigEngine().manifold_url()
616         if 'localhost' in manifold_host:
617             manifold_host = manifold_host.replace('localhost',hostname)
618         sfi_config  = '[sfi]\n'
619         sfi_config += 'auth = '+ authority_hrn +'\n'
620         sfi_config += 'user = '+ user_hrn +'\n'
621         sfi_config += 'registry = '+ registry +'\n'
622         sfi_config += 'sm = http://sfa3.planet-lab.eu:12346/\n\n'
623         sfi_config += '[myslice]\n'
624         sfi_config += 'backend = '+ manifold_host +'\n'
625         sfi_config += 'delegate  = '+ admin_user +'\n'
626         sfi_config += 'platform  = myslice\n'
627         sfi_config += 'username  = '+ user_email +'\n'
628         response = HttpResponse(sfi_config, content_type='text/plain')
629         response['Content-Disposition'] = 'attachment; filename="sfi_config"'
630         return response
631
632     #clear all creds
633     elif 'clear_cred' in request.POST or request.POST['button_value'] == 'clear_cred':
634         try:
635             result = clear_user_creds(request, user_email)
636             if result is not None: 
637                 messages.success(request, 'All Credentials cleared')
638             else:
639                 messages.error(request, 'Delete error: Credentials are not stored in the server')
640         except Exception as e:
641             logger.error("Exception in accountview.py in clear_user_creds {}".format(e))
642             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
643         return HttpResponseRedirect("/portal/account/")
644
645     # Download delegated_user_cred
646     elif 'dl_user_cred' in request.POST or request.POST['button_value'] == 'dl_user_cred':
647         if 'delegated_user_credential' in account_config:
648             user_cred = account_config['delegated_user_credential']
649             response = HttpResponse(user_cred, content_type='text/plain')
650             response['Content-Disposition'] = 'attachment; filename="user_cred.txt"'
651             return response
652         else:
653             messages.error(request, 'Download error: User credential is not stored in the server')
654             return HttpResponseRedirect("/portal/account/")
655
656     # Download user_cert
657     elif 'dl_user_cert' in request.POST or request.POST['button_value'] == 'dl_user_cert':
658         if 'user_credential' in account_config:
659             user_cred = account_config['user_credential']
660             obj_cred = Credential(string=user_cred)
661             obj_gid = obj_cred.get_gid_object()
662             str_cert = obj_gid.save_to_string()
663             response = HttpResponse(str_cert, content_type='text/plain')
664             response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
665             return response
666
667         elif 'delegated_user_credential' in account_config:
668             user_cred = account_config['delegated_user_credential']
669             obj_cred = Credential(string=user_cred)
670             obj_gid = obj_cred.get_gid_object()
671             str_cert = obj_gid.save_to_string()
672             response = HttpResponse(str_cert, content_type='text/plain')
673             response['Content-Disposition'] = 'attachment; filename="user_certificate.pem"'
674             return response
675         else:
676             messages.error(request, 'Download error: User credential is not stored in the server')
677             return HttpResponseRedirect("/portal/account/")
678
679     # Download user p12 = private_key + Certificate
680     elif 'dl_user_p12' in request.POST or request.POST['button_value'] == 'dl_user_p12':
681         if 'user_credential' in account_config and 'user_private_key' in account_config:
682             user_cred = account_config['user_credential']
683             obj_cred = Credential(string=user_cred)
684             obj_gid = obj_cred.get_gid_object()
685             str_cert = obj_gid.save_to_string()
686             cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)
687
688             user_private_key = account_config['user_private_key'].encode('ascii')
689             pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)
690
691             p12 = crypto.PKCS12()
692             p12.set_privatekey(pkey)
693             p12.set_certificate(cert)       
694             pkcs12 = p12.export()
695
696             response = HttpResponse(pkcs12, content_type='text/plain')
697             response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
698             return response
699
700         elif 'delegated_user_credential' in account_config and 'user_private_key' in account_config:
701             user_cred = account_config['delegated_user_credential']
702             obj_cred = Credential(string=user_cred)
703             obj_gid = obj_cred.get_gid_object()
704             str_cert = obj_gid.save_to_string()
705             cert = crypto.load_certificate(crypto.FILETYPE_PEM, str_cert)
706
707             user_private_key = account_config['user_private_key'].encode('ascii')
708             pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, user_private_key)
709
710             p12 = crypto.PKCS12()
711             p12.set_privatekey(pkey)
712             p12.set_certificate(cert)       
713             pkcs12 = p12.export()
714
715             response = HttpResponse(pkcs12, content_type='text/plain')
716             response['Content-Disposition'] = 'attachment; filename="user_pkcs.p12"'
717             return response
718         else:
719             messages.error(request, 'Download error: User private key or credential is not stored in the server')
720             return HttpResponseRedirect("/portal/account/")
721
722     else:
723         messages.info(request, 'Under Construction. Please try again later!')
724         return HttpResponseRedirect("/portal/account/")
725
726