Account: download keys and jfed identity based on functions in actions.py
[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, get_jfed_identity
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         # user was authenticated at the backend
60         elif auth_result is not None:
61             user=auth_result
62             if user.is_active:
63                 login(request, user)
64                 
65                 if request.user.is_authenticated(): 
66                     env['person'] = self.request.user
67                     env['username'] = self.request.user
68                     
69                     # log user activity
70                     activity.user.login(self.request)
71                     
72                     ## check user is pi or not
73                     platform_details = {}
74                     account_details = {}
75                     acc_auth_cred = {}
76                     acc_user_cred = {}
77                     platform_query  = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
78                     account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
79                     platform_details = execute_query(self.request, platform_query)
80                     account_details = execute_query(self.request, account_query)
81                     if platform_details is not None and platform_details != {}:
82                         for platform_detail in platform_details:
83                             for account_detail in account_details:
84                                 if platform_detail['platform_id'] == account_detail['platform_id']:
85                                     if 'config' in account_detail and account_detail['config'] is not '':
86                                         account_config = json.loads(account_detail['config'])
87                                         if 'myslice' in platform_detail['platform']:
88                                             acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
89                                             acc_user_cred = account_config.get('delegated_user_credential','N/A')
90                     # assigning values
91                     #if acc_auth_cred=={} or acc_auth_cred=='N/A':
92                     #    pi = "is_not_pi"
93                     #else:
94                     #    pi = "is_pi"
95                     user_email = str(self.request.user)                   
96                     pi = authority_check_pis(self.request, user_email)
97
98                     # check if the user has creds or not
99                     if acc_user_cred == {} or acc_user_cred == 'N/A':
100                         user_cred = 'no_creds'
101                     else:
102                         exp_date = get_expiration(acc_user_cred, 'timestamp')
103                         if exp_date < time.time():
104                             user_cred = 'creds_expired'
105                         else:
106                             user_cred = 'has_creds'
107
108                     # list the pending slices of this user
109                     pending_slices = []
110                     for slices in PendingSlice.objects.filter(type_of_nodes__iexact=self.request.user).all():
111                         pending_slices.append(slices.slice_name)
112
113                     env['pending_slices'] = pending_slices
114                     env['pi'] = pi
115                     env['user_cred'] = user_cred                
116                 else: 
117                     env['person'] = None
118             else:
119                 # log user activity
120                 activity.user.login(self.request, "notactive")
121                 env['state'] = "Your account is not active, please contact the site admin."
122                 env['layout_1_or_2']="layout-unfold2.html"
123                 
124             jfed_identity = get_jfed_identity(request)
125             if jfed_identity is not None:
126                 import base64
127                 encoded_jfed_identity = base64.b64encode(jfed_identity)
128                 env['jfed_identity'] = encoded_jfed_identity 
129             else:
130                 env['jfed_identity'] = None
131
132         # otherwise
133         else:
134             # log user activity
135             activity.user.login(self.request, "error")
136             env['state'] = "Your username and/or password were incorrect."
137             
138         return render_to_response(self.template,env, context_instance=RequestContext(request))
139
140     def get (self, request, state=None):
141         env = self.default_env()
142         acc_auth_cred={}
143
144         jfed_identity = get_jfed_identity(request)
145         if jfed_identity is not None:
146             import base64
147             encoded_jfed_identity = base64.b64encode(jfed_identity)
148             env['jfed_identity'] = encoded_jfed_identity 
149         else:
150             env['jfed_identity'] = None
151
152         if request.user.is_authenticated():
153            
154             ## check user is pi or not
155             platform_details = {}
156             account_details = {}
157             acc_auth_cred = {}
158             acc_user_cred = {}
159             platform_query  = Query().get('local:platform').select('platform_id','platform','gateway_type','disabled')
160             account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
161             # XXX Something like an invalid session seems to make the execute fail sometimes, and thus gives an error on the main page
162             platform_details = execute_query(self.request, platform_query)
163             account_details = execute_query(self.request, account_query)
164             if platform_details is not None and platform_details != {}:
165                 for platform_detail in platform_details:
166                     for account_detail in account_details:
167                         if 'platform_id' in platform_detail:
168                             if platform_detail['platform_id'] == account_detail['platform_id']:
169                                 if 'config' in account_detail and account_detail['config'] is not '':
170                                     account_config = json.loads(account_detail['config'])
171                                     if 'myslice' in platform_detail['platform']:
172                                         acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
173                                         acc_user_cred = account_config.get('delegated_user_credential','N/A')
174             # assigning values
175             #if acc_auth_cred=={} or acc_auth_cred=='N/A':
176             #    pi = "is_not_pi"
177             #else:
178             #    pi = "is_pi"
179             user_email = str(self.request.user) 
180             pi = authority_check_pis(self.request, user_email)
181             # check if the user has creds or not
182             if acc_user_cred == {} or acc_user_cred == 'N/A':
183                 user_cred = 'no_creds'
184             else:
185                 exp_date = get_expiration(acc_user_cred, 'timestamp')
186                 if exp_date < time.time():
187                     user_cred = 'creds_expired'
188                 else:
189                     user_cred = 'has_creds'
190
191             # list the pending slices of this user
192             pending_slices = []
193             for slices in PendingSlice.objects.filter(type_of_nodes__iexact=self.request.user).all():
194                 pending_slices.append(slices.slice_name)
195         
196             env['pending_slices'] = pending_slices
197             env['pi'] = pi
198             env['user_cred'] = user_cred                
199             env['person'] = self.request.user
200         else: 
201             env['person'] = None
202
203         env['theme'] = self.theme
204         env['section'] = "Dashboard"
205
206
207         env['username']=the_user(request)
208         env['topmenu_items'] = topmenu_items(None, request)
209         if state: env['state'] = state
210         elif not env['username']: env['state'] = None
211         # use one or two columns for the layout - not logged in users will see the login prompt
212         return render_to_response(self.template, env, context_instance=RequestContext(request))
213