Merge branch 'master' of ssh://git.onelab.eu/git/myslice
[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']:
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         print platform_access_list
156         print total_platform_list
157         for platform in platform_access_list:
158             print platform
159             total_platform_list.remove(platform)
160         # we could use zip. this one is used if columns have unequal rows 
161         platform_list = [{'platform_no_access': t[0]}
162             for t in itertools.izip_longest(total_platform_list)]
163
164         context = super(AccountView, self).get_context_data(**kwargs)
165         context['data'] = lst
166         context['ref_acc'] = secondary_list
167         context['platform_list'] = platform_list
168         context['my_users'] = my_users
169         context['my_slices'] = my_slices
170         context['my_auths'] = my_auths
171         context['person']   = self.request.user
172         context['firstname'] = config.get('firstname',"?")
173         context['lastname'] = config.get('lastname',"?")
174         context['fullname'] = context['firstname'] +' '+ context['lastname']
175         context['authority'] = config.get('authority',"Unknown Authority")
176         context['user_private_key'] = account_priv_key
177         
178         # XXX This is repeated in all pages
179         # more general variables expected in the template
180         context['title'] = 'Platforms connected to MySlice'
181         # the menu items on the top
182         context['topmenu_items'] = topmenu_items('My Account', self.request)
183         # so we can sho who is logged
184         context['username'] = the_user(self.request)
185 #        context ['firstname'] = config['firstname']
186         #context.update(page.prelude_env())
187         return context
188
189
190 @login_required
191 #my_acc form value processing
192 def account_process(request):
193     user_query  = Query().get('local:user').select('password','config')
194     user_details = execute_query(request, user_query)
195     
196     account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
197     account_details = execute_query(request, account_query)
198
199     platform_query  = Query().get('local:platform').select('platform_id','platform')
200     platform_details = execute_query(request, platform_query)
201
202    # for account_detail in account_details:
203     #    if account_detail['platform_id'] == 5: 
204      #       account_config = json.loads(account_detail['config'])
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     # add reference platforms       
374     elif 'add_fuseco' in request.POST:
375         # The recipients are the PI of the authority
376         #recipients = authority_get_pi_emails(request, authority_hrn)
377         recipients = ["support@myslice.info"] 
378         requester = request.user # current user
379         sender = 'yasin.upmc@gmail.com' # the server email
380         msg = "OneLab user %s requested account in fuseco Platform" % requester
381         send_mail("Onelab user %s requested an account in Fuseco"%requester , msg, sender, recipients)
382         messages.info(request, 'Request to get access on Fuseco platform received. Please wait for PI\'s reply.')
383         return HttpResponseRedirect("/portal/account/")
384
385     elif 'add_ple' in request.POST:
386         # The recipients are the PI of the authority
387         #recipients = authority_get_pi_emails(request, authority_hrn)
388         recipients = ["support@myslice.info"] 
389         requester = request.user # current user
390         sender = 'yasin.upmc@gmail.com' # the server email
391         msg = "OneLab user %s requested account in fuseco Platform" % requester
392         send_mail("Onelab user %s requested an account in PLE"%requester , msg, sender, recipients)
393         messages.info(request, 'Request to get access on PLE platform received. Please wait for PI\'s reply.')
394         return HttpResponseRedirect("/portal/account/")
395
396     elif 'add_omf' in request.POST:
397         # The recipients are the PI of the authority
398         #recipients = authority_get_pi_emails(request, authority_hrn)
399         recipients = ["support@myslice.info"]
400         requester = request.user # current user
401         sender = 'yasin.upmc@gmail.com' # the server email
402         msg = "OneLab user %s requested account in omf:nitos Platform" % requester
403         send_mail("Onelab user %s requested an account in OMF:NITOS"%requester , msg, sender, recipients)
404         messages.info(request, 'Request to get access on OMF:NITOS platform received. Please wait for PI\'s reply.')
405         return HttpResponseRedirect("/portal/account/")
406
407     elif 'add_wilab' in request.POST:
408         # The recipients are the PI of the authority
409         #recipients = authority_get_pi_emails(request, authority_hrn)
410         recipients = ["support@myslice.info"]
411         requester = request.user # current user
412         sender = 'yasin.upmc@gmail.com' # the server email
413         msg = "OneLab user %s requested account in Wilab Platform" % requester
414         send_mail("Onelab user %s requested an account in Wilab"%requester , msg, sender, recipients)
415         messages.info(request, 'Request to get access on Wilab platform received. Please wait for PI\'s reply.')
416         return HttpResponseRedirect("/portal/account/")
417
418     elif 'iotlab' in request.POST:
419         # The recipients are the PI of the authority
420         #recipients = authority_get_pi_emails(request, authority_hrn)
421         recipients = ["support@myslice.info"]
422         requester = request.user # current user
423         sender = 'yasin.upmc@gmail.com' # the server email
424         msg = "OneLab user %s requested account in IOTLab Platform" % requester
425         send_mail("Onelab user %s requested an account in IOTLab"%requester , msg, sender, recipients)
426         messages.info(request, 'Request to get access on IOTLab platform received. Please wait for PI\'s reply.')
427         return HttpResponseRedirect("/portal/account/")
428
429     #delete reference platoforms
430   
431     else:
432         messages.info(request, 'Under Construction. Please try again later!')
433         return HttpResponseRedirect("/portal/account/")
434
435