1 #----------------------------------------------------------
2 # ir_http modular http routing
3 #----------------------------------------------------------
8 import werkzeug.exceptions
9 import werkzeug.routing
14 import openerp.exceptions
16 from openerp import http
17 from openerp.http import request
18 from openerp.osv import osv, orm
20 _logger = logging.getLogger(__name__)
22 UID_PLACEHOLDER = object()
24 class ModelConverter(werkzeug.routing.BaseConverter):
26 def __init__(self, url_map, model=False):
27 super(ModelConverter, self).__init__(url_map)
29 self.regex = '([0-9]+)'
31 def to_python(self, value):
32 m = re.match(self.regex, value)
33 return request.registry[self.model].browse(
34 request.cr, UID_PLACEHOLDER, int(m.group(1)), context=request.context)
36 def to_url(self, value):
39 class ModelsConverter(werkzeug.routing.BaseConverter):
41 def __init__(self, url_map, model=False):
42 super(ModelsConverter, self).__init__(url_map)
44 # TODO add support for slug in the form [A-Za-z0-9-] bla-bla-89 -> id 89
45 self.regex = '([0-9,]+)'
47 def to_python(self, value):
48 return request.registry[self.model].browse(request.cr, UID_PLACEHOLDER, [int(i) for i in value.split(',')], context=request.context)
50 def to_url(self, value):
51 return ",".join(i.id for i in value)
53 class ir_http(osv.AbstractModel):
55 _description = "HTTP routing"
57 def _get_converters(self):
58 return {'model': ModelConverter, 'models': ModelsConverter}
60 def _find_handler(self, return_rule=False):
61 return self.routing_map().bind_to_environ(request.httprequest.environ).match(return_rule=return_rule)
63 def _auth_method_user(self):
64 request.uid = request.session.uid
66 raise http.SessionExpiredException("Session expired")
68 def _auth_method_none(self):
71 def _auth_method_public(self):
72 if not request.session.uid:
73 dummy, request.uid = self.pool['ir.model.data'].get_object_reference(request.cr, openerp.SUPERUSER_ID, 'base', 'public_user')
75 request.uid = request.session.uid
77 def _authenticate(self, auth_method='user'):
79 if request.session.uid:
81 request.session.check_security()
82 # what if error in security.check()
83 # -> res_users.check()
84 # -> res_users.check_credentials()
85 except (openerp.exceptions.AccessDenied, openerp.http.SessionExpiredException):
86 # All other exceptions mean undetermined status (e.g. connection pool full),
88 request.session.logout(keep_db=True)
89 getattr(self, "_auth_method_%s" % auth_method)()
90 except (openerp.exceptions.AccessDenied, openerp.http.SessionExpiredException):
93 _logger.exception("Exception during request Authentication.")
94 raise openerp.exceptions.AccessDenied()
97 def _handle_exception(self, exception):
98 # If handle_exception returns something different than None, it will be used as a response
100 return request._handle_exception(exception)
101 except openerp.exceptions.AccessDenied:
102 return werkzeug.exceptions.Forbidden()
105 # locate the controller method
107 rule, arguments = self._find_handler(return_rule=True)
109 except werkzeug.exceptions.NotFound, e:
110 return self._handle_exception(e)
112 # check authentication level
114 auth_method = self._authenticate(func.routing["auth"])
115 except Exception as e:
116 return self._handle_exception(e)
118 processing = self._postprocess_args(arguments, rule)
123 # set and execute handler
125 request.set_handler(func, arguments, auth_method)
126 result = request.dispatch()
127 if isinstance(result, Exception):
130 return self._handle_exception(e)
134 def _postprocess_args(self, arguments, rule):
135 """ post process arg to set uid on browse records """
136 for name, arg in arguments.items():
137 if isinstance(arg, orm.browse_record) and arg._uid is UID_PLACEHOLDER:
138 arguments[name] = arg.sudo(request.uid)
141 except openerp.models.MissingError:
142 return self._handle_exception(werkzeug.exceptions.NotFound())
144 def routing_map(self):
145 if not hasattr(self, '_routing_map'):
146 _logger.info("Generating routing map")
148 m = request.registry.get('ir.module.module')
149 ids = m.search(cr, openerp.SUPERUSER_ID, [('state', '=', 'installed'), ('name', '!=', 'web')], context=request.context)
150 installed = set(x['name'] for x in m.read(cr, 1, ids, ['name'], context=request.context))
151 if openerp.tools.config['test_enable']:
152 installed.add(openerp.modules.module.current_test)
153 mods = [''] + openerp.conf.server_wide_modules + sorted(installed)
154 self._routing_map = http.routing_map(mods, False, converters=self._get_converters())
156 return self._routing_map
158 def convert_exception_to(to_type, with_message=False):
159 """ Should only be called from an exception handler. Fetches the current
160 exception data from sys.exc_info() and creates a new exception of type
161 ``to_type`` with the original traceback.
163 If ``with_message`` is ``True``, sets the new exception's message to be
164 the stringification of the original exception. If ``False``, does not
165 set the new exception's message. Otherwise, uses ``with_message`` as the
166 new exception's message.
168 :type with_message: str|bool
170 etype, original, tb = sys.exc_info()
172 if with_message is False:
174 elif with_message is True:
175 message = str(original)
177 message = str(with_message)
179 raise to_type, message, tb