Merge branch 'onelab' of ssh://git.onelab.eu/git/myslice into onelab
[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
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_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             else:
120                 # log user activity
121                 activity.user.login(self.request, "notactive")
122                 env['state'] = "Your account is not active, please contact the site admin."
123                 env['layout_1_or_2']="layout-unfold2.html"
124
125             jfed_identity = get_jfed_identity(request)
126             if jfed_identity is not None:
127                 import base64
128                 encoded_jfed_identity = base64.b64encode(jfed_identity)
129                 env['jfed_identity'] = encoded_jfed_identity 
130             else:
131                 env['jfed_identity'] = None
132
133         # otherwise
134         else:
135             # log user activity
136             activity.user.login(self.request, "error")
137             env['state'] = "Your username and/or password were incorrect."
138
139         return render_to_response(self.template,env, context_instance=RequestContext(request))
140
141     def get (self, request, state=None):
142         env = self.default_env()
143         acc_auth_cred={}
144
145         jfed_identity = get_jfed_identity(request)
146         if jfed_identity is not None:
147             import base64
148             encoded_jfed_identity = base64.b64encode(jfed_identity)
149             env['jfed_identity'] = encoded_jfed_identity 
150         else:
151             env['jfed_identity'] = None
152
153         if request.user.is_authenticated():
154
155             ## check user is pi or not
156             platform_details = {}
157             account_details = {}
158             acc_auth_cred = {}
159             acc_user_cred = {}
160             platform_query  = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
161             account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
162             # XXX Something like an invalid session seems to make the execute fail sometimes, and thus gives an error on the main page
163             platform_details = execute_query(self.request, platform_query)
164             account_details = execute_query(self.request, account_query)
165             if platform_details is not None and platform_details != {}:
166                 for platform_detail in platform_details:
167                     for account_detail in account_details:
168                         if 'platform_id' in platform_detail:
169                             if platform_detail['platform_id'] == account_detail['platform_id']:
170                                 if 'config' in account_detail and account_detail['config'] is not '':
171                                     account_config = json.loads(account_detail['config'])
172                                     if 'myslice' in platform_detail['platform']:
173                                         acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
174                                         acc_user_cred = account_config.get('delegated_user_credential','N/A')
175             # assigning values
176             #if acc_auth_cred=={} or acc_auth_cred=='N/A':
177             #    pi = "is_not_pi"
178             #else:
179             #    pi = "is_pi"
180             user_email = str(self.request.user)
181             pi = authority_check_pis(self.request, user_email)
182             # check if the user has creds or not
183             if acc_user_cred == {} or acc_user_cred == 'N/A':
184                 user_cred = 'no_creds'
185             else:
186                 exp_date = get_expiration(acc_user_cred, 'timestamp')
187                 if exp_date < time.time():
188                     user_cred = 'creds_expired'
189                 else:
190                     user_cred = 'has_creds'
191
192             # list the pending slices of this user
193             pending_slices = []
194             for slices in PendingSlice.objects.filter(type_of_nodes__iexact=self.request.user).all():
195                 pending_slices.append(slices.slice_name)
196
197             env['pending_slices'] = pending_slices
198             env['pi'] = pi
199             env['user_cred'] = user_cred
200             env['person'] = self.request.user
201         else:
202             env['person'] = None
203
204         env['theme'] = self.theme
205         env['section'] = "Dashboard"
206
207
208         env['username']=the_user(request)
209         env['topmenu_items'] = topmenu_items(None, request)
210         if state: env['state'] = state
211         elif not env['username']: env['state'] = None
212         # use one or two columns for the layout - not logged in users will see the login prompt
213
214         return render_to_response(self.template, env, context_instance=RequestContext(request))
215