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