translate most modules to using print() as imported from __future__
[myslice.git] / portal / homeview.py
1 from __future__ import print_function
2
3 # this somehow is not used anymore - should it not be ?
4 from django.core.context_processors     import csrf
5 from django.http                        import HttpResponseRedirect
6 from django.contrib.auth                import authenticate, login, logout
7 from django.template                    import RequestContext
8 from django.shortcuts                   import render_to_response
9 from django.shortcuts                   import render
10
11
12 from unfold.loginrequired               import FreeAccessView
13
14 from manifold.core.query                import Query
15 from manifoldapi.manifoldapi            import execute_query
16
17 from manifoldapi.manifoldresult         import ManifoldResult
18 from ui.topmenu                         import topmenu_items, the_user
19 from myslice.configengine               import ConfigEngine
20
21 from myslice.theme                      import ThemeView
22 from portal.account                     import Account, get_expiration
23 from portal.models                      import PendingSlice
24 from portal.actions                     import authority_check_pis
25
26 import json, time
27 import activity.user
28
29 class HomeView (FreeAccessView, ThemeView):
30     template_name = 'home-view.html'
31         
32     # expose this so we can mention the backend URL on the welcome page
33     def default_env (self):
34         return { 
35                  'MANIFOLD_URL':ConfigEngine().manifold_url(),
36                  }
37
38     def post (self,request):
39         env = self.default_env()
40         env['theme'] = self.theme
41         env['section'] = "Dashboard"
42         
43         username = request.POST.get('username')
44         password = request.POST.get('password')
45         
46         # pass request within the token, so manifold session key can be attached to the request session.
47         token = {'username': username, 'password': password, 'request': request}    
48
49         # our authenticate function returns either
50         # . a ManifoldResult - when something has gone wrong, like e.g. backend is unreachable
51         # . a django User in case of success
52         # . or None if the backend could be reached but the authentication failed
53         auth_result = authenticate(token=token)
54         # use one or two columns for the layout - not logged in users will see the login prompt
55         # high-level errors, like connection refused or the like
56         if isinstance (auth_result, ManifoldResult):
57             manifoldresult = auth_result
58             # let's use ManifoldResult.__repr__
59             env['state']="%s"%manifoldresult
60             
61             return render_to_response(self.template,env, context_instance=RequestContext(request))
62         # user was authenticated at the backend
63         elif auth_result is not None:
64             user=auth_result
65             if user.is_active:
66                 print("LOGGING IN")
67                 login(request, user)
68                 
69                 if request.user.is_authenticated(): 
70                     env['person'] = self.request.user
71                     env['username'] = self.request.user
72                     
73                     # log user activity
74                     activity.user.login(self.request)
75                     
76                     ## check user is pi or not
77                     platform_details = {}
78                     account_details = {}
79                     acc_auth_cred = {}
80                     acc_user_cred = {}
81                     platform_query  = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
82                     account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
83                     platform_details = execute_query(self.request, platform_query)
84                     account_details = execute_query(self.request, account_query)
85                     if platform_details is not None and platform_details != {}:
86                         for platform_detail in platform_details:
87                             for account_detail in account_details:
88                                 if platform_detail['platform_id'] == account_detail['platform_id']:
89                                     if 'config' in account_detail and account_detail['config'] is not '':
90                                         account_config = json.loads(account_detail['config'])
91                                         if 'myslice' in platform_detail['platform']:
92                                             acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
93                                             acc_user_cred = account_config.get('delegated_user_credential','N/A')
94                     # assigning values
95                     #if acc_auth_cred=={} or acc_auth_cred=='N/A':
96                     #    pi = "is_not_pi"
97                     #else:
98                     #    pi = "is_pi"
99                     user_email = str(self.request.user)                   
100                     pi = authority_check_pis(self.request, user_email)
101
102                     # check if the user has creds or not
103                     if acc_user_cred == {} or acc_user_cred == 'N/A':
104                         user_cred = 'no_creds'
105                     else:
106                         exp_date = get_expiration(acc_user_cred, 'timestamp')
107                         if exp_date < time.time():
108                             user_cred = 'creds_expired'
109                         else:
110                             user_cred = 'has_creds'
111
112                     # list the pending slices of this user
113                     pending_slices = []
114                     for slices in PendingSlice.objects.filter(type_of_nodes__iexact=self.request.user).all():
115                         pending_slices.append(slices.slice_name)
116
117                     env['pending_slices'] = pending_slices
118                     env['pi'] = pi
119                     env['user_cred'] = user_cred                
120                 else: 
121                     env['person'] = None
122                 return render_to_response(self.template,env, context_instance=RequestContext(request))
123             else:
124                 # log user activity
125                 activity.user.login(self.request, "notactive")
126                 env['state'] = "Your account is not active, please contact the site admin."
127                 env['layout_1_or_2']="layout-unfold2.html"
128                 
129                 return render_to_response(self.template,env, context_instance=RequestContext(request))
130         # otherwise
131         else:
132             # log user activity
133             activity.user.login(self.request, "error")
134             env['state'] = "Your username and/or password were incorrect."
135             
136             return render_to_response(self.template, env, context_instance=RequestContext(request))
137
138     def get (self, request, state=None):
139         env = self.default_env()
140         acc_auth_cred={}
141         if request.user.is_authenticated():
142            
143             ## check user is pi or not
144             platform_details = {}
145             account_details = {}
146             acc_auth_cred = {}
147             acc_user_cred = {}
148             platform_query  = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
149             account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
150             # XXX Something like an invalid session seems to make the execute fail sometimes, and thus gives an error on the main page
151             platform_details = execute_query(self.request, platform_query)
152             account_details = execute_query(self.request, account_query)
153             if platform_details is not None and platform_details != {}:
154                 for platform_detail in platform_details:
155                     for account_detail in account_details:
156                         if 'platform_id' in platform_detail:
157                             if platform_detail['platform_id'] == account_detail['platform_id']:
158                                 if 'config' in account_detail and account_detail['config'] is not '':
159                                     account_config = json.loads(account_detail['config'])
160                                     if 'myslice' in platform_detail['platform']:
161                                         acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
162                                         acc_user_cred = account_config.get('delegated_user_credential','N/A')
163             # assigning values
164             #if acc_auth_cred=={} or acc_auth_cred=='N/A':
165             #    pi = "is_not_pi"
166             #else:
167             #    pi = "is_pi"
168             user_email = str(self.request.user) 
169             pi = authority_check_pis(self.request, user_email)
170             # check if the user has creds or not
171             if acc_user_cred == {} or acc_user_cred == 'N/A':
172                 user_cred = 'no_creds'
173             else:
174                 exp_date = get_expiration(acc_user_cred, 'timestamp')
175                 if exp_date < time.time():
176                     user_cred = 'creds_expired'
177                 else:
178                     user_cred = 'has_creds'
179
180             # list the pending slices of this user
181             pending_slices = []
182             for slices in PendingSlice.objects.filter(type_of_nodes__iexact=self.request.user).all():
183                 pending_slices.append(slices.slice_name)
184         
185             env['pending_slices'] = pending_slices
186             env['pi'] = pi
187             env['user_cred'] = user_cred                
188             env['person'] = self.request.user
189         else: 
190             env['person'] = None
191
192         env['theme'] = self.theme
193         env['section'] = "Dashboard"
194
195
196         env['username']=the_user(request)
197         env['topmenu_items'] = topmenu_items(None, request)
198         if state: env['state'] = state
199         elif not env['username']: env['state'] = None
200         # use one or two columns for the layout - not logged in users will see the login prompt
201         
202 #         account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
203 #         account_details = execute_query(self.request, account_query)
204 #         for account_detail in account_details:
205 #             account_config = json.loads(account_detail['config'])
206 #             platform_name = platform_detail['platform']
207 #             if 'myslice' in platform_detail['platform']:
208 #                 acc_user_cred = account_config.get('delegated_user_credential','N/A')
209 #                 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
210 #                 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
211
212 #                 if 'N/A' not in acc_user_cred:
213 #                     exp_date = re.search('<expires>(.*)</expires>', acc_user_cred)
214 #                     if exp_date:
215 #                         user_exp_date = exp_date.group(1)
216 #                         user_cred_exp_list.append(user_exp_date)
217
218 #                     my_users = [{'cred_exp': t[0]}
219 #                         for t in zip(user_cred_exp_list)]
220 #                
221
222 #                 if 'N/A' not in acc_slice_cred:
223 #                     for key, value in acc_slice_cred.iteritems():
224 #                         slice_list.append(key)
225 #                         # get cred_exp date
226 #                         exp_date = re.search('<expires>(.*)</expires>', value)
227 #                         if exp_date:
228 #                             exp_date = exp_date.group(1)
229 #                             slice_cred_exp_list.append(exp_date)
230
231 #                     my_slices = [{'slice_name': t[0], 'cred_exp': t[1]}
232 #                         for t in zip(slice_list, slice_cred_exp_list)]
233
234 #                 if 'N/A' not in acc_auth_cred:
235 #                     for key, value in acc_auth_cred.iteritems():
236 #                         auth_list.append(key)
237 #                         #get cred_exp date
238 #                         exp_date = re.search('<expires>(.*)</expires>', value)
239 #                         if exp_date:
240 #                             exp_date = exp_date.group(1)
241 #                             auth_cred_exp_list.append(exp_date)
242
243         
244         return render_to_response(self.template, env, context_instance=RequestContext(request))
245