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