use logger instead of print as often as possible
[myslice.git] / portal / slicerequestview.py
1 import json
2 import time
3 import re
4
5 from django.shortcuts           import render
6 from django.contrib.sites.models import Site
7
8 from unfold.page                import Page
9
10 from manifold.core.query        import Query
11 from manifoldapi.manifoldapi    import execute_admin_query, execute_query
12
13 from portal.actions             import is_pi, create_slice, create_pending_slice, clear_user_creds, authority_check_pis
14 #from portal.forms               import SliceRequestForm
15 from unfold.loginrequired       import LoginRequiredAutoLogoutView
16 from ui.topmenu                 import topmenu_items_live, the_user
17
18 from myslice.theme import ThemeView
19 from myslice.settings import logger
20
21 import activity.user
22
23 class SliceRequestView (LoginRequiredAutoLogoutView, ThemeView):
24     template_name = 'slicerequest_view.html'
25     
26     # because we inherit LoginRequiredAutoLogoutView that is implemented by redefining 'dispatch'
27     # we cannot redefine dispatch here, or we'd lose LoginRequired and AutoLogout behaviours
28     def post (self, request):
29         return self.get_or_post (request, 'POST')
30
31     def get (self, request):
32         return self.get_or_post (request, 'GET')
33
34     def get_or_post  (self, wsgi_request, method):
35         """
36         """
37         errors = []
38         slice_name =''
39         purpose=''
40         url=''
41         authority_hrn = None
42         authority_name = None
43         # Retrieve the list of authorities
44         authorities_query = Query.get('authority').select('name', 'authority_hrn')
45         authorities = execute_admin_query(wsgi_request, authorities_query)
46         if authorities is not None:
47             authorities = sorted(authorities, key=lambda k: k['authority_hrn'])
48             authorities = sorted(authorities, key=lambda k: k['name'])
49
50         # Get user_email (XXX Would deserve to be simplified)
51         user_query  = Query().get('local:user').select('email','config')
52         user_details = execute_query(wsgi_request, user_query)
53         user_email = user_details[0].get('email')
54         # getting user_hrn
55         for user_detail in user_details:
56             user_config = json.loads(user_detail['config'])
57             user_authority = user_config.get('authority','N/A')              
58         # getting the org from authority        
59         for authority in authorities:
60             if authority['authority_hrn'] == user_authority:
61                 authority_name = authority['name']
62
63         # Handle the case when we use only hrn and not name
64         if authority_name is None:
65             authority_name = user_authority
66         
67         account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
68         account_details = execute_query(wsgi_request, account_query)
69         
70         platform_query  = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
71         platform_details = execute_query(wsgi_request, platform_query)
72         user_hrn = None
73         #getting user_hrn from local:account
74         for account_detail in account_details:
75             for platform_detail in platform_details:
76                 if platform_detail['platform_id'] == account_detail['platform_id']:
77                     # taking user_hrn only from myslice account
78                     # NOTE: we should later handle accounts filter_by auth_type= managed OR user
79                     if 'myslice' in platform_detail['platform']:
80                         account_config = json.loads(account_detail['config'])
81                         user_hrn = account_config.get('user_hrn','N/A')
82         #                acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
83
84
85         # checking if pi or not
86         #if acc_auth_cred == {} or acc_auth_cred == 'N/A':
87         #    pi = "is_not_pi"
88         #else:
89         #    pi = "is_pi"
90
91         pi = authority_check_pis (wsgi_request, user_email)
92         logger.debug("SLICEREQUESTVIEW.PY -----  pi= {}".format(pi))
93
94         # Page rendering
95         page = Page(wsgi_request)
96         page.add_js_files  ( [ "js/jquery.validate.js", "js/jquery-ui.js" ] )
97         page.add_css_files ( [ "css/jquery-ui.css" ] )
98         page.expose_js_metadata()
99
100         if method == 'POST':
101             # The form has been submitted
102
103             # get the domain url
104             current_site = Site.objects.get_current()
105             current_site = current_site.domain
106             
107             # getting the authority_hrn from the selected organization
108             for authority in authorities:
109                 if authority['name'] == wsgi_request.POST.get('org_name', ''):
110                     authority_hrn = authority['authority_hrn']
111
112             # Handle the case when we use only hrn and not name
113             if authority_hrn is None:
114                 authority_hrn = wsgi_request.POST.get('org_name', '')
115
116             # Handle project if used
117             project = wsgi_request.POST.get('project', None)
118             if project is not None and project != '':
119                 authority_hrn = project
120
121             slice_request = {
122                 'type'              : 'slice',
123                 'id'                : None,
124                 'user_hrn'          : user_hrn,
125                 'email'             : user_email,
126                 'timestamp'         : time.time(),
127                 'authority_hrn'     : authority_hrn,
128                 'organization'      : wsgi_request.POST.get('org_name', ''),
129                 'slice_name'        : wsgi_request.POST.get('slice_name', ''),
130                 'url'               : wsgi_request.POST.get('url', ''),
131                 'purpose'           : wsgi_request.POST.get('purpose', ''),
132                 'current_site'      : current_site
133             }
134             
135             # create slice_hrn based on authority_hrn and slice_name
136             slice_name = slice_request['slice_name']
137             req_slice_hrn = authority_hrn + '.' + slice_name
138             # comparing requested slice_hrn with the existing slice_hrn 
139             slice_query  = Query().get('myslice:slice').select('slice_hrn','parent_authority').filter_by('parent_authority','==',authority_hrn)
140             slice_details_sfa = execute_admin_query(wsgi_request, slice_query)
141             for _slice in slice_details_sfa:
142                 if _slice['slice_hrn'] == req_slice_hrn:
143                     errors.append('Slice already exists. Please use a different slice name.')
144             
145
146             # What kind of slice name is valid?
147             if (slice_name is None or slice_name == ''):
148                 errors.append('Slice name is mandatory')
149             
150             if (re.search(r'^[A-Za-z0-9_]*$', slice_name) == None):
151                 errors.append('Slice name may contain only letters, numbers, and underscore.')
152             
153             organization = slice_request['organization']    
154             if (organization is None or organization == ''):
155                 errors.append('Organization is mandatory')
156
157
158     
159             purpose = slice_request['purpose']
160             if (purpose is None or purpose == ''):
161                 errors.append('Experiment purpose is mandatory')
162
163             url = slice_request['url']
164
165             if not errors:
166                 if is_pi(wsgi_request, user_hrn, authority_hrn):
167                     # PIs can directly create slices in their own authority...
168                     create_slice(wsgi_request, slice_request)
169                     clear_user_creds(wsgi_request, user_email)
170                     self.template_name = 'slice-request-done-view.html'
171                 else:
172                     # Otherwise a wsgi_request is sent to the PI
173                     create_pending_slice(wsgi_request, slice_request, user_email)
174                     self.template_name = 'slice-request-ack-view.html'
175                 
176                 # log user activity
177                 activity.user.slice(wsgi_request)
178                 
179                 return render(wsgi_request, self.template, {'theme': self.theme}) # Redirect after POST
180         else:
181             slice_request = {}
182
183         template_env = {
184             'username': wsgi_request.user.email,
185             'topmenu_items': topmenu_items_live('Request a slice', page),
186             'errors': errors,
187             'slice_name': slice_name,
188             'purpose': purpose,
189             'email': user_email,
190             'user_hrn': user_hrn,
191             'url': url,
192             'pi': pi,
193             'authority_name': authority_name,        
194             'authority_hrn': user_authority,        
195             'cc_myself': True,
196             'authorities': authorities,
197             'theme': self.theme,
198             'section': "Slice request"
199         }
200         template_env.update(slice_request)
201         template_env.update(page.prelude_env())
202         return render(wsgi_request, self.template, template_env)