From 51f996ab4baea1197524fe2eb1d8476ae1ea6eae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C4=93teris=20Caune?= Date: Fri, 10 Sep 2021 17:52:03 +0300 Subject: [PATCH] Fix /api/v1/badges/ to handle requests with missing X-Api-Key header --- hc/api/decorators.py | 8 ++++++-- hc/api/tests/test_get_badges.py | 4 ++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/hc/api/decorators.py b/hc/api/decorators.py index 8ee64f6a..22df3105 100644 --- a/hc/api/decorators.py +++ b/hc/api/decorators.py @@ -16,8 +16,10 @@ def authorize(f): def wrapper(request, *args, **kwds): if "HTTP_X_API_KEY" in request.META: api_key = request.META["HTTP_X_API_KEY"] - else: + elif hasattr(request, "json"): api_key = str(request.json.get("api_key", "")) + else: + api_key = "" if len(api_key) != 32: return error("missing api key", 401) @@ -38,8 +40,10 @@ def authorize_read(f): def wrapper(request, *args, **kwds): if "HTTP_X_API_KEY" in request.META: api_key = request.META["HTTP_X_API_KEY"] - else: + elif hasattr(request, "json"): api_key = str(request.json.get("api_key", "")) + else: + api_key = "" if len(api_key) != 32: return error("missing api key", 401) diff --git a/hc/api/tests/test_get_badges.py b/hc/api/tests/test_get_badges.py index c9771be7..ef235d8e 100644 --- a/hc/api/tests/test_get_badges.py +++ b/hc/api/tests/test_get_badges.py @@ -41,3 +41,7 @@ class GetBadgesTestCase(BaseTestCase): def test_it_rejects_post(self): r = self.client.post(self.url, HTTP_X_API_KEY="X" * 32) self.assertEqual(r.status_code, 405) + + def test_it_handles_missing_api_key(self): + r = self.client.get(self.url) + self.assertContains(r, "missing api key", status_code=401)