REFACTOR API gateway fix 7

This commit is contained in:
Urtzi Alfaro
2025-07-26 22:03:55 +02:00
parent de3bd5e541
commit 1291d05183
4 changed files with 271 additions and 119 deletions

View File

@@ -20,6 +20,91 @@ logger = structlog.get_logger()
router = APIRouter()
security = HTTPBearer()
@router.post("/register", response_model=TokenResponse)
@track_execution_time("registration_duration_seconds", "auth-service")
async def register(
user_data: UserRegistration,
request: Request,
db: AsyncSession = Depends(get_db)
):
"""Register new user with enhanced debugging"""
metrics = get_metrics_collector(request)
# ✅ DEBUG: Log incoming registration data (without password)
logger.info(f"Registration attempt for email: {user_data.email}")
logger.debug(f"Registration data - email: {user_data.email}, full_name: {user_data.full_name}")
try:
# ✅ DEBUG: Validate input data
if not user_data.email or not user_data.email.strip():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email is required"
)
if not user_data.password or len(user_data.password) < 8:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Password must be at least 8 characters long"
)
if not user_data.full_name or not user_data.full_name.strip():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Full name is required"
)
logger.debug(f"Input validation passed for {user_data.email}")
# ✅ DEBUG: Call auth service with enhanced error tracking
result = await AuthService.register_user_with_tokens(
email=user_data.email.strip().lower(), # Normalize email
password=user_data.password,
full_name=user_data.full_name.strip(),
db=db
)
logger.info(f"Registration successful for {user_data.email}")
# Record successful registration
if metrics:
metrics.increment_counter("registration_total", labels={"status": "success"})
# ✅ DEBUG: Validate response before returning
if not result.get("access_token"):
logger.error(f"Registration succeeded but no access_token in result for {user_data.email}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Registration completed but token generation failed"
)
logger.debug(f"Returning token response for {user_data.email}")
return TokenResponse(**result)
except HTTPException as e:
# Record failed registration with specific error
if metrics:
error_type = "validation_error" if e.status_code == 400 else "conflict" if e.status_code == 409 else "failed"
metrics.increment_counter("registration_total", labels={"status": error_type})
logger.warning(f"Registration failed for {user_data.email}: {e.detail}")
raise
except Exception as e:
# Record registration system error
if metrics:
metrics.increment_counter("registration_total", labels={"status": "error"})
logger.error(f"Registration system error for {user_data.email}: {str(e)}", exc_info=True)
# ✅ DEBUG: Provide more specific error information in development
error_detail = f"Registration failed: {str(e)}" if logger.level == "DEBUG" else "Registration failed"
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=error_detail
)
@router.post("/login", response_model=TokenResponse)
@track_execution_time("login_duration_seconds", "auth-service")
async def login(
@@ -27,28 +112,31 @@ async def login(
request: Request,
db: AsyncSession = Depends(get_db)
):
"""
Login user and return tokens
FIXED: Proper error handling and login attempt tracking
"""
"""Login user with enhanced debugging"""
metrics = get_metrics_collector(request)
logger.info(f"Login attempt for email: {login_data.email}")
try:
# Check if account is locked due to too many failed attempts
can_attempt = await SecurityManager.check_login_attempts(login_data.email)
if not can_attempt:
if metrics:
metrics.increment_counter("login_failure_total", labels={"reason": "rate_limited"})
# ✅ DEBUG: Validate login data
if not login_data.email or not login_data.email.strip():
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail=f"Too many login attempts. Please try again in {SecurityManager.settings.LOCKOUT_DURATION_MINUTES} minutes."
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email is required"
)
if not login_data.password:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Password is required"
)
# Attempt login through AuthService
result = await AuthService.login(login_data.email, login_data.password, db)
# Clear login attempts on successful login
await SecurityManager.clear_login_attempts(login_data.email)
result = await AuthService.login(
email=login_data.email.strip().lower(), # Normalize email
password=login_data.password,
db=db
)
# Record successful login
if metrics:
@@ -58,67 +146,25 @@ async def login(
return TokenResponse(**result)
except HTTPException as e:
# Don't increment attempts for rate limiting errors (already handled above)
if e.status_code != status.HTTP_429_TOO_MANY_REQUESTS:
# Increment login attempts on authentication failure
await SecurityManager.increment_login_attempts(login_data.email)
# Record failed login
# Record failed login with specific reason
if metrics:
reason = "rate_limited" if e.status_code == 429 else "auth_failed"
reason = "validation_error" if e.status_code == 400 else "auth_failed"
metrics.increment_counter("login_failure_total", labels={"reason": reason})
logger.warning(f"Login failed for {login_data.email}: {e.detail}")
raise
except Exception as e:
# Increment login attempts on any other error
await SecurityManager.increment_login_attempts(login_data.email)
# Record login error
# Record login system error
if metrics:
metrics.increment_counter("login_failure_total", labels={"reason": "error"})
logger.error(f"Login error for {login_data.email}: {e}")
logger.error(f"Login system error for {login_data.email}: {str(e)}", exc_info=True)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Login failed"
)
@router.post("/register", response_model=TokenResponse)
@track_execution_time("registration_duration_seconds", "auth-service")
async def register(
user_data: UserRegistration,
request: Request,
db: AsyncSession = Depends(get_db)
):
"""Register new user"""
metrics = get_metrics_collector(request)
try:
result = await AuthService.register_user_with_tokens(user_data.email, user_data.password, user_data.full_name, db)
# Record successful registration
if metrics:
metrics.increment_counter("registration_total", labels={"status": "success"})
logger.info(f"User registered successfully: {user_data.email}")
return TokenResponse(**result)
except HTTPException as e:
if metrics:
metrics.increment_counter("registration_total", labels={"status": "failed"})
logger.warning(f"Registration failed for {user_data.email}: {e.detail}")
raise
except Exception as e:
if metrics:
metrics.increment_counter("registration_total", labels={"status": "error"})
logger.error(f"Registration error for {user_data.email}: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Registration failed"
)
@router.post("/refresh", response_model=TokenResponse)
@track_execution_time("token_refresh_duration_seconds", "auth-service")
async def refresh_token(