1 #----------------------------------------------------------
2 # ir_http modular http routing
3 #----------------------------------------------------------
8 import werkzeug.exceptions
9 import werkzeug.routing
12 from openerp import http
13 from openerp.http import request
14 from openerp.osv import osv, orm
16 _logger = logging.getLogger(__name__)
19 # FIXME: replace by proxy on request.uid?
22 class ModelConverter(werkzeug.routing.BaseConverter):
24 def __init__(self, url_map, model=False):
25 super(ModelConverter, self).__init__(url_map)
27 self.regex = '([0-9]+)'
29 def to_python(self, value):
30 m = re.match(self.regex, value)
31 return request.registry[self.model].browse(
32 request.cr, _uid, int(m.group(1)), context=request.context)
34 def to_url(self, value):
37 class ModelsConverter(werkzeug.routing.BaseConverter):
39 def __init__(self, url_map, model=False):
40 super(ModelsConverter, self).__init__(url_map)
42 # TODO add support for slug in the form [A-Za-z0-9-] bla-bla-89 -> id 89
43 self.regex = '([0-9,]+)'
45 def to_python(self, value):
47 # - raise routing.ValidationError() if no browse record can be createdm
49 return request.registry[self.model].browse(request.cr, _uid, [int(i) for i in value.split(',')], context=request.context)
51 def to_url(self, value):
52 return ",".join(i.id for i in value)
54 class ir_http(osv.AbstractModel):
57 _description = "HTTP routing"
59 def _get_converters(self):
60 return {'model': ModelConverter, 'models': ModelsConverter}
62 def _find_handler(self):
63 return self.routing_map().bind_to_environ(request.httprequest.environ).match()
65 def _auth_method_user(self):
66 request.uid = request.session.uid
68 raise http.SessionExpiredException("Session expired")
70 def _auth_method_admin(self):
72 raise http.SessionExpiredException("No valid database for request %s" % request.httprequest)
73 request.uid = openerp.SUPERUSER_ID
75 def _auth_method_none(self):
76 request.disable_db = True
79 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 http.SessionExpiredException:
87 request.session.logout()
88 raise http.SessionExpiredException("Session expired for request %s" % request.httprequest)
89 getattr(self, "_auth_method_%s" % auth_method)()
92 def _handle_exception(self, exception):
93 if isinstance(exception, openerp.exceptions.AccessError):
96 code = getattr(exception, 'code', 500)
98 fn = getattr(self, '_handle_%d' % code, self._handle_unknown_exception)
101 def _handle_unknown_exception(self, exception):
105 # locate the controller method
107 func, arguments = self._find_handler()
108 except werkzeug.exceptions.NotFound, e:
109 return self._handle_exception(e)
111 # check authentication level
113 auth_method = self._authenticate(getattr(func, "auth", None))
115 # force a Forbidden exception with the original traceback
116 return self._handle_exception(
117 convert_exception_to(
118 werkzeug.exceptions.Forbidden))
120 # post process arg to set uid on browse records
121 for arg in arguments.itervalues():
122 if isinstance(arg, orm.browse_record) and arg._uid is _uid:
123 arg._uid = request.uid
125 # set and execute handler
127 request.set_handler(func, arguments, auth_method)
128 result = request.dispatch()
129 if isinstance(result, Exception):
132 return self._handle_exception(e)
136 def routing_map(self):
137 if not hasattr(self, '_routing_map'):
138 _logger.info("Generating routing map")
140 m = request.registry.get('ir.module.module')
141 ids = m.search(cr, openerp.SUPERUSER_ID, [('state', '=', 'installed'), ('name', '!=', 'web')], context=request.context)
142 installed = set(x['name'] for x in m.read(cr, 1, ids, ['name'], context=request.context))
143 mods = ['', "web"] + sorted(installed)
144 self._routing_map = http.routing_map(mods, False, converters=self._get_converters())
146 return self._routing_map
148 def convert_exception_to(to_type, with_message=False):
149 """ Should only be called from an exception handler. Fetches the current
150 exception data from sys.exc_info() and creates a new exception of type
151 ``to_type`` with the original traceback.
153 If ``with_message`` is ``True``, sets the new exception's message to be
154 the stringification of the original exception. If ``False``, does not
155 set the new exception's message. Otherwise, uses ``with_message`` as the
156 new exception's message.
158 :type with_message: str|bool
160 etype, original, tb = sys.exc_info()
162 if with_message is False:
164 elif with_message is True:
165 message = str(original)
167 message = str(with_message)
169 raise to_type, message, tb