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)