[FIX] Session Expired message in backend
[odoo/odoo.git] / openerp / addons / base / ir / ir_http.py
1 #----------------------------------------------------------
2 # ir_http modular http routing
3 #----------------------------------------------------------
4 import logging
5 import re
6 import sys
7
8 import werkzeug.exceptions
9 import werkzeug.routing
10
11 import openerp
12 from openerp import http
13 from openerp.http import request
14 from openerp.osv import osv, orm
15
16 _logger = logging.getLogger(__name__)
17
18 UID_PLACEHOLDER = object()
19
20 class ModelConverter(werkzeug.routing.BaseConverter):
21
22     def __init__(self, url_map, model=False):
23         super(ModelConverter, self).__init__(url_map)
24         self.model = model
25         self.regex = '([0-9]+)'
26
27     def to_python(self, value):
28         m = re.match(self.regex, value)
29         return request.registry[self.model].browse(
30             request.cr, UID_PLACEHOLDER, int(m.group(1)), context=request.context)
31
32     def to_url(self, value):
33         return value.id
34
35 class ModelsConverter(werkzeug.routing.BaseConverter):
36
37     def __init__(self, url_map, model=False):
38         super(ModelsConverter, self).__init__(url_map)
39         self.model = model
40         # TODO add support for slug in the form [A-Za-z0-9-] bla-bla-89 -> id 89
41         self.regex = '([0-9,]+)'
42
43     def to_python(self, value):
44         return request.registry[self.model].browse(request.cr, UID_PLACEHOLDER, [int(i) for i in value.split(',')], context=request.context)
45
46     def to_url(self, value):
47         return ",".join(i.id for i in value)
48
49 class ir_http(osv.AbstractModel):
50     _name = 'ir.http'
51     _description = "HTTP routing"
52
53     def _get_converters(self):
54         return {'model': ModelConverter, 'models': ModelsConverter}
55
56     def _find_handler(self):
57         return self.routing_map().bind_to_environ(request.httprequest.environ).match()
58
59     def _auth_method_user(self):
60         request.uid = request.session.uid
61         if not request.uid:
62             raise http.SessionExpiredException("Session expired")
63
64     def _auth_method_none(self):
65         request.uid = None
66
67     def _auth_method_public(self):
68         if not request.session.uid:
69             dummy, request.uid = self.pool['ir.model.data'].get_object_reference(request.cr, openerp.SUPERUSER_ID, 'base', 'public_user')
70         else:
71             request.uid = request.session.uid
72
73     def _authenticate(self, auth_method='user'):
74         if request.session.uid:
75             try:
76                 request.session.check_security()
77                 # what if error in security.check()
78                 #   -> res_users.check()
79                 #   -> res_users.check_credentials()
80             except (openerp.exceptions.AccessDenied, openerp.http.SessionExpiredException):
81                 # All other exceptions mean undetermined status (e.g. connection pool full),
82                 # let them bubble up
83                 request.session.logout()
84         getattr(self, "_auth_method_%s" % auth_method)()
85         return auth_method
86
87     def _handle_exception(self, exception):
88         # If handle_exception returns something different than None, it will be used as a response
89         return request._handle_exception(exception)
90
91     def _dispatch(self):
92         # locate the controller method
93         try:
94             func, arguments = self._find_handler()
95         except werkzeug.exceptions.NotFound, e:
96             return self._handle_exception(e)
97
98         # check authentication level
99         try:
100             auth_method = self._authenticate(func.routing["auth"])
101         except Exception, e:
102             # Json requests have their own exception handler
103             # therefore we should not alter their exception's type
104             if func.routing.get('type') != 'json':
105                 # for the rest, convert to a Forbidden exception keeping the original traceback
106                 e = convert_exception_to(werkzeug.exceptions.Forbidden)
107             return self._handle_exception(e)
108
109         processing = self._postprocess_args(arguments)
110         if processing:
111             return processing
112
113
114         # set and execute handler
115         try:
116             request.set_handler(func, arguments, auth_method)
117             result = request.dispatch()
118             if isinstance(result, Exception):
119                 raise result
120         except Exception, e:
121             return self._handle_exception(e)
122
123         return result
124
125     def _postprocess_args(self, arguments):
126         """ post process arg to set uid on browse records """
127         for arg in arguments.itervalues():
128             if isinstance(arg, orm.browse_record) and arg._uid is UID_PLACEHOLDER:
129                 arg._uid = request.uid
130                 try:
131                     arg[arg._rec_name]
132                 except KeyError:
133                     return self._handle_exception(werkzeug.exceptions.NotFound())
134
135     def routing_map(self):
136         if not hasattr(self, '_routing_map'):
137             _logger.info("Generating routing map")
138             cr = request.cr
139             m = request.registry.get('ir.module.module')
140             ids = m.search(cr, openerp.SUPERUSER_ID, [('state', '=', 'installed'), ('name', '!=', 'web')], context=request.context)
141             installed = set(x['name'] for x in m.read(cr, 1, ids, ['name'], context=request.context))
142             mods = [''] + openerp.conf.server_wide_modules + sorted(installed)
143             self._routing_map = http.routing_map(mods, False, converters=self._get_converters())
144
145         return self._routing_map
146
147 def convert_exception_to(to_type, with_message=False):
148     """ Should only be called from an exception handler. Fetches the current
149     exception data from sys.exc_info() and creates a new exception of type
150     ``to_type`` with the original traceback.
151
152     If ``with_message`` is ``True``, sets the new exception's message to be
153     the stringification of the original exception. If ``False``, does not
154     set the new exception's message. Otherwise, uses ``with_message`` as the
155     new exception's message.
156
157     :type with_message: str|bool
158     """
159     etype, original, tb = sys.exc_info()
160     try:
161         if with_message is False:
162             message = None
163         elif with_message is True:
164             message = str(original)
165         else:
166             message = str(with_message)
167
168         raise to_type, message, tb
169     except to_type, e:
170         return e
171
172 # vim:et: