You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
3.9 KiB

  1. # -*- coding: utf-8 -*-
  2. import json
  3. import logging
  4. from functools import wraps
  5. from odoo import http
  6. import werkzeug
  7. _logger = logging.getLogger(__name__)
  8. class ApiException(Exception):
  9. INVALID_REQUEST = 'invalid_request'
  10. def __init__(self, message, code=None):
  11. super(Exception, self).__init__(message)
  12. self.code = code if code else self.INVALID_REQUEST
  13. def to_json(self):
  14. return {
  15. 'error': self.code,
  16. 'error_message': self.message
  17. }
  18. def resource(path, method, auth='user', clients=None):
  19. assert auth in ['user', 'client']
  20. def endpoint_decorator(func):
  21. @http.route(path, auth='public', type='http', methods=[method, 'OPTIONS'], csrf=False)
  22. @wraps(func)
  23. def func_wrapper(self, req, **query):
  24. cors_headers = {
  25. 'Access-Control-Allow-Origin': '*',
  26. 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, X-Debug-Mode, Authorization',
  27. 'Access-Control-Max-Age': 60 * 60 * 24,
  28. }
  29. if req.httprequest.method == 'OPTIONS':
  30. return http.Response(
  31. status=200,
  32. headers=cors_headers
  33. )
  34. try:
  35. access_token = None
  36. if 'Authorization' in req.httprequest.headers:
  37. authorization_header = req.httprequest.headers['Authorization']
  38. if authorization_header[:7] == 'Bearer ':
  39. access_token = authorization_header.split(' ', 1)[1]
  40. if access_token is None:
  41. access_token = query.get('access_token')
  42. if not access_token:
  43. raise ApiException(
  44. 'access_token param is missing',
  45. 'invalid_request',
  46. )
  47. if auth == 'user':
  48. token = req.env['galicea_openid_connect.access_token'].sudo().search(
  49. [('token', '=', access_token)]
  50. )
  51. if not token:
  52. raise ApiException(
  53. 'access_token is invalid',
  54. 'invalid_request',
  55. )
  56. req.uid = token.user_id.id
  57. elif auth == 'client':
  58. token = req.env['galicea_openid_connect.client_access_token'].sudo().search(
  59. [('token', '=', access_token)]
  60. )
  61. if not token:
  62. raise ApiException(
  63. 'access_token is invalid',
  64. 'invalid_request',
  65. )
  66. req.uid = token.client_id.system_user_id.id
  67. if clients:
  68. if token.client_id.id not in map(lambda c: req.env.ref(c).id, clients):
  69. raise ApiException('Access denied', 'restricted_app')
  70. ctx = req.context.copy()
  71. ctx.update({'client_id': token.client_id.id})
  72. req.context = ctx
  73. response = func(self, req, **query)
  74. return werkzeug.Response(
  75. response=json.dumps(response),
  76. headers=cors_headers,
  77. status=200
  78. )
  79. except Exception as e:
  80. status = 400
  81. if not isinstance(e, ApiException):
  82. _logger.exception('Unexpected exception while processing API request')
  83. e = ApiException('Unexpected server error', 'server_error')
  84. status = 500
  85. return werkzeug.Response(
  86. response=json.dumps(e.to_json()),
  87. status=status,
  88. headers=cors_headers
  89. )
  90. return func_wrapper
  91. return endpoint_decorator