1fe1d2a35ef626ea0b126800c78cfe7892d5712e
[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                 print "LOGGING IN"
65                 login(request, user)
66                 
67                 if request.user.is_authenticated(): 
68                     env['person'] = self.request.user
69                     env['username'] = self.request.user
70                     
71                     # log user activity
72                     activity.user.login(self.request)
73                     
74                     ## check user is pi or not
75                     platform_details = {}
76                     account_details = {}
77                     acc_auth_cred = {}
78                     acc_user_cred = {}
79                     platform_query  = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
80                     account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
81                     platform_details = execute_query(self.request, platform_query)
82                     account_details = execute_query(self.request, account_query)
83                     if platform_details is not None and platform_details != {}:
84                         for platform_detail in platform_details:
85                             for account_detail in account_details:
86                                 if platform_detail['platform_id'] == account_detail['platform_id']:
87                                     if 'config' in account_detail and account_detail['config'] is not '':
88                                         account_config = json.loads(account_detail['config'])
89                                         if 'myslice' in platform_detail['platform']:
90                                             acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
91                                             acc_user_cred = account_config.get('delegated_user_credential','N/A')
92                     # assigning values
93                     #if acc_auth_cred=={} or acc_auth_cred=='N/A':
94                     #    pi = "is_not_pi"
95                     #else:
96                     #    pi = "is_pi"
97                     user_email = str(self.request.user)                   
98                     pi = authority_check_pis(self.request, user_email)
99
100                     # check if the user has creds or not
101                     if acc_user_cred == {} or acc_user_cred == 'N/A':
102                         user_cred = 'no_creds'
103                     else:
104                         exp_date = get_expiration(acc_user_cred, 'timestamp')
105                         if exp_date < time.time():
106                             user_cred = 'creds_expired'
107                         else:
108                             user_cred = 'has_creds'
109
110                     # list the pending slices of this user
111                     pending_slices = []
112                     for slices in PendingSlice.objects.filter(type_of_nodes__iexact=self.request.user).all():
113                         pending_slices.append(slices.slice_name)
114
115                     env['pending_slices'] = pending_slices
116                     env['pi'] = pi
117                     env['user_cred'] = user_cred                
118                 else: 
119                     env['person'] = None
120                 return render_to_response(self.template,env, context_instance=RequestContext(request))
121             else:
122                 # log user activity
123                 activity.user.login(self.request, "notactive")
124                 env['state'] = "Your account is not active, please contact the site admin."
125                 env['layout_1_or_2']="layout-unfold2.html"
126                 
127                 return render_to_response(self.template,env, context_instance=RequestContext(request))
128         # otherwise
129         else:
130             # log user activity
131             activity.user.login(self.request, "error")
132             env['state'] = "Your username and/or password were incorrect."
133             
134             return render_to_response(self.template, env, context_instance=RequestContext(request))
135
136     def get (self, request, state=None):
137         env = self.default_env()
138         acc_auth_cred={}
139         if request.user.is_authenticated():
140            
141             ## check user is pi or not
142             platform_details = {}
143             account_details = {}
144             acc_auth_cred = {}
145             acc_user_cred = {}
146             platform_query  = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
147             account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
148             # XXX Something like an invalid session seems to make the execute fail sometimes, and thus gives an error on the main page
149             platform_details = execute_query(self.request, platform_query)
150             account_details = execute_query(self.request, account_query)
151             if platform_details is not None and platform_details != {}:
152                 for platform_detail in platform_details:
153                     for account_detail in account_details:
154                         if 'platform_id' in platform_detail:
155                             if platform_detail['platform_id'] == account_detail['platform_id']:
156                                 if 'config' in account_detail and account_detail['config'] is not '':
157                                     account_config = json.loads(account_detail['config'])
158                                     if 'myslice' in platform_detail['platform']:
159                                         acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
160                                         acc_user_cred = account_config.get('delegated_user_credential','N/A')
161             # assigning values
162             #if acc_auth_cred=={} or acc_auth_cred=='N/A':
163             #    pi = "is_not_pi"
164             #else:
165             #    pi = "is_pi"
166             user_email = str(self.request.user) 
167             pi = authority_check_pis(self.request, user_email)
168             # check if the user has creds or not
169             if acc_user_cred == {} or acc_user_cred == 'N/A':
170                 user_cred = 'no_creds'
171             else:
172                 exp_date = get_expiration(acc_user_cred, 'timestamp')
173                 if exp_date < time.time():
174                     user_cred = 'creds_expired'
175                 else:
176                     user_cred = 'has_creds'
177
178             # list the pending slices of this user
179             pending_slices = []
180             for slices in PendingSlice.objects.filter(type_of_nodes__iexact=self.request.user).all():
181                 pending_slices.append(slices.slice_name)
182         
183             env['pending_slices'] = pending_slices
184             env['pi'] = pi
185             env['user_cred'] = user_cred                
186             env['person'] = self.request.user
187         else: 
188             env['person'] = None
189
190         env['theme'] = self.theme
191         env['section'] = "Dashboard"
192
193
194         env['username']=the_user(request)
195         env['topmenu_items'] = topmenu_items(None, request)
196         if state: env['state'] = state
197         elif not env['username']: env['state'] = None
198         # use one or two columns for the layout - not logged in users will see the login prompt
199         
200 #         account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
201 #         account_details = execute_query(self.request, account_query)
202 #         for account_detail in account_details:
203 #             account_config = json.loads(account_detail['config'])
204 #             platform_name = platform_detail['platform']
205 #             if 'myslice' in platform_detail['platform']:
206 #                 acc_user_cred = account_config.get('delegated_user_credential','N/A')
207 #                 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
208 #                 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
209
210 #                 if 'N/A' not in acc_user_cred:
211 #                     exp_date = re.search('<expires>(.*)</expires>', acc_user_cred)
212 #                     if exp_date:
213 #                         user_exp_date = exp_date.group(1)
214 #                         user_cred_exp_list.append(user_exp_date)
215
216 #                     my_users = [{'cred_exp': t[0]}
217 #                         for t in zip(user_cred_exp_list)]
218 #                
219
220 #                 if 'N/A' not in acc_slice_cred:
221 #                     for key, value in acc_slice_cred.iteritems():
222 #                         slice_list.append(key)
223 #                         # get cred_exp date
224 #                         exp_date = re.search('<expires>(.*)</expires>', value)
225 #                         if exp_date:
226 #                             exp_date = exp_date.group(1)
227 #                             slice_cred_exp_list.append(exp_date)
228
229 #                     my_slices = [{'slice_name': t[0], 'cred_exp': t[1]}
230 #                         for t in zip(slice_list, slice_cred_exp_list)]
231
232 #                 if 'N/A' not in acc_auth_cred:
233 #                     for key, value in acc_auth_cred.iteritems():
234 #                         auth_list.append(key)
235 #                         #get cred_exp date
236 #                         exp_date = re.search('<expires>(.*)</expires>', value)
237 #                         if exp_date:
238 #                             exp_date = exp_date.group(1)
239 #                             auth_cred_exp_list.append(exp_date)
240
241         
242         return render_to_response(self.template, env, context_instance=RequestContext(request))
243