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