|
| 1 | +# Copyright 2026 Camptocamp SA (https://www.camptocamp.com). |
| 2 | +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). |
| 3 | + |
| 4 | +import json |
| 5 | + |
| 6 | +from odoo.http import Controller, route |
| 7 | +from odoo.tests import HttpCase, new_test_user |
| 8 | +from odoo.tools import mute_logger |
| 9 | + |
| 10 | + |
| 11 | +class TestControllers(HttpCase): |
| 12 | + @classmethod |
| 13 | + def setUpClass(cls): |
| 14 | + super().setUpClass() |
| 15 | + cls.AuthApiKey = cls.env["auth.api.key"] |
| 16 | + cls.test_user = new_test_user( |
| 17 | + cls.env, |
| 18 | + name="Test User", |
| 19 | + login="test", |
| 20 | + password="test", |
| 21 | + email="test@test.com", |
| 22 | + group_ids=[cls.env.ref("base.group_user").id], |
| 23 | + company_id=cls.env.company.id, |
| 24 | + ) |
| 25 | + cls.api_key = cls.AuthApiKey.create( |
| 26 | + {"name": "good", "user_id": cls.test_user.id, "key": "api_key"} |
| 27 | + ) |
| 28 | + |
| 29 | + class DummyController(Controller): |
| 30 | + @route("/web/auth-api-key", type="http", auth="api_key", sitemap=False) |
| 31 | + def auth_api_key(self, **params): |
| 32 | + return json.dumps({"name": self.env.user.name}) |
| 33 | + |
| 34 | + @route("/web/auth-api-key-cors", type="http", auth="api_key", cors="*") |
| 35 | + def auth_api_key_cors(self, **params): |
| 36 | + return json.dumps({"name": self.env.user.name}) |
| 37 | + |
| 38 | + cls.env.registry.clear_cache("routing") |
| 39 | + cls.addClassCleanup(cls.env.registry.clear_cache, "routing") |
| 40 | + |
| 41 | + def test_auth_api_key_ok(self): |
| 42 | + res = self.url_open("/web/auth-api-key", headers={"API-KEY": self.api_key.key}) |
| 43 | + self.assertEqual(res.status_code, 200) |
| 44 | + self.assertEqual(res.json(), {"name": self.test_user.name}) |
| 45 | + |
| 46 | + @mute_logger("odoo.addons.base.models.ir_http") |
| 47 | + def test_auth_api_key_wrong(self): |
| 48 | + with self.assertLogs("odoo.http") as cm: |
| 49 | + res = self.url_open("/web/auth-api-key", headers={"API-KEY": "wrong"}) |
| 50 | + self.assertEqual(res.status_code, 403) |
| 51 | + self.assertIn("Access Denied", cm.output[0]) |
| 52 | + |
| 53 | + def test_auth_api_key_cors_options(self): |
| 54 | + res = self.url_open("/web/auth-api-key-cors", method="OPTIONS") |
| 55 | + self.assertEqual(res.status_code, 204) |
| 56 | + self.assertEqual(res.headers["Access-Control-Allow-Origin"], "*") |
| 57 | + self.assertIn("API-Key", res.headers["Access-Control-Allow-Headers"]) |
0 commit comments