From 1740ccbe30946aa6693a6a9ed8211a2ff7cfbf3d Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Wed, 9 Jul 2025 11:51:37 -0500 Subject: Improve error handling and reporting. - Refactor out common functionality into reusable utilities - Handle errors from the Authlib library/package - Handle 4xx errors generically. --- gn_auth/errors/authlib.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 gn_auth/errors/authlib.py (limited to 'gn_auth/errors/authlib.py') diff --git a/gn_auth/errors/authlib.py b/gn_auth/errors/authlib.py new file mode 100644 index 0000000..09862e3 --- /dev/null +++ b/gn_auth/errors/authlib.py @@ -0,0 +1,34 @@ +"""Handle authlib errors.""" +import json +import logging + +from authlib.integrations.flask_oauth2.errors import _HTTPException + +from gn_auth.errors.common import build_handler + +logger = logging.getLogger(__name__) + + +def __description__(body): + """Improve description for errors in authlib.oauth2.rfc6749.errors""" + _desc = body["error_description"] + match body["error"]: + case "missing_authorization": + return ( + 'The expected "Authorization: Bearer ..." token was not found ' + 'in the headers. Do please try again with the token provided.') + case _: + return _desc + + +def _http_exception_handler_(exc: _HTTPException): + """Handle Authlib's `_HTTPException` errors.""" + _handle = build_handler(__description__(json.loads(exc.body))) + return _handle(exc) + + +def authlib_error_handlers() -> dict: + """Return handlers for Authlib errors""" + return { + _HTTPException: _http_exception_handler_ + } -- cgit v1.2.3