11166bbe38256f1050c690d6b0bf42238f01e8d6
[myslice.git] / portal / manageuserview.py
1 from unfold.loginrequired               import LoginRequiredAutoLogoutView
2 #
3 from manifold.core.query                import Query
4 from manifold.manifoldapi               import execute_query, execute_admin_query
5 from portal.actions                     import manifold_update_user, manifold_update_account, manifold_add_account, manifold_delete_account, sfa_update_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 from django.core.mail                   import send_mail
14
15 #
16 import json, os, re, itertools
17
18 # requires login
19 class UserView(LoginRequiredAutoLogoutView):
20     template_name = "manageuserview.html"
21     def dispatch(self, *args, **kwargs):
22         return super(UserView, self).dispatch(*args, **kwargs)
23
24
25     def get_context_data(self, **kwargs):
26
27         page = Page(self.request)
28         page.add_js_files  ( [ "js/jquery.validate.js", "js/my_account.register.js", "js/my_account.edit_profile.js" ] )
29         page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css" ] )
30
31         for key, value in kwargs.iteritems():
32             #print "%s = %s" % (key, value)
33             if key == "email":
34                 selected_email=value
35     
36         user_query  = Query().get('local:user').filter_by('email', '==', selected_email).select('user_id','config','email','status')
37         user_details = execute_admin_query(self.request, user_query)
38         
39         # not always found in user_details...
40         config={}
41         for user_detail in user_details:
42             user_id = user_detail['user_id']
43             user_email = user_detail['email'] 
44             print "hello_world"
45             print user_id          
46             # different significations of user_status
47             if user_detail['status'] == 0: 
48                 user_status = 'Disabled'
49             elif user_detail['status'] == 1:
50                 user_status = 'Validation Pending'
51             elif user_detail['status'] == 2:
52                 user_status = 'Enabled'
53             else:
54                 user_status = 'N/A'
55             #email = user_detail['email']
56             if user_detail['config']:
57                 config = json.loads(user_detail['config'])
58
59         platform_query  = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
60         account_query  = Query().get('local:account').filter_by('user_id', '==', user_id).select('user_id','platform_id','auth_type','config')
61         platform_details = execute_query(self.request, platform_query)
62         account_details = execute_admin_query(self.request, account_query)
63        
64         # initial assignment needed for users having account.config = {} 
65         platform_name = ''
66         account_type = ''
67         account_usr_hrn = ''
68         account_pub_key = ''
69         account_priv_key = ''
70         account_reference = ''
71         my_users = ''
72         my_slices = ''
73         my_auths = ''
74         ref_acc_list = ''
75         principal_acc_list = ''
76         user_status_list = []
77         platform_name_list = []
78         platform_name_secondary_list = []
79         platform_access_list = []
80         platform_no_access_list = []
81         total_platform_list = []
82         account_type_list = []
83         account_type_secondary_list = []
84         account_reference_list = []
85         delegation_type_list = []
86         user_cred_exp_list = []
87         slice_list = []
88         auth_list = []
89         slice_cred_exp_list = []
90         auth_cred_exp_list = []
91         usr_hrn_list = []
92         pub_key_list = []
93           
94         for platform_detail in platform_details:
95             if 'sfa' in platform_detail['gateway_type']:
96                 total_platform = platform_detail['platform']
97                 total_platform_list.append(total_platform)
98                 
99             for account_detail in account_details:
100                 if platform_detail['platform_id'] == account_detail['platform_id']:
101                     platform_name = platform_detail['platform']
102                     account_config = json.loads(account_detail['config'])
103                     account_usr_hrn = account_config.get('user_hrn','N/A')
104                     account_pub_key = account_config.get('user_public_key','N/A')
105                     account_reference = account_config.get ('reference_platform','N/A')
106                     # credentials of myslice platform
107                     if 'myslice' in platform_detail['platform']:
108                         acc_user_cred = account_config.get('delegated_user_credential','N/A')
109                         acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
110                         acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
111
112                         if 'N/A' not in acc_user_cred:
113                             exp_date = re.search('<expires>(.*)</expires>', acc_user_cred)
114                             if exp_date:
115                                 user_exp_date = exp_date.group(1)
116                                 user_cred_exp_list.append(user_exp_date)
117
118                             my_users = [{'cred_exp': t[0]}
119                                 for t in zip(user_cred_exp_list)]
120                        
121
122                         if 'N/A' not in acc_slice_cred:
123                             for key, value in acc_slice_cred.iteritems():
124                                 slice_list.append(key)
125                                 # get cred_exp date
126                                 exp_date = re.search('<expires>(.*)</expires>', value)
127                                 if exp_date:
128                                     exp_date = exp_date.group(1)
129                                     slice_cred_exp_list.append(exp_date)
130
131                             my_slices = [{'slice_name': t[0], 'cred_exp': t[1]}
132                                 for t in zip(slice_list, slice_cred_exp_list)]
133
134                         if 'N/A' not in acc_auth_cred:
135                             for key, value in acc_auth_cred.iteritems():
136                                 auth_list.append(key)
137                                 #get cred_exp date
138                                 exp_date = re.search('<expires>(.*)</expires>', value)
139                                 if exp_date:
140                                     exp_date = exp_date.group(1)
141                                     auth_cred_exp_list.append(exp_date)
142
143                             my_auths = [{'auth_name': t[0], 'cred_exp': t[1]}
144                                 for t in zip(auth_list, auth_cred_exp_list)]
145
146
147                     # for reference accounts
148                     if 'reference' in account_detail['auth_type']:
149                         account_type = 'Reference'
150                         delegation = 'N/A'
151                         platform_name_secondary_list.append(platform_name)
152                         account_type_secondary_list.append(account_type)
153                         account_reference_list.append(account_reference)
154                         ref_acc_list = [{'platform_name': t[0], 'account_type': t[1], 'account_reference': t[2]} 
155                             for t in zip(platform_name_secondary_list, account_type_secondary_list, account_reference_list)]
156                        
157                     elif 'managed' in account_detail['auth_type']:
158                         account_type = 'Principal'
159                         delegation = 'Automatic'
160                     else:
161                         account_type = 'Principal'
162                         delegation = 'Manual'
163                     # for principal (auth_type=user/managed) accounts
164                     if 'reference' not in account_detail['auth_type']:
165                         platform_name_list.append(platform_name)
166                         account_type_list.append(account_type)
167                         delegation_type_list.append(delegation)
168                         usr_hrn_list.append(account_usr_hrn)
169                         pub_key_list.append(account_pub_key)
170                         user_status_list.append(user_status)
171                         # combining 5 lists into 1 [to render in the template] 
172                         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],} 
173                             for t in zip(platform_name_list, account_type_list, delegation_type_list, usr_hrn_list, pub_key_list, user_status_list)]
174                     # to hide private key row if it doesn't exist    
175                     if 'myslice' in platform_detail['platform']:
176                         account_config = json.loads(account_detail['config'])
177                         account_priv_key = account_config.get('user_private_key','N/A')
178                     if 'sfa' in platform_detail['gateway_type']:
179                         platform_access = platform_detail['platform']
180                         platform_access_list.append(platform_access)
181        
182         # Removing the platform which already has access
183         for platform in platform_access_list:
184             total_platform_list.remove(platform)
185         # we could use zip. this one is used if columns have unequal rows 
186         platform_list = [{'platform_no_access': t[0]}
187             for t in itertools.izip_longest(total_platform_list)]
188
189         context = super(UserView, self).get_context_data(**kwargs)
190         context['principal_acc'] = principal_acc_list
191         context['ref_acc'] = ref_acc_list
192         context['platform_list'] = platform_list
193         context['my_users'] = my_users
194         context['my_slices'] = my_slices
195         context['my_auths'] = my_auths
196         context['user_status'] = user_status
197         context['user_email']   = user_email
198         context['firstname'] = config.get('firstname',"?")
199         context['lastname'] = config.get('lastname',"?")
200         context['fullname'] = context['firstname'] +' '+ context['lastname']
201         context['authority'] = config.get('authority',"Unknown Authority")
202         context['user_private_key'] = account_priv_key
203         
204         # XXX This is repeated in all pages
205         # more general variables expected in the template
206         context['title'] = 'Platforms connected to MySlice'
207         # the menu items on the top
208         context['topmenu_items'] = topmenu_items_live('My Account', page)
209         # so we can sho who is logged
210         context['username'] = the_user(self.request)
211 #        context ['firstname'] = config['firstname']
212         prelude_env = page.prelude_env()
213         context.update(prelude_env)
214         return context
215
216
217 @login_required
218 #my_acc form value processing
219 def user_process(request, **kwargs):
220         
221     for key, value in kwargs.iteritems():
222         if key == "email":
223             selected_email=value
224
225     redirect_url = "/portal/user/"+selected_email
226     
227     user_query  = Query().get('local:user').filter_by('email', '==', selected_email).select('user_id','email','password','config')
228     user_details = execute_admin_query(request, user_query)
229
230     # getting the user_id from the session
231     for user_detail in user_details:
232         user_id = user_detail['user_id']
233         user_email = user_detail['email']
234     
235     account_query  = Query().get('local:account').filter_by('user_id', '==', user_id).select('user_id','platform_id','auth_type','config')
236     account_details = execute_admin_query(request, account_query)
237
238     platform_query  = Query().get('local:platform').select('platform_id','platform')
239     platform_details = execute_admin_query(request, platform_query)
240     
241
242     for account_detail in account_details:
243         for platform_detail in platform_details:
244             # Add reference account to the platforms
245             if 'add_'+platform_detail['platform'] in request.POST:
246                 platform_id = platform_detail['platform_id']
247                 user_params = {'platform_id': platform_id, 'user_id': user_id, 'auth_type': "reference", 'config': '{"reference_platform": "myslice"}'}
248                 manifold_add_account(request,user_params)
249                 messages.info(request, 'Reference Account is added to the selected platform successfully!')
250                 return HttpResponseRedirect(redirect_url)
251
252             # Delete reference account from the platforms
253             if 'delete_'+platform_detail['platform'] in request.POST:
254                 platform_id = platform_detail['platform_id']
255                 user_params = {'user_id':user_id}
256                 manifold_delete_account(request,platform_id,user_params)
257                 messages.info(request, 'Refeence Account is removed from the selected platform')
258                 return HttpResponseRedirect(redirect_url)
259
260             if platform_detail['platform_id'] == account_detail['platform_id']:
261                 if 'myslice' in platform_detail['platform']:
262                     account_config = json.loads(account_detail['config'])
263                     acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
264                     acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
265                 
266
267                     
268     
269     # adding the slices and corresponding credentials to list
270     if 'N/A' not in acc_slice_cred:
271         slice_list = []
272         slice_cred = [] 
273         for key, value in acc_slice_cred.iteritems():
274             slice_list.append(key)       
275             slice_cred.append(value)
276         # special case: download each slice credentials separately 
277         for i in range(0, len(slice_list)):
278             if 'dl_'+slice_list[i] in request.POST:
279                 slice_detail = "Slice name: " + slice_list[i] +"\nSlice Credentials: \n"+ slice_cred[i]
280                 response = HttpResponse(slice_detail, content_type='text/plain')
281                 response['Content-Disposition'] = 'attachment; filename="slice_credential.txt"'
282                 return response
283
284     # adding the authority and corresponding credentials to list
285     if 'N/A' not in acc_auth_cred:
286         auth_list = []
287         auth_cred = [] 
288         for key, value in acc_auth_cred.iteritems():
289             auth_list.append(key)       
290             auth_cred.append(value)
291         # special case: download each slice credentials separately
292         for i in range(0, len(auth_list)):
293             if 'dl_'+auth_list[i] in request.POST:
294                 auth_detail = "Authority: " + auth_list[i] +"\nAuthority Credentials: \n"+ auth_cred[i]
295                 response = HttpResponse(auth_detail, content_type='text/plain')
296                 response['Content-Disposition'] = 'attachment; filename="auth_credential.txt"'
297                 return response
298
299
300              
301     if 'submit_name' in request.POST:
302         edited_first_name =  request.POST['fname']
303         edited_last_name =  request.POST['lname']
304         
305         config={}
306         for user_config in user_details:
307             if user_config['config']:
308                 config = json.loads(user_config['config'])
309                 config['firstname'] = edited_first_name
310                 config['lastname'] = edited_last_name
311                 config['authority'] = config.get('authority','Unknown Authority')
312                 updated_config = json.dumps(config)
313                 user_params = {'config': updated_config}
314             else: # it's needed if the config is empty 
315                 user_config['config']= '{"firstname":"' + edited_first_name + '", "lastname":"'+ edited_last_name + '", "authority": "Unknown Authority"}'
316                 user_params = {'config': user_config['config']} 
317         # updating config local:user in manifold       
318         manifold_update_user(request, user_email, user_params)
319         # this will be depricated, we will show the success msg in same page
320         # Redirect to same page with success message
321         messages.success(request, 'Sucess: First Name and Last Name Updated.')
322         return HttpResponseRedirect(redirect_url)       
323     
324     #elif 'submit_pass' in request.POST:
325     #    edited_password = request.POST['password']
326     #    
327     #    for user_pass in user_details:
328     #        user_pass['password'] = edited_password
329     #    #updating password in local:user
330     #    user_params = { 'password': user_pass['password']}
331     #    manifold_update_user(request,request.user.email,user_params)
332 #   #     return HttpResponse('Success: Password Changed!!')
333     #    messages.success(request, 'Sucess: Password Updated.')
334     #    return HttpResponseRedirect("/portal/account/")
335
336 # XXX TODO: Factorize with portal/registrationview.py
337
338     elif 'generate' in request.POST:
339         for account_detail in account_details:
340             for platform_detail in platform_details:
341                 if platform_detail['platform_id'] == account_detail['platform_id']:
342                     if 'myslice' in platform_detail['platform']:
343                         from Crypto.PublicKey import RSA
344                         private = RSA.generate(1024)
345                         private_key = json.dumps(private.exportKey())
346                         public  = private.publickey()
347                         public_key = json.dumps(public.exportKey(format='OpenSSH'))
348                         # updating manifold local:account table
349                         account_config = json.loads(account_detail['config'])
350                         # preserving user_hrn
351                         user_hrn = account_config.get('user_hrn','N/A')
352                         keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
353                         updated_config = json.dumps(account_config) 
354                         # updating manifold
355                         user_params = { 'config': keypair, 'auth_type':'managed'}
356                         manifold_update_account(request,user_params)
357                         # updating sfa
358                         public_key = public_key.replace('"', '');
359                         user_pub_key = {'keys': public_key}
360                         sfa_update_user(request, user_hrn, user_pub_key)
361                         messages.success(request, 'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.')
362                         return HttpResponseRedirect(redirect_url)
363         else:
364             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
365             return HttpResponseRedirect(redirect_url)
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_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(redirect_url)
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(redirect_url)
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(redirect_url)
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_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(redirect_url)
454                            
455         else:
456             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')    
457             return HttpResponseRedirect(redirect_url)
458
459     #clear all creds
460     elif 'clear_cred' 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                         user_cred = account_config.get('delegated_user_credential','N/A')
467                         if 'N/A' not in user_cred:
468                             user_hrn = account_config.get('user_hrn','N/A')
469                             user_pub_key = json.dumps(account_config.get('user_public_key','N/A'))
470                             user_priv_key = json.dumps(account_config.get('user_private_key','N/A'))
471                             updated_config = '{"user_public_key":'+ user_pub_key + ', "user_private_key":'+ user_priv_key + ', "user_hrn":"'+ user_hrn + '"}'
472                             user_params = { 'config': updated_config}
473                             manifold_update_account(request,user_params)
474                             messages.success(request, 'All Credentials cleared')
475                             return HttpResponseRedirect("/portal/account/")
476                         else:
477                             messages.error(request, 'Delete error: Credentials are not stored in the server')
478                             return HttpResponseRedirect(redirect_url)
479         else:
480             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
481             return HttpResponseRedirect(redirect_url)
482
483
484     # Download delegated_user_cred
485     elif 'dl_user_cred' in request.POST:
486         if 'delegated_user_credential' in account_config:
487             user_cred = account_config['delegated_user_credential']
488             response = HttpResponse(user_cred, content_type='text/plain')
489             response['Content-Disposition'] = 'attachment; filename="user_cred.txt"'
490             return response
491         else:
492             messages.error(request, 'Download error: User credential  is not stored in the server')
493             return HttpResponseRedirect(redirect_url)
494         
495     else:
496         messages.info(request, 'Under Construction. Please try again later!')
497         return HttpResponseRedirect(redirect_url)
498
499