All credentials visible
[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'] and platform_detail['disabled']==0:
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         for platform in platform_access_list:
148             total_platform_list.remove(platform)
149         # we could use zip. this one is used if columns have unequal rows 
150         platform_list = [{'platform_no_access': t[0]}
151             for t in itertools.izip_longest(total_platform_list)]
152
153
154         context = super(AccountView, self).get_context_data(**kwargs)
155         context['data'] = lst
156         context['ref_acc'] = secondary_list
157         context['platform_list'] = platform_list
158         context['my_slices'] = my_slices
159         context['my_auths'] = my_auths
160         context['person']   = self.request.user
161         context['firstname'] = config.get('firstname',"?")
162         context['lastname'] = config.get('lastname',"?")
163         context['fullname'] = context['firstname'] +' '+ context['lastname']
164         context['authority'] = config.get('authority',"Unknown Authority")
165         context['user_private_key'] = account_priv_key
166         
167         # XXX This is repeated in all pages
168         # more general variables expected in the template
169         context['title'] = 'Platforms connected to MySlice'
170         # the menu items on the top
171         context['topmenu_items'] = topmenu_items('My Account', self.request)
172         # so we can sho who is logged
173         context['username'] = the_user(self.request)
174 #        context ['firstname'] = config['firstname']
175         #context.update(page.prelude_env())
176         return context
177
178
179 @login_required
180 #my_acc form value processing
181 def account_process(request):
182     user_query  = Query().get('local:user').select('password','config')
183     user_details = execute_query(request, user_query)
184     
185     account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
186     account_details = execute_query(request, account_query)
187
188     platform_query  = Query().get('local:platform').select('platform_id','platform')
189     platform_details = execute_query(request, platform_query)
190
191    # for account_detail in account_details:
192     #    if account_detail['platform_id'] == 5: 
193      #       account_config = json.loads(account_detail['config'])
194
195     if 'submit_name' in request.POST:
196         edited_first_name =  request.POST['fname']
197         edited_last_name =  request.POST['lname']
198         
199         config={}
200         for user_config in user_details:
201         #email = user_detail['email']
202             if user_config['config']:
203                 config = json.loads(user_config['config'])
204                 config['firstname'] = edited_first_name
205                 config['lastname'] = edited_last_name
206                 config['authority'] = config.get('authority','Unknown Authority')
207                 updated_config = json.dumps(config)
208                 user_params = {'config': updated_config}
209             else: # it's needed if the config is empty 
210                 user_config['config']= '{"firstname":"' + edited_first_name + '", "lastname":"'+ edited_last_name + '", "authority": "Unknown Authority"}'
211                 user_params = {'config': user_config['config']} 
212         # updating config local:user in manifold       
213         #user_params = { 'config': updated_config}
214         manifold_update_user(request,user_params)
215         # this will be depricated, we will show the success msg in same page
216 #        return HttpResponse('Sucess: First Name and Last Name Updated!')
217         # Redirect to same page with success message
218         messages.success(request, 'Sucess: First Name and Last Name Updated.')
219         return HttpResponseRedirect("/portal/account/")       
220     
221     elif 'submit_pass' in request.POST:
222         edited_password = request.POST['password']
223         
224         for user_pass in user_details:
225             user_pass['password'] = edited_password
226         #updating password in local:user
227         user_params = { 'password': user_pass['password']}
228         manifold_update_user(request,user_params)
229 #        return HttpResponse('Success: Password Changed!!')
230         messages.success(request, 'Sucess: Password Updated.')
231         return HttpResponseRedirect("/portal/account/")
232
233 # XXX TODO: Factorize with portal/registrationview.py
234
235     elif 'generate' in request.POST:
236         for account_detail in account_details:
237             for platform_detail in platform_details:
238                 if platform_detail['platform_id'] == account_detail['platform_id']:
239                     if 'myslice' in platform_detail['platform']:
240                         from Crypto.PublicKey import RSA
241                         private = RSA.generate(1024)
242                         private_key = json.dumps(private.exportKey())
243                         public  = private.publickey()
244                         public_key = json.dumps(public.exportKey(format='OpenSSH'))
245                         # Generate public and private keys using SFA Library
246 #                        from sfa.trust.certificate  import Keypair
247 #                        k = Keypair(create=True)
248 #                        public_key = k.get_pubkey_string()
249 #                        private_key = k.as_pem()
250 #                        private_key = ''.join(private_key.split())
251 #                        public_key = "ssh-rsa " + public_key
252                         # now we overwrite the config field with keypair
253                         # once there will be user_hrn, we need to keep user_hrn and change only the keypair
254                         # see submit_name section for implementing this    
255 #                       keypair = re.sub("\r", "", keypair)
256 #                       keypair = re.sub("\n", "\\n", keypair)
257 #                       #keypair = keypair.rstrip('\r\n')
258 #                       keypair = ''.join(keypair.split())
259                         # updating maniolf local:account table
260                         account_config = json.loads(account_detail['config'])
261                         # preserving user_hrn
262                         user_hrn = account_config.get('user_hrn','N/A')
263                         keypair = '{"user_public_key":'+ public_key + ', "user_private_key":'+ private_key + ', "user_hrn":"'+ user_hrn + '"}'
264                         updated_config = json.dumps(account_config) 
265
266                         user_params = { 'config': keypair, 'auth_type':'managed'}
267                         manifold_update_account(request,user_params)
268                         messages.success(request, 'Sucess: New Keypair Generated!')
269                         return HttpResponseRedirect("/portal/account/")
270         else:
271             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
272             return HttpResponseRedirect("/portal/account/")
273                        
274     elif 'upload_key' in request.POST:
275         for account_detail in account_details:
276             for platform_detail in platform_details:
277                 if platform_detail['platform_id'] == account_detail['platform_id']:
278                     if 'myslice' in platform_detail['platform']:
279                         up_file = request.FILES['pubkey']
280                         file_content =  up_file.read()
281                         file_name = up_file.name
282                         file_extension = os.path.splitext(file_name)[1] 
283                         allowed_extension =  ['.pub','.txt']
284                         if file_extension in allowed_extension and re.search(r'ssh-rsa',file_content):
285                             account_config = json.loads(account_detail['config'])
286                             # preserving user_hrn
287                             user_hrn = account_config.get('user_hrn','N/A')
288                             file_content = '{"user_public_key":"'+ file_content + '", "user_hrn":"'+ user_hrn +'"}'
289                             #file_content = re.sub("\r", "", file_content)
290                             #file_content = re.sub("\n", "\\n",file_content)
291                             file_content = ''.join(file_content.split())
292                             #update manifold local:account table
293                             user_params = { 'config': file_content, 'auth_type':'user'}
294                             manifold_update_account(request,user_params)
295                             messages.success(request, 'Publickey uploaded! Please delegate your credentials using SFA: http://trac.myslice.info/wiki/DelegatingCredentials')
296                             return HttpResponseRedirect("/portal/account/")
297                         else:
298                             messages.error(request, 'RSA key error: Please upload a valid RSA public key [.txt or .pub].')
299                             return HttpResponseRedirect("/portal/account/")
300         else:
301             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
302             return HttpResponseRedirect("/portal/account/")
303
304     elif 'dl_pubkey' in request.POST:
305         for account_detail in account_details:
306             for platform_detail in platform_details:
307                 if platform_detail['platform_id'] == account_detail['platform_id']:
308                     if 'myslice' in platform_detail['platform']:
309                         account_config = json.loads(account_detail['config'])
310                         public_key = account_config['user_public_key'] 
311                         response = HttpResponse(public_key, content_type='text/plain')
312                         response['Content-Disposition'] = 'attachment; filename="pubkey.txt"'
313                         return response
314                         break
315         else:
316             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
317             return HttpResponseRedirect("/portal/account/")
318                
319     elif 'dl_pkey' in request.POST:
320         for account_detail in account_details:
321             for platform_detail in platform_details:
322                 if platform_detail['platform_id'] == account_detail['platform_id']:
323                     if 'myslice' in platform_detail['platform']:
324                         account_config = json.loads(account_detail['config'])
325                         if 'user_private_key' in account_config:
326                             private_key = account_config['user_private_key']
327                             response = HttpResponse(private_key, content_type='text/plain')
328                             response['Content-Disposition'] = 'attachment; filename="privkey.txt"'
329                             return response
330                         else:
331                             messages.error(request, 'Download error: Private key is not stored in the server')
332                             return HttpResponseRedirect("/portal/account/")
333
334         else:
335             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
336             return HttpResponseRedirect("/portal/account/")
337     
338     elif 'delete' in request.POST:
339         for account_detail in account_details:
340             for platform_detail in platform_details:
341                 if platform_detail['platform_id'] == account_detail['platform_id']:
342                     if 'myslice' in platform_detail['platform']:
343                         account_config = json.loads(account_detail['config'])
344                         if 'user_private_key' in account_config:
345                             for key in account_config.keys():
346                                 if key== 'user_private_key':    
347                                     del account_config[key]
348                                 
349                             updated_config = json.dumps(account_config)
350                             user_params = { 'config': updated_config, 'auth_type':'user'}
351                             manifold_update_account(request,user_params)
352                             messages.success(request, 'Private Key deleted. You need to delegate credentials manually once it expires.')
353                             return HttpResponseRedirect("/portal/account/")
354                         else:
355                             messages.error(request, 'Delete error: Private key is not stored in the server')
356                             return HttpResponseRedirect("/portal/account/")
357                            
358         else:
359             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')    
360             return HttpResponseRedirect("/portal/account/")
361         
362     elif 'fuseco' in request.POST:
363         # The recipients are the PI of the authority
364         #recipients = authority_get_pi_emails(request, authority_hrn)
365         recipients = ["support@myslice.info"] 
366         requester = request.user # current user
367         sender = 'yasin.upmc@gmail.com' # the server email
368         msg = "OneLab user %s requested account in fuseco Platform" % requester
369         send_mail("Onelab user %s requested an account in Fuseco"%requester , msg, sender, recipients)
370         messages.info(request, 'Request to get access on Fuseco platform received. Please wait for PI\'s reply.')
371         return HttpResponseRedirect("/portal/account/")
372
373     elif 'ple' in request.POST:
374         # The recipients are the PI of the authority
375         #recipients = authority_get_pi_emails(request, authority_hrn)
376         recipients = ["support@myslice.info"] 
377         requester = request.user # current user
378         sender = 'yasin.upmc@gmail.com' # the server email
379         msg = "OneLab user %s requested account in fuseco Platform" % requester
380         send_mail("Onelab user %s requested an account in PLE"%requester , msg, sender, recipients)
381         messages.info(request, 'Request to get access on PLE platform received. Please wait for PI\'s reply.')
382         return HttpResponseRedirect("/portal/account/")
383
384     elif 'omf' in request.POST:
385         # The recipients are the PI of the authority
386         #recipients = authority_get_pi_emails(request, authority_hrn)
387         recipients = ["support@myslice.info"]
388         requester = request.user # current user
389         sender = 'yasin.upmc@gmail.com' # the server email
390         msg = "OneLab user %s requested account in omf:nitos Platform" % requester
391         send_mail("Onelab user %s requested an account in OMF:NITOS"%requester , msg, sender, recipients)
392         messages.info(request, 'Request to get access on OMF:NITOS platform received. Please wait for PI\'s reply.')
393         return HttpResponseRedirect("/portal/account/")
394
395     elif 'wilab' in request.POST:
396         # The recipients are the PI of the authority
397         #recipients = authority_get_pi_emails(request, authority_hrn)
398         recipients = ["support@myslice.info"]
399         requester = request.user # current user
400         sender = 'yasin.upmc@gmail.com' # the server email
401         msg = "OneLab user %s requested account in Wilab Platform" % requester
402         send_mail("Onelab user %s requested an account in Wilab"%requester , msg, sender, recipients)
403         messages.info(request, 'Request to get access on Wilab platform received. Please wait for PI\'s reply.')
404         return HttpResponseRedirect("/portal/account/")
405
406     elif 'iotlab' in request.POST:
407         # The recipients are the PI of the authority
408         #recipients = authority_get_pi_emails(request, authority_hrn)
409         recipients = ["support@myslice.info"]
410         requester = request.user # current user
411         sender = 'yasin.upmc@gmail.com' # the server email
412         msg = "OneLab user %s requested account in IOTLab Platform" % requester
413         send_mail("Onelab user %s requested an account in IOTLab"%requester , msg, sender, recipients)
414         messages.info(request, 'Request to get access on IOTLab platform received. Please wait for PI\'s reply.')
415         return HttpResponseRedirect("/portal/account/")
416   
417     else:
418         messages.info(request, 'Under Construction. Please try again later!')
419         return HttpResponseRedirect("/portal/account/")
420
421