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