Add new frontend - fix 8
This commit is contained in:
@@ -1,9 +1,7 @@
|
||||
# ================================================================
|
||||
# services/auth/app/api/auth.py - COMPLETE FIXED VERSION
|
||||
# ================================================================
|
||||
# services/auth/app/api/auth.py - UPDATED TO RETURN TOKENS FROM REGISTRATION
|
||||
"""
|
||||
Authentication API routes - Complete implementation with proper error handling
|
||||
Uses the SecurityManager and AuthService from the provided files
|
||||
Authentication API routes - Updated to return tokens directly from registration
|
||||
Following industry best practices with unified token response format
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Request
|
||||
@@ -34,14 +32,14 @@ def get_metrics_collector(request: Request):
|
||||
# AUTHENTICATION ENDPOINTS
|
||||
# ================================================================
|
||||
|
||||
@router.post("/register", response_model=UserResponse)
|
||||
@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 a new user"""
|
||||
"""Register a new user and return tokens directly"""
|
||||
metrics = get_metrics_collector(request)
|
||||
|
||||
try:
|
||||
@@ -52,8 +50,8 @@ async def register(
|
||||
detail="Password does not meet security requirements"
|
||||
)
|
||||
|
||||
# Create user using AuthService
|
||||
user = await AuthService.create_user(
|
||||
# Create user and generate tokens in one operation
|
||||
result = await AuthService.register_user_with_tokens(
|
||||
email=user_data.email,
|
||||
password=user_data.password,
|
||||
full_name=user_data.full_name,
|
||||
@@ -64,26 +62,16 @@ async def register(
|
||||
if metrics:
|
||||
metrics.increment_counter("registration_total", labels={"status": "success"})
|
||||
|
||||
logger.info(f"User registration successful: {user_data.email}")
|
||||
logger.info(f"User registration with tokens successful: {user_data.email}")
|
||||
|
||||
return UserResponse(
|
||||
id=str(user.id),
|
||||
email=user.email,
|
||||
full_name=user.full_name,
|
||||
is_active=user.is_active,
|
||||
is_verified=user.is_verified,
|
||||
created_at=user.created_at
|
||||
)
|
||||
return TokenResponse(**result)
|
||||
|
||||
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}")
|
||||
raise
|
||||
|
||||
except Exception as e:
|
||||
# Record error
|
||||
if metrics:
|
||||
metrics.increment_counter("registration_total", labels={"status": "error"})
|
||||
logger.error(f"Registration error for {user_data.email}: {e}")
|
||||
@@ -99,14 +87,13 @@ async def login(
|
||||
request: Request,
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""User login"""
|
||||
"""Login user and return tokens"""
|
||||
metrics = get_metrics_collector(request)
|
||||
|
||||
try:
|
||||
# Check login attempts TODO
|
||||
# if not await SecurityManager.check_login_attempts(login_data.email):
|
||||
# if metrics:
|
||||
# metrics.increment_counter("login_failure_total", labels={"reason": "rate_limited"})
|
||||
# Check login attempts (rate limiting)
|
||||
#attempts = await SecurityManager.get_login_attempts(login_data.email)
|
||||
#if attempts >= 5:
|
||||
# raise HTTPException(
|
||||
# status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
# detail="Too many login attempts. Please try again later."
|
||||
@@ -166,14 +153,12 @@ async def refresh_token(
|
||||
return TokenResponse(**result)
|
||||
|
||||
except HTTPException as e:
|
||||
# Record failed refresh
|
||||
if metrics:
|
||||
metrics.increment_counter("token_refresh_failure_total")
|
||||
logger.warning(f"Token refresh failed: {e.detail}")
|
||||
raise
|
||||
|
||||
except Exception as e:
|
||||
# Record refresh error
|
||||
if metrics:
|
||||
metrics.increment_counter("token_refresh_failure_total")
|
||||
logger.error(f"Token refresh error: {e}")
|
||||
@@ -183,46 +168,40 @@ async def refresh_token(
|
||||
)
|
||||
|
||||
@router.post("/verify", response_model=TokenVerification)
|
||||
@track_execution_time("token_verification_duration_seconds", "auth-service")
|
||||
async def verify_token(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
request: Request = None
|
||||
):
|
||||
"""Verify JWT token"""
|
||||
"""Verify access token"""
|
||||
metrics = get_metrics_collector(request) if request else None
|
||||
|
||||
if not credentials:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Authorization header required"
|
||||
)
|
||||
|
||||
try:
|
||||
if not credentials:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="No token provided"
|
||||
)
|
||||
result = await AuthService.verify_user_token(credentials.credentials)
|
||||
|
||||
# Verify token using AuthService
|
||||
payload = await AuthService.verify_user_token(credentials.credentials)
|
||||
|
||||
# Record successful verification
|
||||
if metrics:
|
||||
metrics.increment_counter("token_verification_success_total")
|
||||
metrics.increment_counter("token_verify_success_total")
|
||||
|
||||
return TokenVerification(
|
||||
valid=True,
|
||||
user_id=payload.get("user_id"),
|
||||
email=payload.get("email"),
|
||||
full_name=payload.get("full_name"),
|
||||
tenants=payload.get("tenants", [])
|
||||
user_id=result.get("user_id"),
|
||||
email=result.get("email"),
|
||||
exp=result.get("exp")
|
||||
)
|
||||
|
||||
except HTTPException as e:
|
||||
# Record failed verification
|
||||
if metrics:
|
||||
metrics.increment_counter("token_verification_failure_total")
|
||||
logger.warning(f"Token verification failed: {e.detail}")
|
||||
metrics.increment_counter("token_verify_failure_total")
|
||||
raise
|
||||
|
||||
except Exception as e:
|
||||
# Record verification error
|
||||
if metrics:
|
||||
metrics.increment_counter("token_verification_failure_total")
|
||||
metrics.increment_counter("token_verify_failure_total")
|
||||
logger.error(f"Token verification error: {e}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
@@ -230,34 +209,25 @@ async def verify_token(
|
||||
)
|
||||
|
||||
@router.post("/logout")
|
||||
@track_execution_time("logout_duration_seconds", "auth-service")
|
||||
async def logout(
|
||||
refresh_data: RefreshTokenRequest,
|
||||
request: Request,
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""User logout"""
|
||||
"""Logout user by revoking refresh token"""
|
||||
metrics = get_metrics_collector(request)
|
||||
|
||||
try:
|
||||
success = await AuthService.logout(refresh_data.refresh_token, db)
|
||||
|
||||
# Record logout
|
||||
if metrics:
|
||||
metrics.increment_counter("logout_total", labels={"status": "success" if success else "failed"})
|
||||
status_label = "success" if success else "failed"
|
||||
metrics.increment_counter("logout_total", labels={"status": status_label})
|
||||
|
||||
if success:
|
||||
logger.info("User logout successful")
|
||||
return {"message": "Logout successful"}
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Logout failed"
|
||||
)
|
||||
return {"message": "Logout successful" if success else "Logout failed"}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
# Record logout error
|
||||
if metrics:
|
||||
metrics.increment_counter("logout_total", labels={"status": "error"})
|
||||
logger.error(f"Logout error: {e}")
|
||||
|
||||
Reference in New Issue
Block a user