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