2025-07-17 21:25:27 +02:00
|
|
|
# ================================================================
|
2025-07-18 12:34:28 +02:00
|
|
|
# services/auth/app/api/auth.py - Updated with modular monitoring
|
2025-07-17 21:25:27 +02:00
|
|
|
# ================================================================
|
2025-07-17 13:09:24 +02:00
|
|
|
"""
|
2025-07-18 12:34:28 +02:00
|
|
|
Authentication API routes - Enhanced with proper metrics access
|
2025-07-17 13:09:24 +02:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status, Request
|
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
2025-07-18 14:41:39 +02:00
|
|
|
import structlog
|
2025-07-17 13:09:24 +02:00
|
|
|
|
|
|
|
|
from app.core.database import get_db
|
2025-07-17 21:25:27 +02:00
|
|
|
from app.schemas.auth import (
|
|
|
|
|
UserRegistration, UserLogin, TokenResponse,
|
|
|
|
|
RefreshTokenRequest, UserResponse
|
|
|
|
|
)
|
2025-07-17 13:09:24 +02:00
|
|
|
from app.services.auth_service import AuthService
|
|
|
|
|
from app.core.security import security_manager
|
2025-07-18 12:34:28 +02:00
|
|
|
from shared.monitoring.decorators import track_execution_time, count_calls
|
2025-07-17 13:09:24 +02:00
|
|
|
|
2025-07-18 14:41:39 +02:00
|
|
|
logger = structlog.get_logger()
|
2025-07-17 13:09:24 +02:00
|
|
|
router = APIRouter()
|
2025-07-18 12:34:28 +02:00
|
|
|
|
|
|
|
|
def get_metrics_collector(request: Request):
|
|
|
|
|
"""Get metrics collector from app state"""
|
|
|
|
|
return getattr(request.app.state, 'metrics_collector', None)
|
2025-07-17 13:09:24 +02:00
|
|
|
|
|
|
|
|
@router.post("/register", response_model=UserResponse)
|
2025-07-18 12:34:28 +02:00
|
|
|
@track_execution_time("registration_duration_seconds", "auth-service")
|
2025-07-17 13:09:24 +02:00
|
|
|
async def register(
|
|
|
|
|
user_data: UserRegistration,
|
2025-07-18 12:34:28 +02:00
|
|
|
request: Request,
|
2025-07-17 13:09:24 +02:00
|
|
|
db: AsyncSession = Depends(get_db)
|
|
|
|
|
):
|
|
|
|
|
"""Register a new user"""
|
2025-07-18 12:34:28 +02:00
|
|
|
metrics = get_metrics_collector(request)
|
|
|
|
|
|
2025-07-17 13:09:24 +02:00
|
|
|
try:
|
2025-07-17 21:25:27 +02:00
|
|
|
result = await AuthService.register_user(user_data, db)
|
2025-07-18 12:34:28 +02:00
|
|
|
|
|
|
|
|
# Record successful registration
|
|
|
|
|
if metrics:
|
|
|
|
|
metrics.increment_counter("registration_total", labels={"status": "success"})
|
|
|
|
|
|
2025-07-17 21:25:27 +02:00
|
|
|
logger.info(f"User registration successful: {user_data.email}")
|
|
|
|
|
return result
|
2025-07-18 12:34:28 +02:00
|
|
|
|
|
|
|
|
except HTTPException as e:
|
|
|
|
|
# Record failed registration
|
|
|
|
|
if metrics:
|
|
|
|
|
metrics.increment_counter("registration_total", labels={"status": "failed"})
|
|
|
|
|
logger.warning(f"Registration failed for {user_data.email}: {e.detail}")
|
2025-07-17 13:09:24 +02:00
|
|
|
raise
|
2025-07-18 12:34:28 +02:00
|
|
|
|
2025-07-17 13:09:24 +02:00
|
|
|
except Exception as e:
|
2025-07-18 12:34:28 +02:00
|
|
|
# Record error
|
|
|
|
|
if metrics:
|
|
|
|
|
metrics.increment_counter("registration_total", labels={"status": "error"})
|
2025-07-17 21:25:27 +02:00
|
|
|
logger.error(f"Registration error for {user_data.email}: {e}")
|
2025-07-17 13:09:24 +02:00
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
|
|
|
detail="Registration failed"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
@router.post("/login", response_model=TokenResponse)
|
2025-07-18 12:34:28 +02:00
|
|
|
@track_execution_time("login_duration_seconds", "auth-service")
|
2025-07-17 13:09:24 +02:00
|
|
|
async def login(
|
|
|
|
|
login_data: UserLogin,
|
|
|
|
|
request: Request,
|
|
|
|
|
db: AsyncSession = Depends(get_db)
|
|
|
|
|
):
|
|
|
|
|
"""User login"""
|
2025-07-18 12:34:28 +02:00
|
|
|
metrics = get_metrics_collector(request)
|
|
|
|
|
|
2025-07-17 13:09:24 +02:00
|
|
|
try:
|
|
|
|
|
ip_address = request.client.host
|
|
|
|
|
user_agent = request.headers.get("user-agent", "")
|
|
|
|
|
|
2025-07-17 21:25:27 +02:00
|
|
|
result = await AuthService.login_user(login_data, db, ip_address, user_agent)
|
2025-07-18 12:34:28 +02:00
|
|
|
|
|
|
|
|
# Record successful login
|
|
|
|
|
if metrics:
|
|
|
|
|
metrics.increment_counter("login_success_total")
|
|
|
|
|
|
|
|
|
|
logger.info(f"Login successful for {login_data.email}")
|
2025-07-17 21:25:27 +02:00
|
|
|
return result
|
2025-07-18 12:34:28 +02:00
|
|
|
|
2025-07-17 21:25:27 +02:00
|
|
|
except HTTPException as e:
|
2025-07-18 12:34:28 +02:00
|
|
|
# Record failed login
|
|
|
|
|
if metrics:
|
|
|
|
|
metrics.increment_counter("login_failure_total", labels={"reason": "auth_failed"})
|
2025-07-17 21:25:27 +02:00
|
|
|
logger.warning(f"Login failed for {login_data.email}: {e.detail}")
|
2025-07-17 13:09:24 +02:00
|
|
|
raise
|
2025-07-18 12:34:28 +02:00
|
|
|
|
2025-07-17 13:09:24 +02:00
|
|
|
except Exception as e:
|
2025-07-18 12:34:28 +02:00
|
|
|
# Record login error
|
|
|
|
|
if metrics:
|
|
|
|
|
metrics.increment_counter("login_failure_total", labels={"reason": "error"})
|
2025-07-17 21:25:27 +02:00
|
|
|
logger.error(f"Login error for {login_data.email}: {e}")
|
2025-07-17 13:09:24 +02:00
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
|
|
|
detail="Login failed"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
@router.post("/refresh", response_model=TokenResponse)
|
2025-07-18 12:34:28 +02:00
|
|
|
@track_execution_time("token_refresh_duration_seconds", "auth-service")
|
2025-07-17 13:09:24 +02:00
|
|
|
async def refresh_token(
|
|
|
|
|
refresh_data: RefreshTokenRequest,
|
2025-07-18 12:34:28 +02:00
|
|
|
request: Request,
|
2025-07-17 13:09:24 +02:00
|
|
|
db: AsyncSession = Depends(get_db)
|
|
|
|
|
):
|
|
|
|
|
"""Refresh access token"""
|
2025-07-18 12:34:28 +02:00
|
|
|
metrics = get_metrics_collector(request)
|
|
|
|
|
|
2025-07-17 13:09:24 +02:00
|
|
|
try:
|
2025-07-18 12:34:28 +02:00
|
|
|
result = await AuthService.refresh_token(refresh_data.refresh_token, db)
|
|
|
|
|
|
|
|
|
|
# Record successful refresh
|
|
|
|
|
if metrics:
|
|
|
|
|
metrics.increment_counter("token_refresh_total", labels={"status": "success"})
|
|
|
|
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
except HTTPException as e:
|
|
|
|
|
# Record failed refresh
|
|
|
|
|
if metrics:
|
|
|
|
|
metrics.increment_counter("token_refresh_total", labels={"status": "failed"})
|
2025-07-17 13:09:24 +02:00
|
|
|
raise
|
2025-07-18 12:34:28 +02:00
|
|
|
|
2025-07-17 13:09:24 +02:00
|
|
|
except Exception as e:
|
2025-07-18 12:34:28 +02:00
|
|
|
# Record refresh error
|
|
|
|
|
if metrics:
|
|
|
|
|
metrics.increment_counter("token_refresh_total", labels={"status": "error"})
|
2025-07-17 13:09:24 +02:00
|
|
|
logger.error(f"Token refresh error: {e}")
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
|
|
|
detail="Token refresh failed"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
@router.post("/verify")
|
|
|
|
|
async def verify_token(
|
|
|
|
|
request: Request,
|
|
|
|
|
db: AsyncSession = Depends(get_db)
|
|
|
|
|
):
|
|
|
|
|
"""Verify access token"""
|
2025-07-18 12:34:28 +02:00
|
|
|
metrics = get_metrics_collector(request)
|
|
|
|
|
|
2025-07-17 13:09:24 +02:00
|
|
|
try:
|
|
|
|
|
auth_header = request.headers.get("Authorization")
|
|
|
|
|
if not auth_header or not auth_header.startswith("Bearer "):
|
2025-07-18 12:34:28 +02:00
|
|
|
if metrics:
|
|
|
|
|
metrics.increment_counter("token_verify_total", labels={"status": "no_token"})
|
2025-07-17 13:09:24 +02:00
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
2025-07-18 12:34:28 +02:00
|
|
|
detail="Missing or invalid authorization header"
|
2025-07-17 13:09:24 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
token = auth_header.split(" ")[1]
|
2025-07-18 17:14:30 +02:00
|
|
|
payload = await AuthService.verify_token(token)
|
2025-07-18 12:34:28 +02:00
|
|
|
|
|
|
|
|
# Record successful verification
|
|
|
|
|
if metrics:
|
|
|
|
|
metrics.increment_counter("token_verify_total", labels={"status": "success"})
|
|
|
|
|
|
|
|
|
|
return {"valid": True, "user_id": payload["sub"]}
|
|
|
|
|
|
|
|
|
|
except HTTPException as e:
|
|
|
|
|
# Record failed verification
|
|
|
|
|
if metrics:
|
|
|
|
|
metrics.increment_counter("token_verify_total", labels={"status": "failed"})
|
2025-07-17 13:09:24 +02:00
|
|
|
raise
|
2025-07-18 12:34:28 +02:00
|
|
|
|
2025-07-17 13:09:24 +02:00
|
|
|
except Exception as e:
|
2025-07-18 12:34:28 +02:00
|
|
|
# Record verification error
|
|
|
|
|
if metrics:
|
|
|
|
|
metrics.increment_counter("token_verify_total", labels={"status": "error"})
|
2025-07-17 13:09:24 +02:00
|
|
|
logger.error(f"Token verification error: {e}")
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
|
|
|
detail="Token verification failed"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
@router.post("/logout")
|
|
|
|
|
async def logout(
|
|
|
|
|
request: Request,
|
|
|
|
|
db: AsyncSession = Depends(get_db)
|
|
|
|
|
):
|
2025-07-18 12:34:28 +02:00
|
|
|
"""User logout"""
|
|
|
|
|
metrics = get_metrics_collector(request)
|
|
|
|
|
|
2025-07-17 13:09:24 +02:00
|
|
|
try:
|
|
|
|
|
auth_header = request.headers.get("Authorization")
|
2025-07-18 12:34:28 +02:00
|
|
|
if not auth_header or not auth_header.startswith("Bearer "):
|
|
|
|
|
if metrics:
|
|
|
|
|
metrics.increment_counter("logout_total", labels={"status": "no_token"})
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
|
|
|
detail="Missing or invalid authorization header"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
token = auth_header.split(" ")[1]
|
|
|
|
|
await AuthService.logout_user(token, db)
|
|
|
|
|
|
|
|
|
|
# Record successful logout
|
|
|
|
|
if metrics:
|
|
|
|
|
metrics.increment_counter("logout_total", labels={"status": "success"})
|
|
|
|
|
|
|
|
|
|
return {"message": "Logged out successfully"}
|
|
|
|
|
|
|
|
|
|
except HTTPException as e:
|
|
|
|
|
# Record failed logout
|
|
|
|
|
if metrics:
|
|
|
|
|
metrics.increment_counter("logout_total", labels={"status": "failed"})
|
|
|
|
|
raise
|
|
|
|
|
|
2025-07-17 13:09:24 +02:00
|
|
|
except Exception as e:
|
2025-07-18 12:34:28 +02:00
|
|
|
# Record logout error
|
|
|
|
|
if metrics:
|
|
|
|
|
metrics.increment_counter("logout_total", labels={"status": "error"})
|
2025-07-17 13:09:24 +02:00
|
|
|
logger.error(f"Logout error: {e}")
|
|
|
|
|
raise HTTPException(
|
|
|
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
|
|
|
detail="Logout failed"
|
2025-07-18 12:34:28 +02:00
|
|
|
)
|