MyAcc: look & fill
[myslice.git] / portal / views.py
1 # -*- coding: utf-8 -*-
2 #
3 # portal/views.py: views for the portal application
4 # This file is part of the Manifold project.
5 #
6 # Authors:
7 #   Jordan AugĂ© <jordan.auge@lip6.fr>
8 #   Mohammed Yasin Rahman <mohammed-yasin.rahman@lip6.fr>
9 # Copyright 2013, UPMC Sorbonne UniversitĂ©s / LIP6
10 #
11 # This program is free software; you can redistribute it and/or modify it under
12 # the terms of the GNU General Public License as published by the Free Software
13 # Foundation; either version 3, or (at your option) any later version.
14
15 # This program is distributed in the hope that it will be useful, but WITHOUT
16 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 # FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
18 # details.
19
20 # You should have received a copy of the GNU General Public License along with
21 # this program; see the file COPYING.  If not, write to the Free Software
22 # Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23
24 import json
25
26 from django.http                import HttpResponseRedirect, HttpResponse
27 from django.shortcuts           import render
28 from django.template.loader     import render_to_string
29
30 from unfold.loginrequired       import FreeAccessView
31 from ui.topmenu                 import topmenu_items_live, the_user
32
33 from portal.event               import Event
34 # presview is put in observation for now
35 #from plugins.pres_view          import PresView
36 from plugins.raw                import Raw
37
38 # these seem totally unused for now
39 #from portal.util                import RegistrationView, ActivationView
40
41 from portal.models              import PendingUser, PendingSlice
42 from portal.actions             import get_request_by_authority
43 from manifold.manifoldapi       import execute_query
44 from manifold.core.query        import Query
45 from unfold.page                import Page
46
47 # NOTE
48 # initially all the portal views were defined in this single file
49 # all the other ones have now migrated into separate classes/files for more convenience
50 # I'm leaving these ones here for now as I could not exactly figure what the purpose was 
51 # (i.e. what the correct name should be, as presviewview was a bit cryptic)
52 class PresViewView(FreeAccessView):
53     template_name = "view-unfold1.html"
54
55     def get_context_data(self, **kwargs):
56
57         page = Page(self.request)
58
59 #        pres_view = PresView(page = page)
60         pres_view = Raw(page = page,html="<h1>PresView needs to be integrated</h1>")
61
62         context = super(PresViewView, self).get_context_data(**kwargs)
63
64         #context['ALL_STATIC'] = "all_static"
65         context['unfold_main'] = pres_view.render(self.request)
66
67         # XXX This is repeated in all pages
68         # more general variables expected in the template
69         context['title'] = 'Test view that combines various plugins'
70         # the menu items on the top
71         context['topmenu_items'] = topmenu_items_live('PresView', page)
72         # so we can sho who is logged
73         context['username'] = the_user(self.request)
74
75         prelude_env = page.prelude_env()
76         context.update(prelude_env)
77
78         return context
79
80 def json_me(config_file,type):
81     json_answer = ''
82     for ligne in config_file:
83         if not ligne.startswith('#'):
84             args = ligne.split(';')
85             json_answer += str('{ "name": "' + args[0] + '" ,"id":"' + args[1]  + '" ,"descriptif":"' + args[2]+'"')
86             if type!="dynamic":
87                 json_answer += str(',"contraints":')
88                 if args[3]=="":
89                     json_answer += str('""')
90                 else:
91                     json_answer += str(args[3])
92             json_answer += str('},')
93     return json_answer[:-1]
94
95
96 DIR = '/var/myslice/'
97 STATIC = '%s/config_method_static' % DIR
98 DYNAMIC = '%s/config_method_dynamic' % DIR
99 ANIMATION = '%s/config_method_animation' % DIR
100
101 def pres_view_methods(request, type):
102
103     if type ==None:
104         return 0
105     elif type =="static":
106         config = open(STATIC, "r")
107         json_answer = str('{ "options": [')
108         json_answer += str(json_me(config,"static"))
109         json_answer += str('] }')
110         config.close()
111     elif type =="dynamic":
112         config = open(DYNAMIC, "r")
113         json_answer = str('{ "options": [')
114         json_answer += str(json_me(config,"dynamic"))
115         json_answer += str('] }')
116         config.close()
117     elif type =="animation":
118         config = open(ANIMATION, "r")
119         json_answer = str('{ "options": [')
120         json_answer += str(json_me(config,"animation"))
121         json_answer += str('] }')
122         config.close()
123     elif type =="all":
124         config = open(STATIC, "r")
125         json_answer = str('{ "static": [')
126         json_answer += str(json_me(config,"static"))
127         json_answer += str('],')
128         json_answer += str('"dynamic": [')
129         config.close()
130         config = open(DYNAMIC, "r")
131         json_answer += str(json_me(config,"dynamic"))
132         json_answer += str('],')
133         json_answer += str('"animation": [')
134         config.close()
135         config = open(ANIMATION, "r")
136         json_answer += str(json_me(config,"animation"))
137         json_answer += str('] }')
138         config.close()
139     else:
140         return 0
141     return HttpResponse (json_answer, mimetype="application/json")
142
143 def pres_view_animation(request, constraints, id):
144
145 # sites crees depuis 2008
146 # static.py?contraints=']date_created':1262325600&id='name_id"'
147
148     # method = request.getvalue('method') #ex : GetSites
149     #constraints = "']date_created':1262325600"
150     #id = "2"
151
152     if id == None:
153         return 0
154
155     # method = 'GetSites'#request.getvalue('method') #ex : GetSites
156     # constraints = {}#request.getvalue('constraints') // nul = {}
157     # response_field = "'site_id','name','date_created'"#request.getvalue('response_field')
158
159     config_file = open(ANIMATION, "r")
160     for ligne in config_file:
161         if not ligne.startswith('#'):
162             ligne = ligne.split('\n')
163             first = ligne[0].split(';')
164             if (str(first[1]) == str(id)):
165                 save = first
166     config_file.close()
167
168     #Les print_method, print_option sont definis par le client (js)
169     #Les animations acceptent que les connexions anonymous
170     # args = "postmsg;animation;;;anonymous;https://www.planet-lab.eu/PLCAPI/;"
171     args = ";;"+str(save[8])+";"+str(save[9])+";anonymous;"+str(save[5])+";"+str(save[6])+";{"+str(constraints)+"};"+str(save[7])+";"
172
173
174     #Creation d'un objet event
175     event = Event(args)
176     cmd = [{"params": {
177             "data": {
178                 "print_options": event.print_options,
179                 "print_method": event.print_method,
180                 "message": event.data
181             }
182         }
183     }]
184
185     json_answer = json.dumps(cmd)
186     return HttpResponse (json_answer, mimetype="application/json")
187
188 def pres_view_static(request, constraints, id):
189     #constraints = "']date_created':1262325600"
190     #id = "2"
191
192     # method = 'GetSites'#request.getvalue('method') #ex : GetSites
193     # constraints = {}#request.getvalue('constraints') // nul = {}
194     # response_field = "'site_id','name','date_created'"#request.getvalue('response_field')
195
196     config_file = open(STATIC, "r")
197     for ligne in config_file:
198         if not ligne.startswith('#'):
199             ligne = ligne.split('\n')
200             first = ligne[0].split(';')
201             if (str(first[1]) == str(id)):
202                 save = first
203     config_file.close()
204
205     #Les print_method, print_option sont definis par le client (js)
206     #Les animations acceptent que les connexions anonymous
207     # args = "postmsg;animation;;;anonymous;https://www.planet-lab.eu/PLCAPI/;"
208     args = ";;"+str(save[8])+";"+str(save[9])+";anonymous;"+str(save[5])+";"+str(save[6])+";{"+str(constraints)+"};"+str(save[7])+";"
209
210
211     #Creation d'un objet event
212     event = Event(args)
213     cmd = [{"params": {
214             "data": {
215                 "print_options": event.print_options,
216                 "print_method": event.print_method,
217                 "message": event.data
218             }
219         }
220     }]
221
222     json_answer = json.dumps(cmd)
223     return HttpResponse (json_answer, mimetype="application/json")
224
225 class ValidatePendingView(FreeAccessView):
226     template_name = "validate_pending.html"
227
228     def get_context_data(self, **kwargs):
229         # We might have slices on different registries with different user accounts 
230         # We note that this portal could be specific to a given registry, to which we register users, but i'm not sure that simplifies things
231         # Different registries mean different identities, unless we identify via SFA HRN or have associated the user email to a single hrn
232
233         #messages.info(self.request, 'You have logged in')
234         page = Page(self.request)
235
236         ctx_my_authorities = {}
237         ctx_delegation_authorities = {}
238
239
240         # The user need to be logged in
241         if the_user(self.request):
242             # Who can a PI validate:
243             # His own authorities + those he has credentials for.
244             # In MySlice we need to look at credentials also.
245             
246
247             # XXX This will have to be asynchroneous. Need to implement barriers,
248             # for now it will be sufficient to have it working statically
249
250             # get user_id to later on query accounts
251             # XXX Having real query plan on local tables would simplify all this
252             # XXX $user_email is still not available for local tables
253             #user_query = Query().get('local:user').filter_by('email', '==', '$user_email').select('user_id')
254             user_query = Query().get('local:user').filter_by('email', '==', the_user(self.request)).select('user_id')
255             user, = execute_query(self.request, user_query)
256             user_id = user['user_id']
257
258             # Query manifold to learn about available SFA platforms for more information
259             # In general we will at least have the portal
260             # For now we are considering all registries
261             all_authorities = []
262             platform_ids = []
263             sfa_platforms_query = Query().get('local:platform').filter_by('gateway_type', '==', 'sfa').select('platform_id', 'platform', 'auth_type')
264             sfa_platforms = execute_query(self.request, sfa_platforms_query)
265             for sfa_platform in sfa_platforms:
266                 print "SFA PLATFORM > ", sfa_platform['platform']
267                 if not 'auth_type' in sfa_platform:
268                     continue
269                 auth = sfa_platform['auth_type']
270                 if not auth in all_authorities:
271                     all_authorities.append(auth)
272                 platform_ids.append(sfa_platform['platform_id'])
273
274             print "W: Hardcoding platform myslice"
275             # There has been a tweak on how new platforms are referencing a
276             # so-called 'myslice' platform for storing authentication tokens.
277             # XXX This has to be removed in final versions.
278             myslice_platforms_query = Query().get('local:platform').filter_by('platform', '==', 'myslice').select('platform_id')
279             myslice_platforms = execute_query(self.request, myslice_platforms_query)
280             if myslice_platforms:
281                 myslice_platform, = myslice_platforms
282                 platform_ids.append(myslice_platform['platform_id'])
283
284             # We can check on which the user has authoritity credentials = PI rights
285             credential_authorities = set()
286             credential_authorities_expired = set()
287
288             # User account on these registries
289             user_accounts_query = Query.get('local:account').filter_by('user_id', '==', user_id).filter_by('platform_id', 'included', platform_ids).select('auth_type', 'config')
290             user_accounts = execute_query(self.request, user_accounts_query)
291             #print "=" * 80
292             #print user_accounts
293             #print "=" * 80
294             for user_account in user_accounts:
295
296                 print "USER ACCOUNT", user_account
297                 if user_account['auth_type'] == 'reference':
298                     continue # we hardcoded the myslice platform...
299
300                 config = json.loads(user_account['config'])
301                 creds = []
302                 print "CONFIG KEYS", config.keys()
303                 if 'authority_credentials' in config:
304                     print "***", config['authority_credentials'].keys()
305                     for authority_hrn, credential in config['authority_credentials'].items():
306                         #if credential is not expired:
307                         credential_authorities.add(authority_hrn)
308                         #else
309                         #    credential_authorities_expired.add(authority_hrn)
310                 if 'delegated_authority_credentials' in config:
311                     print "***", config['delegated_authority_credentials'].keys()
312                     for authority_hrn, credential in config['delegated_authority_credentials'].items():
313                         #if credential is not expired:
314                         credential_authorities.add(authority_hrn)
315                         #else
316                         #    credential_authorities_expired.add(authority_hrn)
317
318             print 'credential_authorities =', credential_authorities
319             print 'credential_authorities_expired =', credential_authorities_expired
320
321             # ** Where am I a PI **
322             # For this we need to ask SFA (of all authorities) = PI function
323             pi_authorities_query = Query.get('user').filter_by('user_hrn', '==', '$user_hrn').select('pi_authorities')
324             pi_authorities_tmp = execute_query(self.request, pi_authorities_query)
325             pi_authorities = set()
326             for pa in pi_authorities_tmp:
327                 pi_authorities |= set(pa['pi_authorities'])
328
329             print "pi_authorities =", pi_authorities
330             
331             # My authorities + I have a credential
332             pi_credential_authorities = pi_authorities & credential_authorities
333             pi_no_credential_authorities = pi_authorities - credential_authorities - credential_authorities_expired
334             pi_expired_credential_authorities = pi_authorities & credential_authorities_expired
335             # Authorities I've been delegated PI rights
336             pi_delegation_credential_authorities = credential_authorities - pi_authorities
337             pi_delegation_expired_authorities = credential_authorities_expired - pi_authorities
338
339             print "pi_credential_authorities =", pi_credential_authorities
340             print "pi_no_credential_authorities =", pi_no_credential_authorities
341             print "pi_expired_credential_authorities =", pi_expired_credential_authorities
342             print "pi_delegation_credential_authorities = ", pi_delegation_credential_authorities
343             print "pi_delegation_expired_authorities = ", pi_delegation_expired_authorities
344
345             # Summary intermediary
346             pi_my_authorities = pi_credential_authorities | pi_no_credential_authorities | pi_expired_credential_authorities
347             pi_delegation_authorities = pi_delegation_credential_authorities | pi_delegation_expired_authorities
348
349             print "--"
350             print "pi_my_authorities = ", pi_my_authorities
351             print "pi_delegation_authorities = ", pi_delegation_authorities
352
353             # Summary all
354             queried_pending_authorities = pi_my_authorities | pi_delegation_authorities
355             print "----"
356             print "queried_pending_authorities = ", queried_pending_authorities
357
358             requests = get_request_by_authority(queried_pending_authorities)
359             for request in requests:
360                 auth_hrn = request['authority_hrn']
361
362                 if auth_hrn in pi_my_authorities:
363                     dest = ctx_my_authorities
364
365                     # define the css class
366                     if auth_hrn in pi_credential_authorities:
367                         request['allowed'] = 'allowed'
368                     elif auth_hrn in pi_expired_credential_authorities:
369                         request['allowed'] = 'expired'
370                     else: # pi_no_credential_authorities
371                         request['allowed'] = 'denied'
372
373                 elif auth_hrn in pi_delegation_authorities:
374                     dest = ctx_delegation_authorities
375
376                     if auth_hrn in pi_delegation_credential_authorities:
377                         request['allowed'] = 'allowed'
378                     else: # pi_delegation_expired_authorities
379                         request['allowed'] = 'expired'
380
381                 else:
382                     continue
383
384                 if not auth_hrn in dest:
385                     dest[auth_hrn] = []
386                 dest[auth_hrn].append(request) 
387         
388         context = super(ValidatePendingView, self).get_context_data(**kwargs)
389         context['my_authorities']   = ctx_my_authorities
390         context['delegation_authorities'] = ctx_delegation_authorities
391
392         # XXX This is repeated in all pages
393         # more general variables expected in the template
394         context['title'] = 'Test view that combines various plugins'
395         # the menu items on the top
396         context['topmenu_items'] = topmenu_items('Validation', self.request) 
397         # so we can sho who is logged
398         context['username'] = the_user(self.request) 
399
400         # XXX We need to prepare the page for queries
401         #context.update(page.prelude_env())
402
403         return context