account: template specific for fed4fire
[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         self.template_name = self.template
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         context = super(AccountView, self).get_context_data(**kwargs)
183         context['principal_acc'] = principal_acc_list
184         context['ref_acc'] = ref_acc_list
185         context['platform_list'] = platform_list
186         context['my_users'] = my_users
187         context['my_slices'] = my_slices
188         context['my_auths'] = my_auths
189         context['user_status'] = user_status
190         context['person']   = self.request.user
191         context['firstname'] = config.get('firstname',"?")
192         context['lastname'] = config.get('lastname',"?")
193         context['fullname'] = context['firstname'] +' '+ context['lastname']
194         context['authority'] = config.get('authority',"Unknown Authority")
195         context['user_private_key'] = account_priv_key
196         
197         # XXX This is repeated in all pages
198         # more general variables expected in the template
199         context['title'] = 'Platforms connected to MySlice'
200         # the menu items on the top
201         context['topmenu_items'] = topmenu_items_live('My Account', page)
202         # so we can sho who is logged
203         context['username'] = the_user(self.request)
204         context['theme'] = self.theme
205         context['section'] = "User account"
206 #        context ['firstname'] = config['firstname']
207         prelude_env = page.prelude_env()
208         context.update(prelude_env)
209         return context
210
211
212 @login_required
213 #my_acc form value processing
214 def account_process(request):
215     user_query  = Query().get('local:user').select('user_id','email','password','config')
216     user_details = execute_query(request, user_query)
217     
218     account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
219     account_details = execute_query(request, account_query)
220
221     platform_query  = Query().get('local:platform').select('platform_id','platform')
222     platform_details = execute_query(request, platform_query)
223     
224     # getting the user_id from the session
225     for user_detail in user_details:
226             user_id = user_detail['user_id']
227
228     for account_detail in account_details:
229         for platform_detail in platform_details:
230             # Add reference account to the platforms
231             if 'add_'+platform_detail['platform'] in request.POST:
232                 platform_id = platform_detail['platform_id']
233                 user_params = {'platform_id': platform_id, 'user_id': user_id, 'auth_type': "reference", 'config': '{"reference_platform": "myslice"}'}
234                 manifold_add_account(request,user_params)
235                 messages.info(request, 'Reference Account is added to the selected platform successfully!')
236                 return HttpResponseRedirect("/portal/account/")
237
238             # Delete reference account from the platforms
239             if 'delete_'+platform_detail['platform'] in request.POST:
240                 platform_id = platform_detail['platform_id']
241                 user_params = {'user_id':user_id}
242                 manifold_delete_account(request,platform_id, user_id, user_params)
243                 messages.info(request, 'Reference Account is removed from the selected platform')
244                 return HttpResponseRedirect("/portal/account/")
245
246             if platform_detail['platform_id'] == account_detail['platform_id']:
247                 if 'myslice' in platform_detail['platform']:
248                     account_config = json.loads(account_detail['config'])
249                     acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
250                     acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
251                 
252
253                     
254     
255     # adding the slices and corresponding credentials to list
256     if 'N/A' not in acc_slice_cred:
257         slice_list = []
258         slice_cred = [] 
259         for key, value in acc_slice_cred.iteritems():
260             slice_list.append(key)       
261             slice_cred.append(value)
262         # special case: download each slice credentials separately 
263         for i in range(0, len(slice_list)):
264             if 'dl_'+slice_list[i] in request.POST:
265                 slice_detail = "Slice name: " + slice_list[i] +"\nSlice Credentials: \n"+ slice_cred[i]
266                 response = HttpResponse(slice_detail, content_type='text/plain')
267                 response['Content-Disposition'] = 'attachment; filename="slice_credential.txt"'
268                 return response
269
270     # adding the authority and corresponding credentials to list
271     if 'N/A' not in acc_auth_cred:
272         auth_list = []
273         auth_cred = [] 
274         for key, value in acc_auth_cred.iteritems():
275             auth_list.append(key)       
276             auth_cred.append(value)
277         # special case: download each slice credentials separately
278         for i in range(0, len(auth_list)):
279             if 'dl_'+auth_list[i] in request.POST:
280                 auth_detail = "Authority: " + auth_list[i] +"\nAuthority Credentials: \n"+ auth_cred[i]
281                 response = HttpResponse(auth_detail, content_type='text/plain')
282                 response['Content-Disposition'] = 'attachment; filename="auth_credential.txt"'
283                 return response
284
285
286              
287     if 'submit_name' in request.POST:
288         edited_first_name =  request.POST['fname']
289         edited_last_name =  request.POST['lname']
290         
291         config={}
292         for user_config in user_details:
293             if user_config['config']:
294                 config = json.loads(user_config['config'])
295                 config['firstname'] = edited_first_name
296                 config['lastname'] = edited_last_name
297                 config['authority'] = config.get('authority','Unknown Authority')
298                 updated_config = json.dumps(config)
299                 user_params = {'config': updated_config}
300             else: # it's needed if the config is empty 
301                 user_config['config']= '{"firstname":"' + edited_first_name + '", "lastname":"'+ edited_last_name + '", "authority": "Unknown Authority"}'
302                 user_params = {'config': user_config['config']} 
303         # updating config local:user in manifold       
304         manifold_update_user(request, request.user.email,user_params)
305         # this will be depricated, we will show the success msg in same page
306         # Redirect to same page with success message
307         messages.success(request, 'Sucess: First Name and Last Name Updated.')
308         return HttpResponseRedirect("/portal/account/")       
309     
310     elif 'submit_pass' in request.POST:
311         edited_password = request.POST['password']
312         
313         for user_pass in user_details:
314             user_pass['password'] = edited_password
315         #updating password in local:user
316         user_params = { 'password': user_pass['password']}
317         manifold_update_user(request,request.user.email,user_params)
318 #        return HttpResponse('Success: Password Changed!!')
319         messages.success(request, 'Sucess: Password Updated.')
320         return HttpResponseRedirect("/portal/account/")
321
322 # XXX TODO: Factorize with portal/registrationview.py
323
324     elif 'generate' in request.POST:
325         for account_detail in account_details:
326             for platform_detail in platform_details:
327                 if platform_detail['platform_id'] == account_detail['platform_id']:
328                     if 'myslice' in platform_detail['platform']:
329                         from Crypto.PublicKey import RSA
330                         private = RSA.generate(1024)
331                         private_key = json.dumps(private.exportKey())
332                         public  = private.publickey()
333                         public_key = json.dumps(public.exportKey(format='OpenSSH'))
334                         # updating manifold local:account table
335                         account_config = json.loads(account_detail['config'])
336                         # preserving user_hrn
337                         user_hrn = account_config.get('user_hrn','N/A')
338                         keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
339                         #updated_config = json.dumps(account_config) 
340                         # updating manifold
341                         #user_params = { 'config': keypair, 'auth_type':'managed'}
342                         #manifold_update_account(request, user_id, user_params)
343                         # updating sfa
344                         public_key = public_key.replace('"', '');
345                         user_pub_key = {'keys': public_key}
346                         #sfa_update_user(request, user_hrn, user_pub_key)
347                         sfa_update_user(request, user_hrn, user_pub_key)
348                         result_sfa_user = sfa_get_user(request, user_hrn, public_key)
349                         try:
350                             result_sfa_user = result_sfa_user[0]
351                             if 'keys' in result_sfa_user and result_sfa_user['keys'][0] == public_key:
352                                 # updating manifold
353                                 updated_config = json.dumps(account_config) 
354                                 user_params = { 'config': keypair, 'auth_type':'managed'}
355                                 manifold_update_account(request, user_id, user_params)
356                                 messages.success(request, 'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.')
357                             else:
358                                 raise Exception,"Keys are not matching"
359                         except Exception,e:
360                             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.')
361                         return HttpResponseRedirect("/portal/account/")
362         else:
363             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
364             return HttpResponseRedirect("/portal/account/")
365                        
366     elif 'upload_key' in request.POST:
367         for account_detail in account_details:
368             for platform_detail in platform_details:
369                 if platform_detail['platform_id'] == account_detail['platform_id']:
370                     if 'myslice' in platform_detail['platform']:
371                         up_file = request.FILES['pubkey']
372                         file_content =  up_file.read()
373                         file_name = up_file.name
374                         file_extension = os.path.splitext(file_name)[1] 
375                         allowed_extension =  ['.pub','.txt']
376                         if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
377                             account_config = json.loads(account_detail['config'])
378                             # preserving user_hrn
379                             user_hrn = account_config.get('user_hrn','N/A')
380                             file_content = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
381                             #file_content = re.sub("\r", "", file_content)
382                             #file_content = re.sub("\n", "\\n",file_content)
383                             file_content = ''.join(file_content.split())
384                             #update manifold local:account table
385                             user_params = { 'config': file_content, 'auth_type':'user'}
386                             manifold_update_account(request, user_id, user_params)
387                             # updating sfa
388                             user_pub_key = {'keys': file_content}
389                             sfa_update_user(request, user_hrn, user_pub_key)
390                             messages.success(request, 'Publickey uploaded! Please delegate your credentials using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
391                             return HttpResponseRedirect("/portal/account/")
392                         else:
393                             messages.error(request, 'RSA key error: Please upload a valid RSA public key [.txt or .pub].')
394                             return HttpResponseRedirect("/portal/account/")
395         else:
396             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
397             return HttpResponseRedirect("/portal/account/")
398
399     elif 'dl_pubkey' in request.POST:
400         for account_detail in account_details:
401             for platform_detail in platform_details:
402                 if platform_detail['platform_id'] == account_detail['platform_id']:
403                     if 'myslice' in platform_detail['platform']:
404                         account_config = json.loads(account_detail['config'])
405                         public_key = account_config['user_public_key'] 
406                         response = HttpResponse(public_key, content_type='text/plain')
407                         response['Content-Disposition'] = 'attachment; filename="pubkey.txt"'
408                         return response
409                         break
410         else:
411             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
412             return HttpResponseRedirect("/portal/account/")
413                
414     elif 'dl_pkey' in request.POST:
415         for account_detail in account_details:
416             for platform_detail in platform_details:
417                 if platform_detail['platform_id'] == account_detail['platform_id']:
418                     if 'myslice' in platform_detail['platform']:
419                         account_config = json.loads(account_detail['config'])
420                         if 'user_private_key' in account_config:
421                             private_key = account_config['user_private_key']
422                             response = HttpResponse(private_key, content_type='text/plain')
423                             response['Content-Disposition'] = 'attachment; filename="privkey.txt"'
424                             return response
425                         else:
426                             messages.error(request, 'Download error: Private key is not stored in the server')
427                             return HttpResponseRedirect("/portal/account/")
428
429         else:
430             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
431             return HttpResponseRedirect("/portal/account/")
432     
433     elif 'delete' in request.POST:
434         for account_detail in account_details:
435             for platform_detail in platform_details:
436                 if platform_detail['platform_id'] == account_detail['platform_id']:
437                     if 'myslice' in platform_detail['platform']:
438                         account_config = json.loads(account_detail['config'])
439                         if 'user_private_key' in account_config:
440                             for key in account_config.keys():
441                                 if key == 'user_private_key':    
442                                     del account_config[key]
443                                 
444                             updated_config = json.dumps(account_config)
445                             user_params = { 'config': updated_config, 'auth_type':'user'}
446                             manifold_update_account(request, user_id, user_params)
447                             messages.success(request, 'Private Key deleted. You need to delegate credentials manually once it expires.')
448                             messages.success(request, 'Once your credentials expire, Please delegate manually using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
449                             return HttpResponseRedirect("/portal/account/")
450                         else:
451                             messages.error(request, 'Delete error: Private key is not stored in the server')
452                             return HttpResponseRedirect("/portal/account/")
453                            
454         else:
455             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')    
456             return HttpResponseRedirect("/portal/account/")
457     
458     # download identity for jfed
459     elif 'dl_identity' in request.POST:
460         for account_detail in account_details:
461             for platform_detail in platform_details:
462                 if platform_detail['platform_id'] == account_detail['platform_id']:
463                     if 'myslice' in platform_detail['platform']:
464                         account_config = json.loads(account_detail['config'])
465                         if 'user_private_key' in account_config:
466                             private_key = account_config['user_private_key']
467                             user_hrn = account_config.get('user_hrn','N/A')
468                             registry = 'http://sfa-fed4fire.pl.sophia.inria.fr:12345/'
469                             jfed_identity = user_hrn + '\n' + registry + '\n' + private_key 
470                             response = HttpResponse(jfed_identity, content_type='text/plain')
471                             response['Content-Disposition'] = 'attachment; filename="jfed_identity.txt"'
472                             return response
473                         else:
474                             messages.error(request, 'Download error: Private key is not stored in the server')
475                             return HttpResponseRedirect("/portal/account/")
476
477         else:
478             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
479             return HttpResponseRedirect("/portal/account/")
480
481     #clear all creds
482     elif 'clear_cred' in request.POST:
483         for account_detail in account_details:
484             for platform_detail in platform_details:
485                 if platform_detail['platform_id'] == account_detail['platform_id']:
486                     if 'myslice' in platform_detail['platform']:
487                         account_config = json.loads(account_detail['config'])
488                         user_cred = account_config.get('delegated_user_credential','N/A')
489                         if 'N/A' not in user_cred:
490                             user_hrn = account_config.get('user_hrn','N/A')
491                             user_pub_key = json.dumps(account_config.get('user_public_key','N/A'))
492                             user_priv_key = json.dumps(account_config.get('user_private_key','N/A'))
493                             updated_config = '{"user_public_key":'+ user_pub_key + ', "user_private_key":'+ user_priv_key + ', "user_hrn":"'+ user_hrn + '"}'
494                             user_params = { 'config': updated_config}
495                             manifold_update_account(request,user_id, user_params)
496                             messages.success(request, 'All Credentials cleared')
497                             return HttpResponseRedirect("/portal/account/")
498                         else:
499                             messages.error(request, 'Delete error: Credentials are not stored in the server')
500                             return HttpResponseRedirect("/portal/account/")
501         else:
502             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
503             return HttpResponseRedirect("/portal/account/")
504
505
506     # Download delegated_user_cred
507     elif 'dl_user_cred' in request.POST:
508         if 'delegated_user_credential' in account_config:
509             user_cred = account_config['delegated_user_credential']
510             response = HttpResponse(user_cred, content_type='text/plain')
511             response['Content-Disposition'] = 'attachment; filename="user_cred.txt"'
512             return response
513         else:
514             messages.error(request, 'Download error: User credential  is not stored in the server')
515             return HttpResponseRedirect("/portal/account/")
516         
517     else:
518         messages.info(request, 'Under Construction. Please try again later!')
519         return HttpResponseRedirect("/portal/account/")
520
521