Files
bakery-ia/services/auth/app/main.py

180 lines
6.1 KiB
Python
Raw Normal View History

"""
2025-07-18 12:34:28 +02:00
Authentication Service Main Application - Fixed middleware issue
"""
2025-07-18 14:41:39 +02:00
import structlog
2025-07-17 21:25:27 +02:00
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
2025-07-17 21:25:27 +02:00
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager
from app.core.config import settings
2025-07-17 21:25:27 +02:00
from app.core.database import engine, create_tables
2025-08-11 07:01:08 +02:00
from app.api import auth, users, onboarding
2025-07-17 21:25:27 +02:00
from app.services.messaging import setup_messaging, cleanup_messaging
2025-07-18 12:34:28 +02:00
from shared.monitoring import setup_logging, HealthChecker
from shared.monitoring.metrics import setup_metrics_early
2025-07-18 12:34:28 +02:00
# Setup logging first
setup_logging("auth-service", settings.LOG_LEVEL)
2025-07-18 14:41:39 +02:00
logger = structlog.get_logger()
2025-07-18 12:34:28 +02:00
# Global variables for lifespan access
metrics_collector = None
health_checker = None
# Create FastAPI app FIRST
app = FastAPI(
title="Authentication Service",
description="Handles user authentication and authorization for bakery forecasting platform",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc"
)
# Setup metrics BEFORE any middleware and BEFORE lifespan
# This must happen before the app starts
metrics_collector = setup_metrics_early(app, "auth-service")
2025-07-17 21:25:27 +02:00
@asynccontextmanager
async def lifespan(app: FastAPI):
2025-07-18 12:34:28 +02:00
"""Application lifespan events - NO MIDDLEWARE ADDED HERE"""
global health_checker
2025-07-17 21:25:27 +02:00
# Startup
logger.info("Starting Authentication Service...")
2025-07-18 12:34:28 +02:00
try:
# Create database tables
await create_tables()
logger.info("Database tables created")
# Setup messaging
await setup_messaging()
logger.info("Messaging setup complete")
# Register custom metrics (metrics_collector already exists)
2025-07-18 13:39:40 +02:00
metrics_collector.register_counter(
"registration_total",
"Total user registrations by status",
labels=["status"] # Add this line
)
metrics_collector.register_counter(
"login_success_total",
"Total successful user logins"
)
metrics_collector.register_counter(
"login_failure_total",
"Total failed user logins by reason",
labels=["reason"] # Add this line, based on auth.py usage
)
metrics_collector.register_counter(
"token_refresh_total",
"Total token refreshes by status",
labels=["status"] # Add this line
)
metrics_collector.register_counter(
"token_verify_total",
"Total token verifications by status",
labels=["status"] # Add this line
)
metrics_collector.register_counter(
"logout_total",
"Total user logouts by status",
labels=["status"] # Add this line
)
metrics_collector.register_counter("errors_total", "Total errors", labels=["type"]) # Add this line
2025-07-18 12:34:28 +02:00
metrics_collector.register_histogram("registration_duration_seconds", "Registration request duration")
metrics_collector.register_histogram("login_duration_seconds", "Login request duration")
metrics_collector.register_histogram("token_refresh_duration_seconds", "Token refresh duration")
# Setup health checker
health_checker = HealthChecker("auth-service")
# Add database health check
async def check_database():
try:
from app.core.database import get_db
2025-08-08 09:08:41 +02:00
from sqlalchemy import text
2025-07-18 12:34:28 +02:00
async for db in get_db():
2025-08-08 09:08:41 +02:00
await db.execute(text("SELECT 1"))
2025-07-18 12:34:28 +02:00
return True
except Exception as e:
return f"Database error: {e}"
health_checker.add_check("database", check_database, timeout=5.0, critical=True)
# Add messaging health check
def check_messaging():
try:
# Add your messaging health check logic here
return True
except Exception as e:
return f"Messaging error: {e}"
health_checker.add_check("messaging", check_messaging, timeout=3.0, critical=False)
# Store health checker in app state
app.state.health_checker = health_checker
logger.info("Authentication Service started successfully")
except Exception as e:
logger.error(f"Failed to start Authentication Service: {e}")
raise
2025-07-17 21:25:27 +02:00
yield
# Shutdown
logger.info("Shutting down Authentication Service...")
2025-07-18 12:34:28 +02:00
try:
await cleanup_messaging()
await engine.dispose()
logger.info("Authentication Service shutdown complete")
except Exception as e:
logger.error(f"Error during shutdown: {e}")
2025-07-17 21:25:27 +02:00
2025-07-18 12:34:28 +02:00
# Set lifespan AFTER metrics setup
app.router.lifespan_context = lifespan
2025-07-18 12:34:28 +02:00
# CORS middleware (added after metrics setup)
app.add_middleware(
CORSMiddleware,
2025-07-17 21:25:27 +02:00
allow_origins=["*"], # Configure properly for production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
2025-07-17 21:25:27 +02:00
app.include_router(auth.router, prefix="/api/v1/auth", tags=["authentication"])
app.include_router(users.router, prefix="/api/v1/users", tags=["users"])
2025-08-11 07:01:08 +02:00
app.include_router(onboarding.router, prefix="/api/v1/users", tags=["onboarding"])
2025-07-18 12:34:28 +02:00
# Health check endpoint with comprehensive checks
@app.get("/health")
async def health_check():
2025-07-18 12:34:28 +02:00
"""Comprehensive health check endpoint"""
if health_checker:
return await health_checker.check_health()
else:
return {
"service": "auth-service",
"status": "healthy",
"version": "1.0.0"
}
2025-07-17 21:25:27 +02:00
# Exception handlers
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
2025-07-18 12:34:28 +02:00
"""Global exception handler with metrics"""
2025-07-17 21:25:27 +02:00
logger.error(f"Unhandled exception: {exc}", exc_info=True)
2025-07-18 12:34:28 +02:00
# Record error metric if available
if metrics_collector:
metrics_collector.increment_counter("errors_total", labels={"type": "unhandled"})
2025-07-17 21:25:27 +02:00
return JSONResponse(
status_code=500,
content={"detail": "Internal server error"}
2025-07-18 12:34:28 +02:00
)