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