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