Merge branch 'fibre' of ssh://git.onelab.eu/git/myslice into fibre
[unfold.git] / portal / managementtabrequests.py
1 from django.template                 import RequestContext
2 from django.shortcuts                import render_to_response
3
4 from manifold.core.query             import Query, AnalyzedQuery
5 from manifoldapi.manifoldapi         import execute_query
6
7 from django.views.generic.base      import TemplateView
8
9 from unfold.loginrequired           import LoginRequiredView
10 from django.http                    import HttpResponse
11 from django.shortcuts               import render
12
13 from manifold.core.query            import Query, AnalyzedQuery
14 from manifoldapi.manifoldapi        import execute_query
15
16 from portal.actions                 import get_requests
17
18 from myslice.theme import ThemeView
19
20 import json
21 import ast
22
23 class ManagementRequestsView (LoginRequiredView, ThemeView):
24     template_name = "management-tab-requests.html"
25     
26     def get_context_data(self, **kwargs):
27        
28         ctx_my_authorities = {}
29         ctx_delegation_authorities = {}
30         ctx_sub_authorities = {}
31         dest = {}
32         user_username = ''
33         user_authority = ''
34
35         # The user need to be logged in
36         if (self.request.user):
37            
38             user_query = Query().get('local:user').filter_by('email', '==', self.request.user.username).select('user_id')
39             user, = execute_query(self.request, user_query)
40             user_id = user['user_id']
41             user_query = Query().get('local:user').filter_by('email', '==', self.request.user.username).select('config')
42             user, = execute_query(self.request, user_query)
43             user_config = user['config']
44             user_config = ast.literal_eval(user_config)
45             user_authority = user_config['authority']   
46             user_username = self.request.user.username
47             # Query manifold to learn about available SFA platforms for more information
48             # In general we will at least have the portal
49             # For now we are considering all registries
50             all_authorities = []
51             platform_ids = []
52             sfa_platforms_query = Query().get('local:platform').filter_by('gateway_type', '==', 'sfa').select('platform_id', 'platform', 'auth_type')
53             sfa_platforms = execute_query(self.request, sfa_platforms_query)
54             for sfa_platform in sfa_platforms:
55                 print "SFA PLATFORM > ", sfa_platform['platform']
56                 if not 'auth_type' in sfa_platform:
57                     continue
58                 auth = sfa_platform['auth_type']
59                 if not auth in all_authorities:
60                     all_authorities.append(auth)
61                 platform_ids.append(sfa_platform['platform_id'])
62
63             print "W: Hardcoding platform myslice"
64             # There has been a tweak on how new platforms are referencing a
65             # so-called 'myslice' platform for storing authentication tokens.
66             # XXX This has to be removed in final versions.
67             myslice_platforms_query = Query().get('local:platform').filter_by('platform', '==', 'myslice').select('platform_id')
68             myslice_platforms = execute_query(self.request, myslice_platforms_query)
69             if myslice_platforms:
70                 myslice_platform, = myslice_platforms
71                 platform_ids.append(myslice_platform['platform_id'])
72
73             # We can check on which the user has authoritity credentials = PI rights
74             credential_authorities = set()
75             credential_authorities_expired = set()
76
77             # User account on these registries
78             user_accounts_query = Query.get('local:account').filter_by('user_id', '==', user_id).filter_by('platform_id', 'included', platform_ids).select('auth_type', 'config')
79             user_accounts = execute_query(self.request, user_accounts_query)
80             
81             for user_account in user_accounts:
82
83                 print "USER ACCOUNT", user_account
84                 if user_account['auth_type'] == 'reference':
85                     continue # we hardcoded the myslice platform...
86
87                 config = json.loads(user_account['config'])
88                 creds = []
89                 print "CONFIG KEYS", config.keys()
90                 if 'authority_credentials' in config:
91                     print "***", config['authority_credentials'].keys()
92                     for authority_hrn, credential in config['authority_credentials'].items():
93                         credential_authorities.add(authority_hrn)
94                 if 'delegated_authority_credentials' in config:
95                     print "***", config['delegated_authority_credentials'].keys()
96                     for authority_hrn, credential in config['delegated_authority_credentials'].items():
97                         credential_authorities.add(authority_hrn)
98
99             print 'credential_authorities =', credential_authorities
100             print 'credential_authorities_expired =', credential_authorities_expired
101
102             # ** Where am I a PI **
103             # For this we need to ask SFA (of all authorities) = PI function
104             pi_authorities_query = Query.get('user').filter_by('user_hrn', '==', '$user_hrn').select('pi_authorities')
105             pi_authorities_tmp = execute_query(self.request, pi_authorities_query)
106             pi_authorities = set()
107             try:
108                 for pa in pi_authorities_tmp:
109                     pi_authorities |= set(pa['pi_authorities'])
110             except:
111                 print 'No pi_authorities'
112
113             pi_credential_authorities = pi_authorities & credential_authorities
114             pi_no_credential_authorities = pi_authorities - credential_authorities - credential_authorities_expired
115             pi_expired_credential_authorities = pi_authorities & credential_authorities_expired
116             # Authorities I've been delegated PI rights
117             pi_delegation_credential_authorities = credential_authorities - pi_authorities
118             pi_delegation_expired_authorities = credential_authorities_expired - pi_authorities
119
120             # Summary intermediary
121             pi_my_authorities = pi_credential_authorities | pi_no_credential_authorities | pi_expired_credential_authorities
122             pi_delegation_authorities = pi_delegation_credential_authorities | pi_delegation_expired_authorities
123
124             # Summary all
125             queried_pending_authorities = pi_my_authorities | pi_delegation_authorities #| pi_subauthorities
126
127             # iterate on the requests and check if the authority matches a prefix 
128             # startswith an authority on which the user is PI
129             requests = get_requests()
130             auth_hrn = ''
131             for r in requests:
132                 auth_hrn = r['authority_hrn']
133                 for my_auth in pi_my_authorities: 
134                     if auth_hrn.startswith(my_auth):
135                         dest = ctx_my_authorities
136                         r['allowed'] = 'allowed'
137                 for my_auth in pi_delegation_authorities:
138                     if auth_hrn.startswith(my_auth):
139                         dest = ctx_delegation_authorities
140                         r['allowed'] = 'allowed'
141                 if auth_hrn in pi_expired_credential_authorities:
142                     r['allowed'] = 'expired'
143                 if 'allowed' not in r:
144                     ## TEMP FIX for allowing new authority registration
145                     #r['allowed'] = 'denied'
146                     r['allowed'] = 'allowed'
147
148                 if not auth_hrn in dest:
149                     dest[auth_hrn] = []
150                 dest[auth_hrn].append(r)
151                 
152               
153 #         env = {}
154 #         env['my_authorities']   = ctx_my_authorities
155 #         env['sub_authorities']   = ctx_sub_authorities
156 #         env['delegation_authorities'] = ctx_delegation_authorities
157
158 #         # XXX This is repeated in all pages
159 #         # more general variables expected in the template
160 #         # the menu items on the top
161 #         #env['topmenu_items'] = topmenu_items_live('Validation', page) 
162 #         # so we can sho who is logged
163 #         env['username'] = request.user
164 #         env['pi'] = "is_pi"       
165 #         env['theme'] = self.theme
166 #         env['section'] = "Requests"
167 #        auth_hrn = user_authority + '.' + user_username.split("@")[1]
168             ctx_list = [ctx_my_authorities, ctx_sub_authorities, ctx_delegation_authorities]
169             for ctx in ctx_list:
170                 if ctx:
171                     for authorities in ctx:
172                         for requests in ctx[authorities]:
173                             try:
174                                 requests['object_auth'] = requests['user_hrn'].split('.')[0] + '.' + requests['user_hrn'].split('@')[1]
175                             except:
176                                 print "This object has no user_hrn"
177
178         pi_authority = user_authority + '.' + user_username.split("@")[1]
179         context = super(ManagementRequestsView, self).get_context_data(**kwargs)
180         print "testing"
181         print ctx_my_authorities
182         print auth_hrn
183         print user_username
184         print pi_authority
185         context['my_authorities']   = ctx_my_authorities
186         context['sub_authorities']   = ctx_sub_authorities
187         context['delegation_authorities'] = ctx_delegation_authorities
188
189         # XXX This is repeated in all pages
190         # more general variables expected in the template
191         context['title'] = 'Test view that combines various plugins'
192         # the menu items on the top
193         #context['topmenu_items'] = topmenu_items_live('Validation', page) 
194         # so we can sho who is logged
195         context['username'] = self.request.user 
196         context['pi'] = "is_pi"       
197         context['theme'] = self.theme
198         context['section'] = "Requests"
199         context['pi_authority'] = pi_authority
200         # XXX We need to prepare the page for queries
201         #context.update(page.prelude_env())
202
203         return context
204     
205         #return render_to_response(self.template, env, context_instance=RequestContext(request))