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