author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Mon, 06 Jul 2009 10:56:13 +0200 | |
branch | stable |
changeset 2272 | f27a3a75be0d |
parent 2263 | 1f59cd5b710f |
child 2293 | 7ded2a1416e4 |
permissions | -rw-r--r-- |
0 | 1 |
"""CubicWeb web client application object |
2 |
||
3 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1426
diff
changeset
|
4 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 5 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1426
diff
changeset
|
6 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 7 |
""" |
8 |
__docformat__ = "restructuredtext en" |
|
9 |
||
10 |
import sys |
|
11 |
from time import clock, time |
|
12 |
||
13 |
from rql import BadRQLQuery |
|
14 |
||
15 |
from cubicweb import set_log_methods |
|
16 |
from cubicweb import (ValidationError, Unauthorized, AuthenticationError, |
|
2272
f27a3a75be0d
no tb for RequestError
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2263
diff
changeset
|
17 |
NoSelectableObject, RepositoryError) |
0 | 18 |
from cubicweb.cwvreg import CubicWebRegistry |
2272
f27a3a75be0d
no tb for RequestError
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2263
diff
changeset
|
19 |
from cubicweb.web import (LOGGER, StatusResponse, DirectResponse, Redirect, |
f27a3a75be0d
no tb for RequestError
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2263
diff
changeset
|
20 |
NotFound, RemoteCallFailed, ExplicitLogin, |
f27a3a75be0d
no tb for RequestError
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2263
diff
changeset
|
21 |
InvalidSession, RequestError) |
661
4f61eb8a96b7
properly kill/depreciate component base class, only keep Component
sylvain.thenault@logilab.fr
parents:
581
diff
changeset
|
22 |
from cubicweb.web.component import Component |
0 | 23 |
|
24 |
# make session manager available through a global variable so the debug view can |
|
25 |
# print information about web session |
|
26 |
SESSION_MANAGER = None |
|
27 |
||
661
4f61eb8a96b7
properly kill/depreciate component base class, only keep Component
sylvain.thenault@logilab.fr
parents:
581
diff
changeset
|
28 |
class AbstractSessionManager(Component): |
0 | 29 |
"""manage session data associated to a session identifier""" |
30 |
id = 'sessionmanager' |
|
1426 | 31 |
|
0 | 32 |
def __init__(self): |
33 |
self.session_time = self.vreg.config['http-session-time'] or None |
|
34 |
assert self.session_time is None or self.session_time > 0 |
|
168
f6be0c92fc38
fix default values
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
35 |
self.cleanup_session_time = self.vreg.config['cleanup-session-time'] or 43200 |
0 | 36 |
assert self.cleanup_session_time > 0 |
168
f6be0c92fc38
fix default values
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
37 |
self.cleanup_anon_session_time = self.vreg.config['cleanup-anonymous-session-time'] or 120 |
0 | 38 |
assert self.cleanup_anon_session_time > 0 |
39 |
if self.session_time: |
|
40 |
assert self.cleanup_session_time < self.session_time |
|
41 |
assert self.cleanup_anon_session_time < self.session_time |
|
42 |
self.authmanager = self.vreg.select_component('authmanager') |
|
43 |
assert self.authmanager, 'no authentication manager found' |
|
1426 | 44 |
|
0 | 45 |
def clean_sessions(self): |
46 |
"""cleanup sessions which has not been unused since a given amount of |
|
47 |
time. Return the number of sessions which have been closed. |
|
48 |
""" |
|
49 |
self.debug('cleaning http sessions') |
|
50 |
closed, total = 0, 0 |
|
51 |
for session in self.current_sessions(): |
|
52 |
no_use_time = (time() - session.last_usage_time) |
|
53 |
total += 1 |
|
54 |
if session.anonymous_connection: |
|
55 |
if no_use_time >= self.cleanup_anon_session_time: |
|
56 |
self.close_session(session) |
|
57 |
closed += 1 |
|
58 |
elif no_use_time >= self.cleanup_session_time: |
|
59 |
self.close_session(session) |
|
60 |
closed += 1 |
|
61 |
return closed, total - closed |
|
1426 | 62 |
|
0 | 63 |
def has_expired(self, session): |
64 |
"""return True if the web session associated to the session is expired |
|
65 |
""" |
|
66 |
return not (self.session_time is None or |
|
67 |
time() < session.last_usage_time + self.session_time) |
|
1426 | 68 |
|
0 | 69 |
def current_sessions(self): |
70 |
"""return currently open sessions""" |
|
71 |
raise NotImplementedError() |
|
1426 | 72 |
|
0 | 73 |
def get_session(self, req, sessionid): |
74 |
"""return existing session for the given session identifier""" |
|
75 |
raise NotImplementedError() |
|
76 |
||
77 |
def open_session(self, req): |
|
78 |
"""open and return a new session for the given request |
|
1426 | 79 |
|
0 | 80 |
:raise ExplicitLogin: if authentication is required |
81 |
""" |
|
82 |
raise NotImplementedError() |
|
1426 | 83 |
|
0 | 84 |
def close_session(self, session): |
85 |
"""close session on logout or on invalid session detected (expired out, |
|
86 |
corrupted...) |
|
87 |
""" |
|
88 |
raise NotImplementedError() |
|
89 |
||
90 |
||
661
4f61eb8a96b7
properly kill/depreciate component base class, only keep Component
sylvain.thenault@logilab.fr
parents:
581
diff
changeset
|
91 |
class AbstractAuthenticationManager(Component): |
0 | 92 |
"""authenticate user associated to a request and check session validity""" |
93 |
id = 'authmanager' |
|
94 |
||
95 |
def authenticate(self, req): |
|
96 |
"""authenticate user and return corresponding user object |
|
1426 | 97 |
|
0 | 98 |
:raise ExplicitLogin: if authentication is required (no authentication |
99 |
info found or wrong user/password) |
|
100 |
""" |
|
101 |
raise NotImplementedError() |
|
102 |
||
1426 | 103 |
|
0 | 104 |
class CookieSessionHandler(object): |
105 |
"""a session handler using a cookie to store the session identifier |
|
106 |
||
107 |
:cvar SESSION_VAR: |
|
108 |
string giving the name of the variable used to store the session |
|
109 |
identifier |
|
110 |
""" |
|
111 |
SESSION_VAR = '__session' |
|
1426 | 112 |
|
0 | 113 |
def __init__(self, appli): |
114 |
self.session_manager = appli.vreg.select_component('sessionmanager') |
|
115 |
assert self.session_manager, 'no session manager found' |
|
116 |
global SESSION_MANAGER |
|
117 |
SESSION_MANAGER = self.session_manager |
|
118 |
if not 'last_login_time' in appli.vreg.schema: |
|
119 |
self._update_last_login_time = lambda x: None |
|
120 |
||
121 |
def clean_sessions(self): |
|
122 |
"""cleanup sessions which has not been unused since a given amount of |
|
123 |
time |
|
124 |
""" |
|
125 |
self.session_manager.clean_sessions() |
|
1426 | 126 |
|
0 | 127 |
def set_session(self, req): |
128 |
"""associate a session to the request |
|
129 |
||
130 |
Session id is searched from : |
|
131 |
- # form variable |
|
132 |
- cookie |
|
133 |
||
134 |
if no session id is found, open a new session for the connected user |
|
135 |
or request authentification as needed |
|
136 |
||
1426 | 137 |
:raise Redirect: if authentication has occured and succeed |
0 | 138 |
""" |
139 |
assert req.cnx is None # at this point no cnx should be set on the request |
|
140 |
cookie = req.get_cookie() |
|
141 |
try: |
|
142 |
sessionid = str(cookie[self.SESSION_VAR].value) |
|
143 |
except KeyError: # no session cookie |
|
144 |
session = self.open_session(req) |
|
145 |
else: |
|
146 |
try: |
|
147 |
session = self.get_session(req, sessionid) |
|
148 |
except InvalidSession: |
|
149 |
try: |
|
150 |
session = self.open_session(req) |
|
151 |
except ExplicitLogin: |
|
152 |
req.remove_cookie(cookie, self.SESSION_VAR) |
|
153 |
raise |
|
154 |
# remember last usage time for web session tracking |
|
155 |
session.last_usage_time = time() |
|
156 |
||
157 |
def get_session(self, req, sessionid): |
|
158 |
return self.session_manager.get_session(req, sessionid) |
|
1426 | 159 |
|
0 | 160 |
def open_session(self, req): |
161 |
session = self.session_manager.open_session(req) |
|
162 |
cookie = req.get_cookie() |
|
163 |
cookie[self.SESSION_VAR] = session.sessionid |
|
164 |
req.set_cookie(cookie, self.SESSION_VAR, maxage=None) |
|
165 |
# remember last usage time for web session tracking |
|
166 |
session.last_usage_time = time() |
|
167 |
if not session.anonymous_connection: |
|
168 |
self._postlogin(req) |
|
169 |
return session |
|
170 |
||
171 |
def _update_last_login_time(self, req): |
|
172 |
try: |
|
173 |
req.execute('SET X last_login_time NOW WHERE X eid %(x)s', |
|
174 |
{'x' : req.user.eid}, 'x') |
|
175 |
req.cnx.commit() |
|
176 |
except (RepositoryError, Unauthorized): |
|
177 |
# ldap user are not writeable for instance |
|
178 |
req.cnx.rollback() |
|
179 |
except: |
|
180 |
req.cnx.rollback() |
|
181 |
raise |
|
1426 | 182 |
|
0 | 183 |
def _postlogin(self, req): |
184 |
"""postlogin: the user has been authenticated, redirect to the original |
|
185 |
page (index by default) with a welcome message |
|
186 |
""" |
|
187 |
# Update last connection date |
|
188 |
# XXX: this should be in a post login hook in the repository, but there |
|
189 |
# we can't differentiate actual login of automatic session |
|
190 |
# reopening. Is it actually a problem? |
|
191 |
self._update_last_login_time(req) |
|
192 |
args = req.form |
|
193 |
args['__message'] = req._('welcome %s !') % req.user.login |
|
194 |
if 'vid' in req.form: |
|
195 |
args['vid'] = req.form['vid'] |
|
196 |
if 'rql' in req.form: |
|
197 |
args['rql'] = req.form['rql'] |
|
198 |
path = req.relative_path(False) |
|
199 |
if path == 'login': |
|
200 |
path = 'view' |
|
201 |
raise Redirect(req.build_url(path, **args)) |
|
1426 | 202 |
|
0 | 203 |
def logout(self, req): |
204 |
"""logout from the application by cleaning the session and raising |
|
205 |
`AuthenticationError` |
|
206 |
""" |
|
207 |
self.session_manager.close_session(req.cnx) |
|
208 |
req.remove_cookie(req.get_cookie(), self.SESSION_VAR) |
|
209 |
raise AuthenticationError() |
|
210 |
||
211 |
||
212 |
class CubicWebPublisher(object): |
|
213 |
"""Central registry for the web application. This is one of the central |
|
214 |
object in the web application, coupling dynamically loaded objects with |
|
215 |
the application's schema and the application's configuration objects. |
|
1426 | 216 |
|
0 | 217 |
It specializes the VRegistry by adding some convenience methods to |
218 |
access to stored objects. Currently we have the following registries |
|
219 |
of objects known by the web application (library may use some others |
|
220 |
additional registries): |
|
221 |
* controllers, which are directly plugged into the application |
|
222 |
object to handle request publishing |
|
223 |
* views |
|
224 |
* templates |
|
225 |
* components |
|
226 |
* actions |
|
227 |
""" |
|
1426 | 228 |
|
0 | 229 |
def __init__(self, config, debug=None, |
230 |
session_handler_fact=CookieSessionHandler, |
|
231 |
vreg=None): |
|
232 |
super(CubicWebPublisher, self).__init__() |
|
233 |
# connect to the repository and get application's schema |
|
234 |
if vreg is None: |
|
235 |
vreg = CubicWebRegistry(config, debug=debug) |
|
236 |
self.vreg = vreg |
|
237 |
self.info('starting web application from %s', config.apphome) |
|
238 |
self.repo = config.repository(vreg) |
|
239 |
if not vreg.initialized: |
|
240 |
self.config.init_cubes(self.repo.get_cubes()) |
|
241 |
vreg.init_properties(self.repo.properties()) |
|
242 |
vreg.set_schema(self.repo.get_schema()) |
|
243 |
# set the correct publish method |
|
244 |
if config['query-log-file']: |
|
245 |
from threading import Lock |
|
246 |
self._query_log = open(config['query-log-file'], 'a') |
|
247 |
self.publish = self.log_publish |
|
1426 | 248 |
self._logfile_lock = Lock() |
0 | 249 |
else: |
250 |
self._query_log = None |
|
251 |
self.publish = self.main_publish |
|
252 |
# instantiate session and url resolving helpers |
|
253 |
self.session_handler = session_handler_fact(self) |
|
254 |
self.url_resolver = vreg.select_component('urlpublisher') |
|
1426 | 255 |
|
0 | 256 |
def connect(self, req): |
257 |
"""return a connection for a logged user object according to existing |
|
258 |
sessions (i.e. a new connection may be created or an already existing |
|
259 |
one may be reused |
|
260 |
""" |
|
261 |
self.session_handler.set_session(req) |
|
262 |
||
263 |
def select_controller(self, oid, req): |
|
264 |
"""return the most specific view according to the resultset""" |
|
265 |
vreg = self.vreg |
|
266 |
try: |
|
267 |
return vreg.select(vreg.registry_objects('controllers', oid), |
|
268 |
req=req, appli=self) |
|
269 |
except NoSelectableObject: |
|
270 |
raise Unauthorized(req._('not authorized')) |
|
1426 | 271 |
|
0 | 272 |
# publish methods ######################################################### |
1426 | 273 |
|
0 | 274 |
def log_publish(self, path, req): |
275 |
"""wrapper around _publish to log all queries executed for a given |
|
276 |
accessed path |
|
277 |
""" |
|
278 |
try: |
|
279 |
return self.main_publish(path, req) |
|
280 |
finally: |
|
281 |
cnx = req.cnx |
|
282 |
self._logfile_lock.acquire() |
|
283 |
try: |
|
284 |
try: |
|
285 |
result = ['\n'+'*'*80] |
|
286 |
result.append(req.url()) |
|
287 |
result += ['%s %s -- (%.3f sec, %.3f CPU sec)' % q for q in cnx.executed_queries] |
|
288 |
cnx.executed_queries = [] |
|
289 |
self._query_log.write('\n'.join(result).encode(req.encoding)) |
|
290 |
self._query_log.flush() |
|
291 |
except Exception: |
|
292 |
self.exception('error while logging queries') |
|
293 |
finally: |
|
294 |
self._logfile_lock.release() |
|
295 |
||
296 |
def main_publish(self, path, req): |
|
297 |
"""method called by the main publisher to process <path> |
|
1426 | 298 |
|
0 | 299 |
should return a string containing the resulting page or raise a |
300 |
`NotFound` exception |
|
301 |
||
302 |
:type path: str |
|
303 |
:param path: the path part of the url to publish |
|
1426 | 304 |
|
0 | 305 |
:type req: `web.Request` |
306 |
:param req: the request object |
|
307 |
||
308 |
:rtype: str |
|
309 |
:return: the result of the pusblished url |
|
310 |
""" |
|
311 |
path = path or 'view' |
|
312 |
# don't log form values they may contains sensitive information |
|
313 |
self.info('publish "%s" (form params: %s)', path, req.form.keys()) |
|
314 |
# remove user callbacks on a new request (except for json controllers |
|
315 |
# to avoid callbacks being unregistered before they could be called) |
|
316 |
tstart = clock() |
|
317 |
try: |
|
318 |
try: |
|
319 |
ctrlid, rset = self.url_resolver.process(req, path) |
|
320 |
controller = self.select_controller(ctrlid, req) |
|
581
09f87f2c535e
update_search_state in the publisher since it should be done whatever the controller
sylvain.thenault@logilab.fr
parents:
168
diff
changeset
|
321 |
req.update_search_state() |
0 | 322 |
result = controller.publish(rset=rset) |
323 |
if req.cnx is not None: |
|
324 |
# req.cnx is None if anonymous aren't allowed and we are |
|
325 |
# displaying the cookie authentication form |
|
326 |
req.cnx.commit() |
|
327 |
except (StatusResponse, DirectResponse): |
|
328 |
req.cnx.commit() |
|
329 |
raise |
|
330 |
except Redirect: |
|
331 |
# redirect is raised by edit controller when everything went fine, |
|
332 |
# so try to commit |
|
333 |
try: |
|
334 |
req.cnx.commit() |
|
335 |
except ValidationError, ex: |
|
336 |
self.validation_error_handler(req, ex) |
|
337 |
except Unauthorized, ex: |
|
338 |
req.data['errmsg'] = req._('You\'re not authorized to access this page. ' |
|
339 |
'If you think you should, please contact the site administrator.') |
|
340 |
self.error_handler(req, ex, tb=False) |
|
341 |
except Exception, ex: |
|
342 |
self.error_handler(req, ex, tb=True) |
|
343 |
else: |
|
344 |
# delete validation errors which may have been previously set |
|
345 |
if '__errorurl' in req.form: |
|
346 |
req.del_session_data(req.form['__errorurl']) |
|
347 |
raise |
|
348 |
except (AuthenticationError, NotFound, RemoteCallFailed): |
|
349 |
raise |
|
350 |
except ValidationError, ex: |
|
351 |
self.validation_error_handler(req, ex) |
|
2272
f27a3a75be0d
no tb for RequestError
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2263
diff
changeset
|
352 |
except (Unauthorized, BadRQLQuery, RequestError), ex: |
0 | 353 |
self.error_handler(req, ex, tb=False) |
354 |
except Exception, ex: |
|
355 |
self.error_handler(req, ex, tb=True) |
|
356 |
finally: |
|
357 |
if req.cnx is not None: |
|
358 |
try: |
|
359 |
req.cnx.rollback() |
|
360 |
except: |
|
361 |
pass # ignore rollback error at this point |
|
362 |
self.info('query %s executed in %s sec', req.relative_path(), clock() - tstart) |
|
363 |
return result |
|
364 |
||
365 |
def validation_error_handler(self, req, ex): |
|
366 |
ex.errors = dict((k, v) for k, v in ex.errors.items()) |
|
367 |
if '__errorurl' in req.form: |
|
368 |
forminfo = {'errors': ex, |
|
369 |
'values': req.form, |
|
370 |
'eidmap': req.data.get('eidmap', {}) |
|
371 |
} |
|
372 |
req.set_session_data(req.form['__errorurl'], forminfo) |
|
373 |
raise Redirect(req.form['__errorurl']) |
|
374 |
self.error_handler(req, ex, tb=False) |
|
1426 | 375 |
|
0 | 376 |
def error_handler(self, req, ex, tb=False): |
377 |
excinfo = sys.exc_info() |
|
378 |
self.exception(repr(ex)) |
|
379 |
req.set_header('Cache-Control', 'no-cache') |
|
380 |
req.remove_header('Etag') |
|
381 |
req.message = None |
|
382 |
req.reset_headers() |
|
383 |
try: |
|
384 |
req.data['ex'] = ex |
|
385 |
if tb: |
|
386 |
req.data['excinfo'] = excinfo |
|
387 |
req.form['vid'] = 'error' |
|
823
cb8ccbef8fa5
main template refactoring
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
661
diff
changeset
|
388 |
errview = self.vreg.select_view('error', req, None) |
882
75488a2a875e
fix ui.main-template property handling
sylvain.thenault@logilab.fr
parents:
871
diff
changeset
|
389 |
template = self.main_template_id(req) |
75488a2a875e
fix ui.main-template property handling
sylvain.thenault@logilab.fr
parents:
871
diff
changeset
|
390 |
content = self.vreg.main_template(req, template, view=errview) |
0 | 391 |
except: |
832
8e06873d80d3
rename error template to avoid conflicts with the error view
sylvain.thenault@logilab.fr
parents:
823
diff
changeset
|
392 |
content = self.vreg.main_template(req, 'error-template') |
0 | 393 |
raise StatusResponse(500, content) |
1426 | 394 |
|
0 | 395 |
def need_login_content(self, req): |
396 |
return self.vreg.main_template(req, 'login') |
|
1426 | 397 |
|
0 | 398 |
def loggedout_content(self, req): |
399 |
return self.vreg.main_template(req, 'loggedout') |
|
1426 | 400 |
|
0 | 401 |
def notfound_content(self, req): |
402 |
req.form['vid'] = '404' |
|
871 | 403 |
view = self.vreg.select_view('404', req, None) |
882
75488a2a875e
fix ui.main-template property handling
sylvain.thenault@logilab.fr
parents:
871
diff
changeset
|
404 |
template = self.main_template_id(req) |
823
cb8ccbef8fa5
main template refactoring
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
661
diff
changeset
|
405 |
return self.vreg.main_template(req, template, view=view) |
0 | 406 |
|
882
75488a2a875e
fix ui.main-template property handling
sylvain.thenault@logilab.fr
parents:
871
diff
changeset
|
407 |
def main_template_id(self, req): |
2263
1f59cd5b710f
accept a __template parameter that specifies a different (main) template
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1977
diff
changeset
|
408 |
template = req.form.get('__template', req.property_value('ui.main-template')) |
1f59cd5b710f
accept a __template parameter that specifies a different (main) template
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1977
diff
changeset
|
409 |
if template not in self.vreg.registry('views'): |
882
75488a2a875e
fix ui.main-template property handling
sylvain.thenault@logilab.fr
parents:
871
diff
changeset
|
410 |
template = 'main-template' |
75488a2a875e
fix ui.main-template property handling
sylvain.thenault@logilab.fr
parents:
871
diff
changeset
|
411 |
return template |
1426 | 412 |
|
0 | 413 |
|
414 |
set_log_methods(CubicWebPublisher, LOGGER) |
|
415 |
set_log_methods(CookieSessionHandler, LOGGER) |