Skip to content

Instantly share code, notes, and snippets.

@drkpkg
Last active March 3, 2022 15:12
Show Gist options
  • Save drkpkg/a91ddd233a7aa8f20b64a9d67cd02660 to your computer and use it in GitHub Desktop.
Save drkpkg/a91ddd233a7aa8f20b64a9d67cd02660 to your computer and use it in GitHub Desktop.
Odoo Http controller decorator
# Custom decorator
def check_origin_and_token(func):
@functools.wraps(func)
def secure_func(self, **kwargs):
headers = http.request.httprequest.headers
origin = '{}://{}'.format(headers.environ['wsgi.url_scheme'], headers['Host'])
_logger.info('New request from Origin:{}'.format(origin))
if 'X-Token' not in headers:
_logger.error('X-Token not found in headers')
raise BadRequest("Forbidden")
else:
token_header = headers['X-Token']
"""
You can add here how to get the authorized origins.
"""
#api_application = http.request.env['api.application'].sudo().search([
# ('api_token', '=', token_header),
# ('active', '=', True)
#])
#_logger.info('Found API Application: {}'.format(api_application.name))
# Check origin
#if not api_application:
# _logger.error('Origin not allowed: {}'.format(origin))
# raise BadRequest("Origin not allowed: {}".format(origin))
return func(self, **kwargs)
return secure_func
# Integration example
class FooApiController(http.Controller):
"""
Foo API Controller
foo: /api/v1/foo
"""
@check_origin_and_token
@http.route('/api/v1/foo', methods=['GET'], type="http", auth='public',
csrf=False, cors='*')
def knowledge(self, **kw):
res = []
for foo in request.env['res.foo'].search([('active', '=', True)]):
res.append({'id': foo.id, 'name': foo.name})
Response(json.dumps({'result': res}), content_type='application/json', status=200)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment