From a44c1da1fe69e62e2b04be04d7eb3a7266f3c5a2 Mon Sep 17 00:00:00 2001 From: Anton Bakker Date: Thu, 18 Jan 2024 16:43:17 +0100 Subject: [PATCH] add api-key header to oas document (configurable) --- .vscode/launch.json | 4 +++- src/coordinate_transformation_api/settings.py | 10 ++++++++ src/coordinate_transformation_api/util.py | 23 +++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 03970a8..3aeb45e 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -19,7 +19,9 @@ "LOG_LEVEL": "DEBUG", "DEBUG": "true", "MAX_SIZE_REQUEST_BODY": "5000000", - "CORS_ALLOW_ORIGINS": "*" + "CORS_ALLOW_ORIGINS": "*", + "API_KEY_IN_OAS": "true", + "EXAMPLE_API_KEY": "FOOBAR" }, "jinja": true, "justMyCode": false diff --git a/src/coordinate_transformation_api/settings.py b/src/coordinate_transformation_api/settings.py index 6fe2660..01028da 100644 --- a/src/coordinate_transformation_api/settings.py +++ b/src/coordinate_transformation_api/settings.py @@ -89,6 +89,16 @@ class AppSettings(BaseSettings): default=False, description="enable access log, defaults to False", ) + api_key_in_oas: bool = Field( + alias="API_KEY_IN_OAS", + default=False, + description="add required api key to oas document", + ) + example_api_key: str | None = Field( + alias="EXAMPLE_API_KEY", + default=None, + description="default api key to expose in oas document", + ) @classmethod def settings_customise_sources( # type: ignore # noqa: PLR0913 diff --git a/src/coordinate_transformation_api/util.py b/src/coordinate_transformation_api/util.py index 6e792aa..785408b 100644 --- a/src/coordinate_transformation_api/util.py +++ b/src/coordinate_transformation_api/util.py @@ -259,6 +259,29 @@ def init_oas(crs_config) -> tuple[dict, str, str]: oas["info"]["version"] = version("coordinate_transformation_api") oas["components"]["schemas"]["CrsEnum"]["enum"] = available_crss oas["components"]["schemas"]["CrsHeaderEnum"]["enum"] = available_crss_uri + + if app_settings.api_key_in_oas: + api_key_header_def = { + "APIKeyHeader": { + "type": "apiKey", + "in": "header", + "name": "apikey", + } + } + security: dict = {"security": [{"APIKeyHeader": []}]} + if app_settings.example_api_key is not None: + api_key_description = f"\n\nDemo API key is `{app_settings.example_api_key}` en is bedoeld voor exploratief gebruik van de API. " + oas["info"]["description"] = ( + oas["info"]["description"] + api_key_description + ) + + oas["components"]["securitySchemes"] = api_key_header_def + + for path in oas["paths"]: + if path != "/openapi": + for op in oas["paths"][path]: + oas["paths"][path][op] = oas["paths"][path][op] | security + api_title = oas["info"]["title"] return (oas, api_title, oas["info"]["version"])