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

174 lines
6.8 KiB
Python
Raw Normal View History

"""
2025-09-29 13:13:12 +02:00
Authentication Service Main Application
"""
2025-09-29 13:13:12 +02:00
from fastapi import FastAPI
2025-09-30 08:12:45 +02:00
from sqlalchemy import text
from app.core.config import settings
2025-09-29 13:13:12 +02:00
from app.core.database import database_manager
2026-01-16 09:55:54 +01:00
from app.api import auth_operations, users, onboarding_progress, consent, data_export, account_deletion, internal_demo, password_reset
2025-09-29 13:13:12 +02:00
from shared.service_base import StandardFastAPIService
2025-12-05 20:07:01 +01:00
from shared.messaging import UnifiedEventPublisher
2025-09-29 13:13:12 +02:00
class AuthService(StandardFastAPIService):
"""Authentication Service with standardized setup"""
2025-07-18 12:34:28 +02:00
2025-09-30 08:12:45 +02:00
async def on_startup(self, app):
"""Custom startup logic including migration verification"""
await self.verify_migrations()
await super().on_startup(app)
async def verify_migrations(self):
"""Verify database schema matches the latest migrations."""
try:
async with self.database_manager.get_session() as session:
2025-09-30 21:58:10 +02:00
# Check if alembic_version table exists
result = await session.execute(text("""
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'alembic_version'
)
"""))
table_exists = result.scalar()
if table_exists:
# If table exists, check the version
result = await session.execute(text("SELECT version_num FROM alembic_version"))
version = result.scalar()
self.logger.info(f"Migration verification successful: {version}")
else:
# If table doesn't exist, migrations might not have run yet
# This is OK - the migration job should create it
self.logger.warning("alembic_version table does not exist yet - migrations may not have run")
2025-09-30 08:12:45 +02:00
except Exception as e:
2025-09-30 21:58:10 +02:00
self.logger.warning(f"Migration verification failed (this may be expected during initial setup): {e}")
2025-09-30 08:12:45 +02:00
2025-09-29 13:13:12 +02:00
def __init__(self):
# Define expected database tables for health checks
auth_expected_tables = [
'users', 'refresh_tokens', 'user_onboarding_progress',
2025-10-16 07:28:04 +02:00
'user_onboarding_summary', 'login_attempts', 'user_consents',
'consent_history', 'audit_logs'
2025-09-29 13:13:12 +02:00
]
2025-07-18 12:34:28 +02:00
2025-09-29 13:13:12 +02:00
# Define custom metrics for auth service
auth_custom_metrics = {
"registration_total": {
"type": "counter",
"description": "Total user registrations by status",
"labels": ["status"]
},
"login_success_total": {
"type": "counter",
"description": "Total successful user logins"
},
"login_failure_total": {
"type": "counter",
"description": "Total failed user logins by reason",
"labels": ["reason"]
},
"token_refresh_total": {
"type": "counter",
"description": "Total token refreshes by status",
"labels": ["status"]
},
"token_verify_total": {
"type": "counter",
"description": "Total token verifications by status",
"labels": ["status"]
},
"logout_total": {
"type": "counter",
"description": "Total user logouts by status",
"labels": ["status"]
},
"registration_duration_seconds": {
"type": "histogram",
"description": "Registration request duration"
},
"login_duration_seconds": {
"type": "histogram",
"description": "Login request duration"
},
"token_refresh_duration_seconds": {
"type": "histogram",
"description": "Token refresh duration"
}
}
2025-07-17 21:25:27 +02:00
2025-09-29 13:13:12 +02:00
super().__init__(
service_name="auth-service",
app_name="Authentication Service",
description="Handles user authentication and authorization for bakery forecasting platform",
version="1.0.0",
log_level=settings.LOG_LEVEL,
2025-10-06 15:27:01 +02:00
api_prefix="", # Empty because RouteBuilder already includes /api/v1
2025-09-29 13:13:12 +02:00
database_manager=database_manager,
expected_tables=auth_expected_tables,
enable_messaging=True,
custom_metrics=auth_custom_metrics
2025-07-18 13:39:40 +02:00
)
2025-09-29 13:13:12 +02:00
async def _setup_messaging(self):
"""Setup messaging for auth service"""
2025-12-05 20:07:01 +01:00
from shared.messaging import RabbitMQClient
try:
self.rabbitmq_client = RabbitMQClient(settings.RABBITMQ_URL, service_name="auth-service")
await self.rabbitmq_client.connect()
# Create event publisher
self.event_publisher = UnifiedEventPublisher(self.rabbitmq_client, "auth-service")
self.logger.info("Auth service messaging setup completed")
except Exception as e:
self.logger.error("Failed to setup auth messaging", error=str(e))
raise
2025-09-29 13:13:12 +02:00
async def _cleanup_messaging(self):
"""Cleanup messaging for auth service"""
2025-12-05 20:07:01 +01:00
try:
if self.rabbitmq_client:
await self.rabbitmq_client.disconnect()
self.logger.info("Auth service messaging cleanup completed")
except Exception as e:
self.logger.error("Error during auth messaging cleanup", error=str(e))
2025-07-17 21:25:27 +02:00
2025-09-29 13:13:12 +02:00
async def on_shutdown(self, app: FastAPI):
"""Custom shutdown logic for auth service"""
self.logger.info("Authentication Service shutdown complete")
2025-09-29 13:13:12 +02:00
def get_service_features(self):
"""Return auth-specific features"""
return [
"user_authentication",
"token_management",
"user_onboarding",
"role_based_access",
"messaging_integration"
]
2025-09-29 13:13:12 +02:00
# Create service instance
service = AuthService()
# Create FastAPI app with standardized setup
app = service.create_app(
docs_url="/docs",
redoc_url="/redoc"
)
# Setup standard endpoints
service.setup_standard_endpoints()
2025-07-17 21:25:27 +02:00
2025-09-29 13:13:12 +02:00
# Include routers with specific configurations
2025-10-06 15:27:01 +02:00
# Note: Routes now use RouteBuilder which includes full paths, so no prefix needed
service.add_router(auth_operations.router, tags=["authentication"])
service.add_router(users.router, tags=["users"])
service.add_router(onboarding_progress.router, tags=["onboarding"])
2025-10-16 07:28:04 +02:00
service.add_router(consent.router, tags=["gdpr", "consent"])
service.add_router(data_export.router, tags=["gdpr", "data-export"])
service.add_router(account_deletion.router, tags=["gdpr", "account-deletion"])
2025-12-13 23:57:54 +01:00
service.add_router(internal_demo.router, tags=["internal-demo"])
2026-01-16 09:55:54 +01:00
service.add_router(password_reset.router, tags=["password-reset"])