Mint/add_cors_to_error_response (#312)

* add cors to error response and log validation errors

* shorten hash for invoices to avoid base64 escape characters
This commit is contained in:
callebtc
2023-09-08 15:21:14 +02:00
committed by GitHub
parent 87c0adc60d
commit 75e8428af7
2 changed files with 35 additions and 3 deletions

View File

@@ -58,5 +58,5 @@ def derive_keyset_id(keys: Dict[int, PublicKey]):
def random_hash() -> str: def random_hash() -> str:
"""Returns a base64-urlsafe encoded random hash.""" """Returns a base64-urlsafe encoded random hash."""
return base64.urlsafe_b64encode( return base64.urlsafe_b64encode(
bytes([random.getrandbits(8) for i in range(32)]) bytes([random.getrandbits(8) for i in range(30)])
).decode() ).decode()

View File

@@ -3,6 +3,10 @@ import sys
from traceback import print_exception from traceback import print_exception
from fastapi import FastAPI, status from fastapi import FastAPI, status
from fastapi.exception_handlers import (
request_validation_exception_handler as _request_validation_exception_handler,
)
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
# from fastapi_profiler import PyInstrumentProfilerMiddleware # from fastapi_profiler import PyInstrumentProfilerMiddleware
@@ -114,6 +118,12 @@ app = create_app()
@app.middleware("http") @app.middleware("http")
async def catch_exceptions(request: Request, call_next): async def catch_exceptions(request: Request, call_next):
CORS_HEADERS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Credentials": "true",
}
try: try:
return await call_next(request) return await call_next(request)
except Exception as e: except Exception as e:
@@ -124,22 +134,44 @@ async def catch_exceptions(request: Request, call_next):
if isinstance(e, CashuError): if isinstance(e, CashuError):
logger.error(f"CashuError: {err_message}") logger.error(f"CashuError: {err_message}")
# return with cors headers
return JSONResponse( return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, status_code=status.HTTP_400_BAD_REQUEST,
content={"detail": err_message, "code": e.code}, content={"detail": err_message, "code": e.code},
headers=CORS_HEADERS,
) )
logger.error(f"Exception: {err_message}") logger.error(f"Exception: {err_message}")
if settings.debug: if settings.debug:
print_exception(*sys.exc_info()) print_exception(*sys.exc_info())
return JSONResponse( return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, status_code=status.HTTP_400_BAD_REQUEST,
content={"detail": err_message, "code": 0}, content={"detail": err_message, "code": 0},
headers=CORS_HEADERS,
) )
async def request_validation_exception_handler(
request: Request, exc: RequestValidationError
) -> JSONResponse:
"""
This is a wrapper to the default RequestValidationException handler of FastAPI.
This function will be called when client input is not valid.
"""
query_params = request.query_params._dict
detail = {
"errors": exc.errors(),
"query_params": query_params,
}
# log the error
logger.error(detail)
# pass on
return await _request_validation_exception_handler(request, exc)
@app.on_event("startup") @app.on_event("startup")
async def startup_mint(): async def startup_mint():
await start_mint_init() await start_mint_init()
app.include_router(router=router) app.include_router(router=router)
app.add_exception_handler(RequestValidationError, request_validation_exception_handler)