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