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