1 #----------------------------------------------------------
2 # ir_http modular http routing
3 #----------------------------------------------------------
11 from openerp import http
12 from openerp.http import request
13 from openerp.osv import osv, orm
15 _logger = logging.getLogger(__name__)
17 UID_PLACEHOLDER = object()
19 class ModelConverter(werkzeug.routing.BaseConverter):
21 def __init__(self, url_map, model=False):
22 super(ModelConverter, self).__init__(url_map)
24 self.regex = '([0-9]+)'
26 def to_python(self, value):
27 m = re.match(self.regex, value)
28 return request.registry[self.model].browse(
29 request.cr, UID_PLACEHOLDER, int(m.group(1)), context=request.context)
31 def to_url(self, value):
34 class ModelsConverter(werkzeug.routing.BaseConverter):
36 def __init__(self, url_map, model=False):
37 super(ModelsConverter, self).__init__(url_map)
39 # TODO add support for slug in the form [A-Za-z0-9-] bla-bla-89 -> id 89
40 self.regex = '([0-9,]+)'
42 def to_python(self, value):
43 return request.registry[self.model].browse(request.cr, UID_PLACEHOLDER, [int(i) for i in value.split(',')], context=request.context)
45 def to_url(self, value):
46 return ",".join(i.id for i in value)
48 class ir_http(osv.AbstractModel):
50 _description = "HTTP routing"
52 def _get_converters(self):
53 return {'model': ModelConverter, 'models': ModelsConverter}
55 def _find_handler(self, return_rule=False):
56 return self.routing_map().bind_to_environ(request.httprequest.environ).match(return_rule=return_rule)
58 def _auth_method_user(self):
59 request.uid = request.session.uid
61 if not request.params.get('noredirect'):
62 query = werkzeug.url_encode({
63 'redirect': request.httprequest.url,
65 response = werkzeug.utils.redirect('/web/login?%s' % query)
66 werkzeug.exceptions.abort(response)
67 raise http.SessionExpiredException("Session expired")
69 def _auth_method_none(self):
72 def _auth_method_public(self):
73 if not request.session.uid:
74 dummy, request.uid = self.pool['ir.model.data'].get_object_reference(request.cr, openerp.SUPERUSER_ID, 'base', 'public_user')
76 request.uid = request.session.uid
78 def _authenticate(self, auth_method='user'):
80 if request.session.uid:
82 request.session.check_security()
83 # what if error in security.check()
84 # -> res_users.check()
85 # -> res_users.check_credentials()
86 except (openerp.exceptions.AccessDenied, openerp.http.SessionExpiredException):
87 # All other exceptions mean undetermined status (e.g. connection pool full),
89 request.session.logout()
90 getattr(self, "_auth_method_%s" % auth_method)()
91 except (openerp.exceptions.AccessDenied, openerp.http.SessionExpiredException):
94 _logger.exception("Exception during request Authentication.")
95 raise openerp.exceptions.AccessDenied()
98 def _handle_exception(self, exception):
99 # If handle_exception returns something different than None, it will be used as a response
100 return request._handle_exception(exception)
103 # locate the controller method
105 rule, arguments = self._find_handler(return_rule=True)
107 except werkzeug.exceptions.NotFound, e:
108 return self._handle_exception(e)
110 # check authentication level
112 auth_method = self._authenticate(func.routing["auth"])
114 # force a Forbidden exception with the original traceback
115 return self._handle_exception(
116 convert_exception_to(
117 werkzeug.exceptions.Forbidden))
119 processing = self._postprocess_args(arguments, rule)
124 # set and execute handler
126 request.set_handler(func, arguments, auth_method)
127 result = request.dispatch()
128 if isinstance(result, Exception):
131 return self._handle_exception(e)
135 def _postprocess_args(self, arguments, rule):
136 """ post process arg to set uid on browse records """
137 for arg in arguments.itervalues():
138 if isinstance(arg, orm.browse_record) and arg._uid is UID_PLACEHOLDER:
139 arg._uid = request.uid
143 return self._handle_exception(werkzeug.exceptions.NotFound())
145 def routing_map(self):
146 if not hasattr(self, '_routing_map'):
147 _logger.info("Generating routing map")
149 m = request.registry.get('ir.module.module')
150 ids = m.search(cr, openerp.SUPERUSER_ID, [('state', '=', 'installed'), ('name', '!=', 'web')], context=request.context)
151 installed = set(x['name'] for x in m.read(cr, 1, ids, ['name'], context=request.context))
152 if openerp.tools.config['test_enable']:
153 installed.add(openerp.modules.module.current_test)
154 mods = [''] + openerp.conf.server_wide_modules + sorted(installed)
155 self._routing_map = http.routing_map(mods, False, converters=self._get_converters())
157 return self._routing_map
159 def convert_exception_to(to_type, with_message=False):
160 """ Should only be called from an exception handler. Fetches the current
161 exception data from sys.exc_info() and creates a new exception of type
162 ``to_type`` with the original traceback.
164 If ``with_message`` is ``True``, sets the new exception's message to be
165 the stringification of the original exception. If ``False``, does not
166 set the new exception's message. Otherwise, uses ``with_message`` as the
167 new exception's message.
169 :type with_message: str|bool
171 etype, original, tb = sys.exc_info()
173 if with_message is False:
175 elif with_message is True:
176 message = str(original)
178 message = str(with_message)
180 raise to_type, message, tb