Merge branch 'onelab' of ssh://git.onelab.eu/git/myslice into onelab
[myslice.git] / portal / projectrequestview.py
1 from django.shortcuts           import render
2 from django.contrib.sites.models import Site
3
4 from manifold.core.query        import Query
5 from manifoldapi.manifoldapi    import execute_admin_query, execute_query
6
7 from unfold.loginrequired       import LoginRequiredAutoLogoutView
8
9 from portal.actions import create_pending_project
10
11 from portal.models import PendingProject
12
13 from myslice.theme import ThemeView
14
15 import json, time, re
16
17 class ProjectRequestView(LoginRequiredAutoLogoutView, ThemeView):
18     template_name = 'projectrequest_view.html'
19     
20     def getAuthorities(self, request):
21         authorities_query = Query.get('authority').select('name', 'authority_hrn')
22         authorities = execute_admin_query(request, authorities_query)
23         if authorities is not None:
24             authorities = sorted(authorities, key=lambda k: k['authority_hrn'])
25             authorities = sorted(authorities, key=lambda k: k['name'])
26         return authorities
27     
28     def getUserAuthority(self, request):
29         # Get user_email (XXX Would deserve to be simplified)
30         user_query  = Query().get('local:user').select('email','config')
31         user_details = execute_query(request, user_query)
32         for user_detail in user_details:
33             user_config = json.loads(user_detail['config'])
34             user_authority = user_config.get('authority','N/A')
35         return user_authority
36     
37     def getUserHrn(self, request):
38         user_hrn = None
39         
40         account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
41         account_details = execute_query(request, account_query)
42
43         platform_query  = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
44         platform_details = execute_query(request, platform_query)
45         
46         # getting user_hrn from local:account
47         for account_detail in account_details:
48             for platform_detail in platform_details:
49                 if platform_detail['platform_id'] == account_detail['platform_id']:
50                     # taking user_hrn only from myslice account
51                     # NOTE: we should later handle accounts filter_by auth_type= managed OR user
52                     if 'myslice' in platform_detail['platform']:
53                         account_config = json.loads(account_detail['config'])
54                         user_hrn = account_config.get('user_hrn','N/A')
55         return user_hrn        
56                    
57     def post(self, request):
58         return self.handle_request(request, 'POST')
59
60     def get(self, request):
61         return self.handle_request(request, 'GET')
62
63     def handle_request(self, wsgi_request, method):
64         errors = []
65         authority_hrn = None
66         authority_name = None
67         
68         user_hrn = self.getUserHrn(wsgi_request)
69         
70         authorities = self.getAuthorities(wsgi_request)
71         
72         user_authority = self.getUserAuthority(wsgi_request)
73         
74         # getting the org from authority
75         for authority in authorities:
76             if authority['authority_hrn'] == user_authority:
77                 authority_name = authority['name']
78         
79         if method == 'POST' :
80            
81             post = {
82                 'user_hrn'          : user_hrn,
83                 'authority_hrn'     : wsgi_request.POST.get('authority_name', ''),
84                 'project_name'      : wsgi_request.POST.get('project_name', ''),
85                 'purpose'           : wsgi_request.POST.get('purpose', ''),
86             }
87         
88 #             # create slice_hrn based on authority_hrn and slice_name
89 #             #             slice_name = slice_request['slice_name']
90 #             req_slice_hrn = authority_hrn + '.' + slice_name
91 #             # comparing requested slice_hrn with the existing slice_hrn 
92 #             slice_query  = Query().get('myslice:slice').select('slice_hrn','parent_authority').filter_by('parent_authority','==',authority_hrn)
93 #             slice_details_sfa = execute_admin_query(wsgi_request, slice_query)
94 #             for _slice in slice_details_sfa:
95 #                 if _slice['slice_hrn'] == req_slice_hrn:
96 #                     errors.append('Slice already exists. Please use a different slice name.')
97             
98
99             # What kind of slice name is valid?
100             if (post['project_name'] is None or post['project_name'] == ''):
101                 errors.append('Project name is mandatory')
102             
103             if (re.search(r'^[A-Za-z0-9_]*$', post['project_name']) == None):
104                 errors.append('Project name may contain only letters, numbers, and underscore.')
105             
106             if (post['authority_hrn'] is None or post['authority_hrn'] == ''):
107                 errors.append('Organization is mandatory')
108     
109             if (post['purpose'] is None or post['purpose'] == ''):
110                 errors.append('Experiment purpose is mandatory')
111
112             if not errors:
113                 create_pending_project(wsgi_request, post)
114         
115         # retrieves the pending projects list
116         pending_projects = PendingProject.objects.all().filter(user_hrn=user_hrn)
117                     
118         env = {
119                'errors':        errors,
120                'username':      wsgi_request.user,
121                'theme':         self.theme,
122                'authorities':   authorities,
123                'authority_hrn': user_authority,
124                'pending_projects': pending_projects,
125         }
126         return render(wsgi_request, self.template, env)
127     
128         
129     
130         """
131         """
132         errors = []
133         slice_name =''
134         purpose=''
135         url=''
136         authority_hrn = None
137         authority_name = None
138         # Retrieve the list of authorities
139         authorities_query = Query.get('authority').select('name', 'authority_hrn')
140         authorities = execute_admin_query(wsgi_request, authorities_query)
141         if authorities is not None:
142             authorities = sorted(authorities, key=lambda k: k['authority_hrn'])
143             authorities = sorted(authorities, key=lambda k: k['name'])
144
145         # Get user_email (XXX Would deserve to be simplified)
146         user_query  = Query().get('local:user').select('email','config')
147         user_details = execute_query(wsgi_request, user_query)
148         user_email = user_details[0].get('email')
149         # getting user_hrn
150         for user_detail in user_details:
151             user_config = json.loads(user_detail['config'])
152             user_authority = user_config.get('authority','N/A')              
153         # getting the org from authority        
154         for authority in authorities:
155             if authority['authority_hrn'] == user_authority:
156                 authority_name = authority['name']
157
158         # Handle the case when we use only hrn and not name
159         if authority_name is None:
160             authority_name = user_authority
161         #
162         account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
163         account_details = execute_query(wsgi_request, account_query)
164         #
165         platform_query  = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
166         platform_details = execute_query(wsgi_request, platform_query)
167         
168         user_hrn = None
169         # getting user_hrn from local:account
170         for account_detail in account_details:
171             for platform_detail in platform_details:
172                 if platform_detail['platform_id'] == account_detail['platform_id']:
173                     # taking user_hrn only from myslice account
174                     # NOTE: we should later handle accounts filter_by auth_type= managed OR user
175                     if 'myslice' in platform_detail['platform']:
176                         account_config = json.loads(account_detail['config'])
177                         user_hrn = account_config.get('user_hrn','N/A')
178                         acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
179
180
181         # checking if pi or not
182         if acc_auth_cred == {} or acc_auth_cred == 'N/A':
183             pi = "is_not_pi"
184         else:
185             pi = "is_pi"
186
187
188         # Page rendering
189 #         page = Page(wsgi_request)
190 #         page.add_js_files  ( [ "js/jquery.validate.js", "js/jquery-ui.js" ] )
191 #         page.add_css_files ( [ "https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" ] )
192 #         page.expose_js_metadata()
193
194         if method == 'POST':
195             # The form has been submitted
196
197             # get the domain url
198 #             current_site = Site.objects.get_current()
199 #             current_site = current_site.domain
200             
201             # getting the authority_hrn from the selected organization
202             for authority in authorities:
203                 if authority['name'] == wsgi_request.POST.get('org_name', ''):
204                     authority_hrn = authority['authority_hrn']
205
206             # Handle the case when we use only hrn and not name
207             if authority_hrn is None:
208                 authority_hrn = wsgi_request.POST.get('org_name', '')
209
210             slice_request = {
211                 'type'              : 'slice',
212                 'id'                : None,
213                 'user_hrn'          : user_hrn,
214                 'email'             : user_email,
215                 'timestamp'         : time.time(),
216                 'authority_hrn'     : authority_hrn,
217                 'organization'      : wsgi_request.POST.get('org_name', ''),
218                 'slice_name'        : wsgi_request.POST.get('slice_name', ''),
219                 'url'               : wsgi_request.POST.get('url', ''),
220                 'purpose'           : wsgi_request.POST.get('purpose', ''),
221                 'current_site'      : current_site
222             }
223             
224             # create slice_hrn based on authority_hrn and slice_name
225 #             slice_name = slice_request['slice_name']
226             req_slice_hrn = authority_hrn + '.' + slice_name
227             # comparing requested slice_hrn with the existing slice_hrn 
228             slice_query  = Query().get('myslice:slice').select('slice_hrn','parent_authority').filter_by('parent_authority','==',authority_hrn)
229             slice_details_sfa = execute_admin_query(wsgi_request, slice_query)
230             for _slice in slice_details_sfa:
231                 if _slice['slice_hrn'] == req_slice_hrn:
232                     errors.append('Slice already exists. Please use a different slice name.')
233             
234
235             # What kind of slice name is valid?
236             if (slice_name is None or slice_name == ''):
237                 errors.append('Slice name is mandatory')
238             
239             if (re.search(r'^[A-Za-z0-9_]*$', slice_name) == None):
240                 errors.append('Slice name may contain only letters, numbers, and underscore.')
241             
242             organization = slice_request['organization']    
243             if (organization is None or organization == ''):
244                 errors.append('Organization is mandatory')
245
246
247     
248             purpose = slice_request['purpose']
249             if (purpose is None or purpose == ''):
250                 errors.append('Experiment purpose is mandatory')
251
252             url = slice_request['url']
253
254             if not errors:
255                 if is_pi(wsgi_request, user_hrn, authority_hrn):
256                     # PIs can directly create slices in their own authority...
257                     create_slice(wsgi_request, slice_request)
258                     clear_user_creds(wsgi_request, user_email)
259                     self.template_name = 'slice-request-done-view.html'
260                 else:
261                     # Otherwise a wsgi_request is sent to the PI
262                     create_pending_slice(wsgi_request, slice_request, user_email)
263                     self.template_name = 'slice-request-ack-view.html'
264                 
265                 # log user activity
266                 activity.user.slice(wsgi_request)
267                 
268                 return render(wsgi_request, self.template, {'theme': self.theme}) # Redirect after POST
269         else:
270             slice_request = {}
271
272         template_env = {
273             'username': wsgi_request.user.email,
274             'errors': errors,
275             'slice_name': slice_name,
276             'purpose': purpose,
277             'email': user_email,
278             'user_hrn': user_hrn,
279             'url': url,
280             'pi': pi,
281             'authority_name': authority_name,        
282             'authority_hrn': user_authority,        
283             'cc_myself': True,
284             'authorities': authorities,
285             'theme': self.theme,
286             'section': "Slice request"
287         }
288         template_env.update(slice_request)
289         template_env.update(page.prelude_env())
290         return render(wsgi_request, self.template, template_env)