Adds auth module

This commit is contained in:
Urtzi Alfaro
2025-07-17 21:25:27 +02:00
parent 654d1c2fe8
commit efca9a125a
19 changed files with 1169 additions and 406 deletions

View File

@@ -1,5 +1,8 @@
# ================================================================
# services/auth/app/api/auth.py (ENHANCED VERSION)
# ================================================================
"""
Authentication API routes
Authentication API routes - Enhanced with proper error handling and logging
"""
from fastapi import APIRouter, Depends, HTTPException, status, Request
@@ -7,12 +10,17 @@ from sqlalchemy.ext.asyncio import AsyncSession
import logging
from app.core.database import get_db
from app.schemas.auth import UserRegistration, UserLogin, TokenResponse, RefreshTokenRequest, UserResponse
from app.schemas.auth import (
UserRegistration, UserLogin, TokenResponse,
RefreshTokenRequest, UserResponse
)
from app.services.auth_service import AuthService
from app.core.security import security_manager
from shared.monitoring.metrics import MetricsCollector
logger = logging.getLogger(__name__)
router = APIRouter()
metrics = MetricsCollector("auth_service")
@router.post("/register", response_model=UserResponse)
async def register(
@@ -21,11 +29,14 @@ async def register(
):
"""Register a new user"""
try:
return await AuthService.register_user(user_data, db)
metrics.increment_counter("auth_registration_total")
result = await AuthService.register_user(user_data, db)
logger.info(f"User registration successful: {user_data.email}")
return result
except HTTPException:
raise
except Exception as e:
logger.error(f"Registration error: {e}")
logger.error(f"Registration error for {user_data.email}: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Registration failed"
@@ -42,11 +53,16 @@ async def login(
ip_address = request.client.host
user_agent = request.headers.get("user-agent", "")
return await AuthService.login_user(login_data, db, ip_address, user_agent)
except HTTPException:
result = await AuthService.login_user(login_data, db, ip_address, user_agent)
metrics.increment_counter("auth_login_success_total")
return result
except HTTPException as e:
metrics.increment_counter("auth_login_failure_total")
logger.warning(f"Login failed for {login_data.email}: {e.detail}")
raise
except Exception as e:
logger.error(f"Login error: {e}")
metrics.increment_counter("auth_login_failure_total")
logger.error(f"Login error for {login_data.email}: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Login failed"
@@ -84,7 +100,15 @@ async def verify_token(
)
token = auth_header.split(" ")[1]
return await AuthService.verify_token(token, db)
token_data = await AuthService.verify_token(token)
return {
"valid": True,
"user_id": token_data.get("user_id"),
"email": token_data.get("email"),
"role": token_data.get("role"),
"tenant_id": token_data.get("tenant_id")
}
except HTTPException:
raise
except Exception as e:
@@ -96,29 +120,27 @@ async def verify_token(
@router.post("/logout")
async def logout(
refresh_data: RefreshTokenRequest,
request: Request,
db: AsyncSession = Depends(get_db)
):
"""User logout"""
"""Logout user"""
try:
# Get user from token
auth_header = request.headers.get("Authorization")
if not auth_header or not auth_header.startswith("Bearer "):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authorization header required"
)
if auth_header and auth_header.startswith("Bearer "):
token = auth_header.split(" ")[1]
token_data = await AuthService.verify_token(token)
user_id = token_data.get("user_id")
if user_id:
success = await AuthService.logout_user(user_id, refresh_data.refresh_token, db)
return {"success": success}
token = auth_header.split(" ")[1]
user_data = await AuthService.verify_token(token, db)
await AuthService.logout_user(user_data["user_id"], db)
return {"message": "Logged out successfully"}
except HTTPException:
raise
return {"success": False, "message": "Invalid token"}
except Exception as e:
logger.error(f"Logout error: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Logout failed"
)
)