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

124 lines
3.7 KiB
Python
Raw Normal View History

2025-07-17 21:25:27 +02:00
# ================================================================
# services/auth/app/main.py (ENHANCED VERSION)
# ================================================================
"""
2025-07-17 21:25:27 +02:00
Authentication Service Main Application
Enhanced version with proper lifecycle management and microservices integration
"""
import logging
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
from app.api import auth, users
2025-07-17 21:25:27 +02:00
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__)
2025-07-17 21:25:27 +02:00
# 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",
2025-07-17 21:25:27 +02:00
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,
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-07-17 21:25:27 +02:00
# Health check endpoint
@app.get("/health")
async def health_check():
"""Health check endpoint"""
return {
"service": "auth-service",
2025-07-17 21:25:27 +02:00
"status": "healthy",
"version": "1.0.0"
}
2025-07-17 21:25:27 +02:00
# 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
2025-07-17 21:48:41 +02:00
metrics.observe_histogram("auth_request_duration_seconds", duration)
2025-07-17 21:25:27 +02:00
metrics.increment_counter("auth_requests_total")
return response