Merge branch 'fibre' of ssh://git.onelab.eu/git/myslice into fibre
[unfold.git] / portal / validationview.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 #   Loic Baron <loic.baron@lip6.fr>
10 # Copyright 2013, UPMC Sorbonne UniversitĂ©s / LIP6
11 #
12 # This program is free software; you can redistribute it and/or modify it under
13 # the terms of the GNU General Public License as published by the Free Software
14 # Foundation; either version 3, or (at your option) any later version.
15
16 # This program is distributed in the hope that it will be useful, but WITHOUT
17 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18 # FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
19 # details.
20
21 # You should have received a copy of the GNU General Public License along with
22 # this program; see the file COPYING.  If not, write to the Free Software
23 # Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24
25 import json
26
27 from django.http                import HttpResponseRedirect, HttpResponse
28 from django.shortcuts           import render
29 from django.template.loader     import render_to_string
30
31 from unfold.loginrequired       import LoginRequiredAutoLogoutView
32 from ui.topmenu                 import topmenu_items_live, the_user
33
34 from portal.event               import Event
35 # presview is put in observation for now
36 #from plugins.pres_view          import PresView
37 from plugins.raw                import Raw
38
39 # these seem totally unused for now
40 #from portal.util                import RegistrationView, ActivationView
41
42 from portal.models              import PendingUser, PendingSlice
43 from portal.actions             import get_requests
44 from manifoldapi.manifoldapi    import execute_query
45 from manifold.core.query        import Query
46 from unfold.page                import Page
47 from myslice.theme import ThemeView
48
49 class ValidatePendingView(LoginRequiredAutoLogoutView, ThemeView):
50     template_name = "validate_pending.html"
51
52     def get_context_data(self, **kwargs):
53         pi = ""
54         # We might have slices on different registries with different user accounts 
55         # 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
56         # Different registries mean different identities, unless we identify via SFA HRN or have associated the user email to a single hrn
57
58         #messages.info(self.request, 'You have logged in')
59         page = Page(self.request)
60
61         ctx_my_authorities = {}
62         ctx_delegation_authorities = {}
63         ctx_sub_authorities = {}
64         dest = {}
65
66
67         # The user need to be logged in
68         if the_user(self.request):
69             # Who can a PI validate:
70             # His own authorities + those he has credentials for.
71             # In MySlice we need to look at credentials also.
72             
73
74             # XXX This will have to be asynchroneous. Need to implement barriers,
75             # for now it will be sufficient to have it working statically
76
77             # get user_id to later on query accounts
78             # XXX Having real query plan on local tables would simplify all this
79             # XXX $user_email is still not available for local tables
80             #user_query = Query().get('local:user').filter_by('email', '==', '$user_email').select('user_id')
81             user_query = Query().get('local:user').filter_by('email', '==', the_user(self.request)).select('user_id')
82             user, = execute_query(self.request, user_query)
83             user_id = user['user_id']
84
85             # Query manifold to learn about available SFA platforms for more information
86             # In general we will at least have the portal
87             # For now we are considering all registries
88             all_authorities = []
89             platform_ids = []
90             sfa_platforms_query = Query().get('local:platform').filter_by('gateway_type', '==', 'sfa').select('platform_id', 'platform', 'auth_type')
91             sfa_platforms = execute_query(self.request, sfa_platforms_query)
92             for sfa_platform in sfa_platforms:
93                 print "SFA PLATFORM > ", sfa_platform['platform']
94                 if not 'auth_type' in sfa_platform:
95                     continue
96                 auth = sfa_platform['auth_type']
97                 if not auth in all_authorities:
98                     all_authorities.append(auth)
99                 platform_ids.append(sfa_platform['platform_id'])
100
101             print "W: Hardcoding platform myslice"
102             # There has been a tweak on how new platforms are referencing a
103             # so-called 'myslice' platform for storing authentication tokens.
104             # XXX This has to be removed in final versions.
105             myslice_platforms_query = Query().get('local:platform').filter_by('platform', '==', 'myslice').select('platform_id')
106             myslice_platforms = execute_query(self.request, myslice_platforms_query)
107             if myslice_platforms:
108                 myslice_platform, = myslice_platforms
109                 platform_ids.append(myslice_platform['platform_id'])
110
111             # We can check on which the user has authoritity credentials = PI rights
112             credential_authorities = set()
113             credential_authorities_expired = set()
114
115             # User account on these registries
116             user_accounts_query = Query.get('local:account').filter_by('user_id', '==', user_id).filter_by('platform_id', 'included', platform_ids).select('auth_type', 'config')
117             user_accounts = execute_query(self.request, user_accounts_query)
118             #print "=" * 80
119             #print user_accounts
120             #print "=" * 80
121             for user_account in user_accounts:
122
123                 print "USER ACCOUNT", user_account
124                 if user_account['auth_type'] == 'reference':
125                     continue # we hardcoded the myslice platform...
126
127                 config = json.loads(user_account['config'])
128                 creds = []
129                 print "CONFIG KEYS", config.keys()
130                 if 'authority_credentials' in config:
131                     print "***", config['authority_credentials'].keys()
132                     for authority_hrn, credential in config['authority_credentials'].items():
133                         #if credential is not expired:
134                         credential_authorities.add(authority_hrn)
135                         #else
136                         #    credential_authorities_expired.add(authority_hrn)
137                 if 'delegated_authority_credentials' in config:
138                     print "***", config['delegated_authority_credentials'].keys()
139                     for authority_hrn, credential in config['delegated_authority_credentials'].items():
140                         #if credential is not expired:
141                         credential_authorities.add(authority_hrn)
142                         #else
143                         #    credential_authorities_expired.add(authority_hrn)
144
145             print 'credential_authorities =', credential_authorities
146             print 'credential_authorities_expired =', credential_authorities_expired
147
148 #            # Using cache manifold-tables to get the list of authorities faster
149 #            all_authorities_query = Query.get('authority').select('name', 'authority_hrn')
150 #            all_authorities = execute_query(self.request, all_authorities_query)
151
152             # ** Where am I a PI **
153             # For this we need to ask SFA (of all authorities) = PI function
154             pi_authorities_query = Query.get('user').filter_by('user_hrn', '==', '$user_hrn').select('pi_authorities')
155             pi_authorities_tmp = execute_query(self.request, pi_authorities_query)
156             pi_authorities = set()
157             try:
158                 for pa in pi_authorities_tmp:
159                     pi_authorities |= set(pa['pi_authorities'])
160             except:
161                 print 'No pi_authorities'
162 # TODO: exception if no parent_authority
163 #             try:
164 #                 for pa in pi_authorities_tmp:
165 #                     pi_authorities |= set(pa['pi_authorities'])
166 #             except:
167
168
169 #            # include all sub-authorities of the PI
170 #            # if PI on ple, include all sub-auths ple.upmc, ple.inria and so on...
171 #            pi_subauthorities = set()
172 #            for authority in all_authorities:
173 #                authority_hrn = authority['authority_hrn']
174 #                for my_authority in pi_authorities:
175 #                    if authority_hrn.startswith(my_authority) and authority_hrn not in pi_subauthorities:
176 #                        pi_subauthorities.add(authority_hrn)
177
178             #print "pi_authorities =", pi_authorities
179             #print "pi_subauthorities =", pi_subauthorities
180             
181             # My authorities + I have a credential
182             pi_credential_authorities = pi_authorities & credential_authorities
183             pi_no_credential_authorities = pi_authorities - credential_authorities - credential_authorities_expired
184             pi_expired_credential_authorities = pi_authorities & credential_authorities_expired
185             # Authorities I've been delegated PI rights
186             pi_delegation_credential_authorities = credential_authorities - pi_authorities
187             pi_delegation_expired_authorities = credential_authorities_expired - pi_authorities
188
189             #print "pi_credential_authorities =", pi_credential_authorities
190             #print "pi_no_credential_authorities =", pi_no_credential_authorities
191             #print "pi_expired_credential_authorities =", pi_expired_credential_authorities
192             #print "pi_delegation_credential_authorities = ", pi_delegation_credential_authorities
193             #print "pi_delegation_expired_authorities = ", pi_delegation_expired_authorities
194
195             # Summary intermediary
196             pi_my_authorities = pi_credential_authorities | pi_no_credential_authorities | pi_expired_credential_authorities
197             pi_delegation_authorities = pi_delegation_credential_authorities | pi_delegation_expired_authorities
198
199             #print "--"
200             #print "pi_my_authorities = ", pi_my_authorities
201             #print "pi_delegation_authorities = ", pi_delegation_authorities
202             #print "pi_subauthorities = ", pi_subauthorities
203
204             # Summary all
205             queried_pending_authorities = pi_my_authorities | pi_delegation_authorities #| pi_subauthorities
206             #print "----"
207             #print "queried_pending_authorities = ", queried_pending_authorities
208
209 # iterate on the requests and check if the authority matches a prefix startswith an authority on which the user is PI
210             requests = get_requests()
211 #            requests = get_requests(queried_pending_authorities)
212             for request in requests:
213                 auth_hrn = request['authority_hrn']
214                 for my_auth in pi_my_authorities: 
215                     if auth_hrn.startswith(my_auth):
216                         dest = ctx_my_authorities
217                         request['allowed'] = 'allowed'
218                 for my_auth in pi_delegation_authorities:
219                     if auth_hrn.startswith(my_auth):
220                         dest = ctx_delegation_authorities
221                         request['allowed'] = 'allowed'
222                 if auth_hrn in pi_expired_credential_authorities:
223                     request['allowed'] = 'expired'
224                 if 'allowed' not in request:
225                     request['allowed'] = 'denied'
226                #print "authority for this request", auth_hrn
227
228 #                if auth_hrn in pi_my_authorities:
229 #                    dest = ctx_my_authorities
230 #
231 #                    # define the css class
232 #                    if auth_hrn in pi_credential_authorities:
233 #                        request['allowed'] = 'allowed'
234 #                    elif auth_hrn in pi_expired_credential_authorities:
235 #                        request['allowed'] = 'expired'
236 #                    else: # pi_no_credential_authorities
237 #                        request['allowed'] = 'denied'
238 #
239 #                elif auth_hrn in pi_delegation_authorities:
240 #                    dest = ctx_delegation_authorities
241 #
242 #                    if auth_hrn in pi_delegation_credential_authorities:
243 #                        request['allowed'] = 'allowed'
244 #                    else: # pi_delegation_expired_authorities
245 #                        request['allowed'] = 'expired'
246 #
247 #                elif auth_hrn in pi_subauthorities:
248 #                    dest = ctx_sub_authorities
249 #
250 #                    if auth_hrn in pi_subauthorities:
251 #                        request['allowed'] = 'allowed'
252 #                    else: # pi_delegation_expired_authorities
253 #                        request['allowed'] = 'denied'
254 #
255 #                else:
256 #                    continue
257
258                 if not auth_hrn in dest:
259                     dest[auth_hrn] = []
260                 dest[auth_hrn].append(request)
261         
262         context = super(ValidatePendingView, self).get_context_data(**kwargs)
263         print "testing"
264         print ctx_my_authorities
265         print auth_hrn
266         context['my_authorities']   = ctx_my_authorities
267         context['sub_authorities']   = ctx_sub_authorities
268         context['delegation_authorities'] = ctx_delegation_authorities
269
270         # XXX This is repeated in all pages
271         # more general variables expected in the template
272         context['title'] = 'Test view that combines various plugins'
273         # the menu items on the top
274         context['topmenu_items'] = topmenu_items_live('Validation', page) 
275         # so we can sho who is logged
276         context['username'] = the_user(self.request) 
277         context['pi'] = "is_pi"       
278         context['theme'] = self.theme
279         context['section'] = "Requests"
280         # XXX We need to prepare the page for queries
281         #context.update(page.prelude_env())
282
283         return context