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