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