2025-07-17 13:09:24 +02:00
|
|
|
"""
|
2025-07-18 12:34:28 +02:00
|
|
|
Authentication Service Main Application - Fixed middleware issue
|
2025-07-17 13:09:24 +02:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
import logging
|
2025-07-17 21:25:27 +02:00
|
|
|
from fastapi import FastAPI, Request
|
2025-07-17 13:09:24 +02:00
|
|
|
from fastapi.middleware.cors import CORSMiddleware
|
2025-07-17 21:25:27 +02:00
|
|
|
from fastapi.responses import JSONResponse
|
|
|
|
|
from contextlib import asynccontextmanager
|
2025-07-17 13:09:24 +02:00
|
|
|
|
|
|
|
|
from app.core.config import settings
|
2025-07-17 21:25:27 +02:00
|
|
|
from app.core.database import engine, create_tables
|
2025-07-17 13:09:24 +02:00
|
|
|
from app.api import auth, users
|
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-17 13:09:24 +02:00
|
|
|
|
2025-07-18 12:34:28 +02:00
|
|
|
# Setup logging first
|
2025-07-17 13:09:24 +02:00
|
|
|
setup_logging("auth-service", settings.LOG_LEVEL)
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
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)
|
|
|
|
|
metrics_collector.register_counter("registration_total", "Total user registrations")
|
|
|
|
|
metrics_collector.register_counter("login_success_total", "Successful logins")
|
|
|
|
|
metrics_collector.register_counter("login_failure_total", "Failed logins")
|
|
|
|
|
metrics_collector.register_counter("token_refresh_total", "Token refresh requests")
|
|
|
|
|
metrics_collector.register_counter("token_verify_total", "Token verification requests")
|
|
|
|
|
metrics_collector.register_counter("logout_total", "User logout requests")
|
|
|
|
|
metrics_collector.register_counter("errors_total", "Total errors")
|
|
|
|
|
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
|
|
|
|
|
async for db in get_db():
|
|
|
|
|
await db.execute("SELECT 1")
|
|
|
|
|
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-17 13:09:24 +02:00
|
|
|
|
2025-07-18 12:34:28 +02:00
|
|
|
# CORS middleware (added after metrics setup)
|
2025-07-17 13:09:24 +02:00
|
|
|
app.add_middleware(
|
|
|
|
|
CORSMiddleware,
|
2025-07-17 21:25:27 +02:00
|
|
|
allow_origins=["*"], # Configure properly for production
|
2025-07-17 13:09:24 +02:00
|
|
|
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-07-17 13:09:24 +02:00
|
|
|
|
2025-07-18 12:34:28 +02:00
|
|
|
# Health check endpoint with comprehensive checks
|
2025-07-17 13:09:24 +02:00
|
|
|
@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
|
|
|
)
|