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