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