UserManagement: New Templates and view created [same like accountview- will be modifi...
[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
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(AccountView, 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 == "platformname":
34             #    platformname=value
35     
36         user_query  = Query().get('local:user').select('config','email','status')
37         user_details = execute_query(self.request, user_query)
38         
39         # not always found in user_details...
40         config={}
41         for user_detail in user_details:
42             # different significations of user_status
43             if user_detail['status'] == 0: 
44                 user_status = 'Disabled'
45             elif user_detail['status'] == 1:
46                 user_status = 'Validation Pending'
47             elif user_detail['status'] == 2:
48                 user_status = 'Enabled'
49             else:
50                 user_status = 'N/A'
51             #email = user_detail['email']
52             if user_detail['config']:
53                 config = json.loads(user_detail['config'])
54
55         platform_query  = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
56         account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
57         platform_details = execute_query(self.request, platform_query)
58         account_details = execute_query(self.request, account_query)
59        
60         # initial assignment needed for users having account.config = {} 
61         platform_name = ''
62         account_type = ''
63         account_usr_hrn = ''
64         account_pub_key = ''
65         account_priv_key = ''
66         account_reference = ''
67         my_users = ''
68         my_slices = ''
69         my_auths = ''
70         ref_acc_list = ''
71         principal_acc_list = ''
72         user_status_list = []
73         platform_name_list = []
74         platform_name_secondary_list = []
75         platform_access_list = []
76         platform_no_access_list = []
77         total_platform_list = []
78         account_type_list = []
79         account_type_secondary_list = []
80         account_reference_list = []
81         delegation_type_list = []
82         user_cred_exp_list = []
83         slice_list = []
84         auth_list = []
85         slice_cred_exp_list = []
86         auth_cred_exp_list = []
87         usr_hrn_list = []
88         pub_key_list = []
89           
90         for platform_detail in platform_details:
91             if 'sfa' in platform_detail['gateway_type']:
92                 total_platform = platform_detail['platform']
93                 total_platform_list.append(total_platform)
94                 
95             for account_detail in account_details:
96                 if platform_detail['platform_id'] == account_detail['platform_id']:
97                     platform_name = platform_detail['platform']
98                     account_config = json.loads(account_detail['config'])
99                     account_usr_hrn = account_config.get('user_hrn','N/A')
100                     account_pub_key = account_config.get('user_public_key','N/A')
101                     account_reference = account_config.get ('reference_platform','N/A')
102                     # credentials of myslice platform
103                     if 'myslice' in platform_detail['platform']:
104                         acc_user_cred = account_config.get('delegated_user_credential','N/A')
105                         acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
106                         acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
107
108                         if 'N/A' not in acc_user_cred:
109                             exp_date = re.search('<expires>(.*)</expires>', acc_user_cred)
110                             if exp_date:
111                                 user_exp_date = exp_date.group(1)
112                                 user_cred_exp_list.append(user_exp_date)
113
114                             my_users = [{'cred_exp': t[0]}
115                                 for t in zip(user_cred_exp_list)]
116                        
117
118                         if 'N/A' not in acc_slice_cred:
119                             for key, value in acc_slice_cred.iteritems():
120                                 slice_list.append(key)
121                                 # get cred_exp date
122                                 exp_date = re.search('<expires>(.*)</expires>', value)
123                                 if exp_date:
124                                     exp_date = exp_date.group(1)
125                                     slice_cred_exp_list.append(exp_date)
126
127                             my_slices = [{'slice_name': t[0], 'cred_exp': t[1]}
128                                 for t in zip(slice_list, slice_cred_exp_list)]
129
130                         if 'N/A' not in acc_auth_cred:
131                             for key, value in acc_auth_cred.iteritems():
132                                 auth_list.append(key)
133                                 #get cred_exp date
134                                 exp_date = re.search('<expires>(.*)</expires>', value)
135                                 if exp_date:
136                                     exp_date = exp_date.group(1)
137                                     auth_cred_exp_list.append(exp_date)
138
139                             my_auths = [{'auth_name': t[0], 'cred_exp': t[1]}
140                                 for t in zip(auth_list, auth_cred_exp_list)]
141
142
143                     # for reference accounts
144                     if 'reference' in account_detail['auth_type']:
145                         account_type = 'Reference'
146                         delegation = 'N/A'
147                         platform_name_secondary_list.append(platform_name)
148                         account_type_secondary_list.append(account_type)
149                         account_reference_list.append(account_reference)
150                         ref_acc_list = [{'platform_name': t[0], 'account_type': t[1], 'account_reference': t[2]} 
151                             for t in zip(platform_name_secondary_list, account_type_secondary_list, account_reference_list)]
152                        
153                     elif 'managed' in account_detail['auth_type']:
154                         account_type = 'Principal'
155                         delegation = 'Automatic'
156                     else:
157                         account_type = 'Principal'
158                         delegation = 'Manual'
159                     # for principal (auth_type=user/managed) accounts
160                     if 'reference' not in account_detail['auth_type']:
161                         platform_name_list.append(platform_name)
162                         account_type_list.append(account_type)
163                         delegation_type_list.append(delegation)
164                         usr_hrn_list.append(account_usr_hrn)
165                         pub_key_list.append(account_pub_key)
166                         user_status_list.append(user_status)
167                         # combining 5 lists into 1 [to render in the template] 
168                         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],} 
169                             for t in zip(platform_name_list, account_type_list, delegation_type_list, usr_hrn_list, pub_key_list, user_status_list)]
170                     # to hide private key row if it doesn't exist    
171                     if 'myslice' in platform_detail['platform']:
172                         account_config = json.loads(account_detail['config'])
173                         account_priv_key = account_config.get('user_private_key','N/A')
174                     if 'sfa' in platform_detail['gateway_type']:
175                         platform_access = platform_detail['platform']
176                         platform_access_list.append(platform_access)
177        
178         # Removing the platform which already has access
179         for platform in platform_access_list:
180             total_platform_list.remove(platform)
181         # we could use zip. this one is used if columns have unequal rows 
182         platform_list = [{'platform_no_access': t[0]}
183             for t in itertools.izip_longest(total_platform_list)]
184
185         context = super(AccountView, self).get_context_data(**kwargs)
186         context['principal_acc'] = principal_acc_list
187         context['ref_acc'] = ref_acc_list
188         context['platform_list'] = platform_list
189         context['my_users'] = my_users
190         context['my_slices'] = my_slices
191         context['my_auths'] = my_auths
192         context['user_status'] = user_status
193         context['person']   = self.request.user
194         context['firstname'] = config.get('firstname',"?")
195         context['lastname'] = config.get('lastname',"?")
196         context['fullname'] = context['firstname'] +' '+ context['lastname']
197         context['authority'] = config.get('authority',"Unknown Authority")
198         context['user_private_key'] = account_priv_key
199         
200         # XXX This is repeated in all pages
201         # more general variables expected in the template
202         context['title'] = 'Platforms connected to MySlice'
203         # the menu items on the top
204         context['topmenu_items'] = topmenu_items_live('My Account', page)
205         # so we can sho who is logged
206         context['username'] = the_user(self.request)
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 user_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_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_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                         messages.success(request, 'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.')
349                         return HttpResponseRedirect("/portal/account/")
350         else:
351             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
352             return HttpResponseRedirect("/portal/account/")
353                        
354     elif 'upload_key' in request.POST:
355         for account_detail in account_details:
356             for platform_detail in platform_details:
357                 if platform_detail['platform_id'] == account_detail['platform_id']:
358                     if 'myslice' in platform_detail['platform']:
359                         up_file = request.FILES['pubkey']
360                         file_content =  up_file.read()
361                         file_name = up_file.name
362                         file_extension = os.path.splitext(file_name)[1] 
363                         allowed_extension =  ['.pub','.txt']
364                         if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
365                             account_config = json.loads(account_detail['config'])
366                             # preserving user_hrn
367                             user_hrn = account_config.get('user_hrn','N/A')
368                             file_content = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
369                             #file_content = re.sub("\r", "", file_content)
370                             #file_content = re.sub("\n", "\\n",file_content)
371                             file_content = ''.join(file_content.split())
372                             #update manifold local:account table
373                             user_params = { 'config': file_content, 'auth_type':'user'}
374                             manifold_update_account(request,user_params)
375                             # updating sfa
376                             user_pub_key = {'keys': file_content}
377                             sfa_update_user(request, user_hrn, user_pub_key)
378                             messages.success(request, 'Publickey uploaded! Please delegate your credentials using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
379                             return HttpResponseRedirect("/portal/account/")
380                         else:
381                             messages.error(request, 'RSA key error: Please upload a valid RSA public key [.txt or .pub].')
382                             return HttpResponseRedirect("/portal/account/")
383         else:
384             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
385             return HttpResponseRedirect("/portal/account/")
386
387     elif 'dl_pubkey' in request.POST:
388         for account_detail in account_details:
389             for platform_detail in platform_details:
390                 if platform_detail['platform_id'] == account_detail['platform_id']:
391                     if 'myslice' in platform_detail['platform']:
392                         account_config = json.loads(account_detail['config'])
393                         public_key = account_config['user_public_key'] 
394                         response = HttpResponse(public_key, content_type='text/plain')
395                         response['Content-Disposition'] = 'attachment; filename="pubkey.txt"'
396                         return response
397                         break
398         else:
399             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
400             return HttpResponseRedirect("/portal/account/")
401                
402     elif 'dl_pkey' in request.POST:
403         for account_detail in account_details:
404             for platform_detail in platform_details:
405                 if platform_detail['platform_id'] == account_detail['platform_id']:
406                     if 'myslice' in platform_detail['platform']:
407                         account_config = json.loads(account_detail['config'])
408                         if 'user_private_key' in account_config:
409                             private_key = account_config['user_private_key']
410                             response = HttpResponse(private_key, content_type='text/plain')
411                             response['Content-Disposition'] = 'attachment; filename="privkey.txt"'
412                             return response
413                         else:
414                             messages.error(request, 'Download error: Private key is not stored in the server')
415                             return HttpResponseRedirect("/portal/account/")
416
417         else:
418             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
419             return HttpResponseRedirect("/portal/account/")
420     
421     elif 'delete' in request.POST:
422         for account_detail in account_details:
423             for platform_detail in platform_details:
424                 if platform_detail['platform_id'] == account_detail['platform_id']:
425                     if 'myslice' in platform_detail['platform']:
426                         account_config = json.loads(account_detail['config'])
427                         if 'user_private_key' in account_config:
428                             for key in account_config.keys():
429                                 if key == 'user_private_key':    
430                                     del account_config[key]
431                                 
432                             updated_config = json.dumps(account_config)
433                             user_params = { 'config': updated_config, 'auth_type':'user'}
434                             manifold_update_account(request,user_params)
435                             messages.success(request, 'Private Key deleted. You need to delegate credentials manually once it expires.')
436                             messages.success(request, 'Once your credentials expire, Please delegate manually using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
437                             return HttpResponseRedirect("/portal/account/")
438                         else:
439                             messages.error(request, 'Delete error: Private key is not stored in the server')
440                             return HttpResponseRedirect("/portal/account/")
441                            
442         else:
443             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')    
444             return HttpResponseRedirect("/portal/account/")
445
446     #clear all creds
447     elif 'clear_cred' in request.POST:
448         for account_detail in account_details:
449             for platform_detail in platform_details:
450                 if platform_detail['platform_id'] == account_detail['platform_id']:
451                     if 'myslice' in platform_detail['platform']:
452                         account_config = json.loads(account_detail['config'])
453                         user_cred = account_config.get('delegated_user_credential','N/A')
454                         if 'N/A' not in user_cred:
455                             user_hrn = account_config.get('user_hrn','N/A')
456                             user_pub_key = json.dumps(account_config.get('user_public_key','N/A'))
457                             user_priv_key = json.dumps(account_config.get('user_private_key','N/A'))
458                             updated_config = '{"user_public_key":'+ user_pub_key + ', "user_private_key":'+ user_priv_key + ', "user_hrn":"'+ user_hrn + '"}'
459                             user_params = { 'config': updated_config}
460                             manifold_update_account(request,user_params)
461                             messages.success(request, 'All Credentials cleared')
462                             return HttpResponseRedirect("/portal/account/")
463                         else:
464                             messages.error(request, 'Delete error: Credentials are not stored in the server')
465                             return HttpResponseRedirect("/portal/account/")
466         else:
467             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
468             return HttpResponseRedirect("/portal/account/")
469
470
471     # Download delegated_user_cred
472     elif 'dl_user_cred' in request.POST:
473         if 'delegated_user_credential' in account_config:
474             user_cred = account_config['delegated_user_credential']
475             response = HttpResponse(user_cred, content_type='text/plain')
476             response['Content-Disposition'] = 'attachment; filename="user_cred.txt"'
477             return response
478         else:
479             messages.error(request, 'Download error: User credential  is not stored in the server')
480             return HttpResponseRedirect("/portal/account/")
481         
482     else:
483         messages.info(request, 'Under Construction. Please try again later!')
484         return HttpResponseRedirect("/portal/account/")
485
486