aboutsummaryrefslogtreecommitdiff
"""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_
    }