IMP] Launch a 404 when ModelConverter's browse records can't resolve _rec_name. Also...
[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         # TODO:
45         # - raise routing.ValidationError() if no browse record can be createdm
46         # - support slug
47         return request.registry[self.model].browse(request.cr, UID_PLACEHOLDER, [int(i) for i in value.split(',')], context=request.context)
48
49     def to_url(self, value):
50         return ",".join(i.id for i in value)
51
52 class ir_http(osv.AbstractModel):
53     _name = 'ir.http'
54     _description = "HTTP routing"
55
56     def _get_converters(self):
57         return {'model': ModelConverter, 'models': ModelsConverter}
58
59     def _find_handler(self):
60         return self.routing_map().bind_to_environ(request.httprequest.environ).match()
61
62     def _auth_method_user(self):
63         request.uid = request.session.uid
64         if not request.uid:
65             raise http.SessionExpiredException("Session expired")
66
67     def _auth_method_admin(self):
68         if not request.db:
69             raise http.SessionExpiredException("No valid database for request %s" % request.httprequest)
70         request.uid = openerp.SUPERUSER_ID
71
72     def _auth_method_none(self):
73         request.disable_db = True
74         request.uid = None
75
76     def _authenticate(self, auth_method='user'):
77         if request.session.uid:
78             try:
79                 request.session.check_security()
80                 # what if error in security.check()
81                 #   -> res_users.check()
82                 #   -> res_users.check_credentials()
83             except Exception:
84                 request.session.logout()
85         getattr(self, "_auth_method_%s" % auth_method)()
86         return auth_method
87
88     def _handle_exception(self, exception):
89         raise
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:
102             # force a Forbidden exception with the original traceback
103             return self._handle_exception(
104                 convert_exception_to(
105                     werkzeug.exceptions.Forbidden))
106
107         # post process arg to set uid on browse records
108         for arg in arguments.itervalues():
109             if isinstance(arg, orm.browse_record) and arg._uid is UID_PLACEHOLDER:
110                 arg._uid = request.uid
111                 try:
112                     arg[arg._rec_name]
113                 except KeyError:
114                     return self._handle_exception(werkzeug.exceptions.NotFound())
115
116         # set and execute handler
117         try:
118             request.set_handler(func, arguments, auth_method)
119             result = request.dispatch()
120             if isinstance(result, Exception):
121                 raise result
122         except Exception, e:
123             return self._handle_exception(e)
124
125         return result
126
127     def routing_map(self):
128         if not hasattr(self, '_routing_map'):
129             _logger.info("Generating routing map")
130             cr = request.cr
131             m = request.registry.get('ir.module.module')
132             ids = m.search(cr, openerp.SUPERUSER_ID, [('state', '=', 'installed'), ('name', '!=', 'web')], context=request.context)
133             installed = set(x['name'] for x in m.read(cr, 1, ids, ['name'], context=request.context))
134             mods = ['', "web"] + sorted(installed)
135             self._routing_map = http.routing_map(mods, False, converters=self._get_converters())
136
137         return self._routing_map
138
139 def convert_exception_to(to_type, with_message=False):
140     """ Should only be called from an exception handler. Fetches the current
141     exception data from sys.exc_info() and creates a new exception of type
142     ``to_type`` with the original traceback.
143
144     If ``with_message`` is ``True``, sets the new exception's message to be
145     the stringification of the original exception. If ``False``, does not
146     set the new exception's message. Otherwise, uses ``with_message`` as the
147     new exception's message.
148
149     :type with_message: str|bool
150     """
151     etype, original, tb = sys.exc_info()
152     try:
153         if with_message is False:
154             message = None
155         elif with_message is True:
156             message = str(original)
157         else:
158             message = str(with_message)
159
160         raise to_type, message, tb
161     except to_type, e:
162         return e
163
164 # vim:et: