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