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