# ================================================================ # services/auth/app/main.py (ENHANCED VERSION) # ================================================================ """ Authentication Service Main Application Enhanced version with proper lifecycle management and microservices integration """ import logging from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from contextlib import asynccontextmanager from app.core.config import settings from app.core.database import engine, create_tables from app.api import auth, users from app.services.messaging import setup_messaging, cleanup_messaging from shared.monitoring.logging import setup_logging from shared.monitoring.metrics import MetricsCollector # Setup logging setup_logging("auth-service", settings.LOG_LEVEL) logger = logging.getLogger(__name__) # Initialize metrics metrics = MetricsCollector("auth_service") @asynccontextmanager async def lifespan(app: FastAPI): """Application lifespan events""" # Startup logger.info("Starting Authentication Service...") # Create database tables await create_tables() logger.info("Database tables created") # Setup messaging await setup_messaging() logger.info("Messaging setup complete") # Register metrics metrics.register_counter("auth_requests_total", "Total authentication requests") metrics.register_counter("auth_login_success_total", "Successful logins") metrics.register_counter("auth_login_failure_total", "Failed logins") metrics.register_counter("auth_registration_total", "User registrations") metrics.register_histogram("auth_request_duration_seconds", "Request duration") logger.info("Authentication Service started successfully") yield # Shutdown logger.info("Shutting down Authentication Service...") await cleanup_messaging() await engine.dispose() logger.info("Authentication Service shutdown complete") # Create FastAPI app 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", lifespan=lifespan ) # CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], # Configure properly for production allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Include routers app.include_router(auth.router, prefix="/api/v1/auth", tags=["authentication"]) app.include_router(users.router, prefix="/api/v1/users", tags=["users"]) # Health check endpoint @app.get("/health") async def health_check(): """Health check endpoint""" return { "service": "auth-service", "status": "healthy", "version": "1.0.0" } # Metrics endpoint @app.get("/metrics") async def get_metrics(): """Prometheus metrics endpoint""" return metrics.get_metrics() # Exception handlers @app.exception_handler(Exception) async def global_exception_handler(request: Request, exc: Exception): """Global exception handler""" logger.error(f"Unhandled exception: {exc}", exc_info=True) return JSONResponse( status_code=500, content={"detail": "Internal server error"} ) # Request middleware for metrics @app.middleware("http") async def metrics_middleware(request: Request, call_next): """Middleware to collect metrics""" import time start_time = time.time() response = await call_next(request) # Record metrics duration = time.time() - start_time metrics.record_histogram("auth_request_duration_seconds", duration) metrics.increment_counter("auth_requests_total") return response