Phase 1 fix auth redirect API handling and route issues
This commit is contained in:
+28
-1
@@ -1,4 +1,5 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.middleware.sessions import SessionMiddleware
|
||||
|
||||
from app.core.settings import get_settings
|
||||
@@ -7,9 +8,34 @@ from app.core.middleware.domain_resolver import DomainResolverMiddleware
|
||||
from app.core.middleware.security_headers import SecurityHeadersMiddleware
|
||||
from app.core.startup import on_startup
|
||||
from app.core.api import api_router
|
||||
from app.core.http_responses import auth_required_response, forbidden_response, not_found_response, wants_json
|
||||
from app.ui.app import mount_ui
|
||||
|
||||
|
||||
def _register_error_handlers(app: FastAPI) -> None:
|
||||
@app.exception_handler(PermissionError)
|
||||
async def permission_error_handler(request: Request, exc: PermissionError):
|
||||
message = str(exc) or "Access denied"
|
||||
if "csrf" in message.lower():
|
||||
return JSONResponse({"detail": "CSRF validation failed"}, status_code=403) if wants_json(request) else forbidden_response(request, "CSRF validation failed")
|
||||
if "not authenticated" in message.lower():
|
||||
return auth_required_response(request)
|
||||
return forbidden_response(request, message)
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
detail = exc.detail if isinstance(exc.detail, str) else "Error"
|
||||
if request.url.path.startswith("/api"):
|
||||
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code, headers=exc.headers)
|
||||
if exc.status_code == 401:
|
||||
return auth_required_response(request)
|
||||
if exc.status_code == 403:
|
||||
return forbidden_response(request, detail or "Access denied")
|
||||
if exc.status_code == 404:
|
||||
return not_found_response(request, detail or "Not found")
|
||||
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code, headers=exc.headers)
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
s = get_settings()
|
||||
app = FastAPI(title=s.APP_NAME, debug=s.DEBUG)
|
||||
@@ -30,6 +56,7 @@ def create_app() -> FastAPI:
|
||||
)
|
||||
|
||||
app.add_event_handler("startup", lambda: on_startup(app))
|
||||
_register_error_handlers(app)
|
||||
|
||||
app.include_router(api_router, prefix="/api")
|
||||
mount_ui(app)
|
||||
|
||||
Reference in New Issue
Block a user