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