REFACTOR API gateway fix 1

This commit is contained in:
Urtzi Alfaro
2025-07-26 19:15:18 +02:00
parent e4885db828
commit b0629c5971
3 changed files with 55 additions and 16 deletions

View File

@@ -56,7 +56,7 @@ app.add_middleware(AuthMiddleware)
# Include routers # Include routers
app.include_router(auth.router, prefix="/api/v1/auth", tags=["authentication"]) app.include_router(auth.router, prefix="/api/v1/auth", tags=["authentication"])
app.include_router(user.router, prefix="/api/v1/user", tags=["user"]) app.include_router(user.router, prefix="/api/v1/users", tags=["users"])
app.include_router(tenant.router, prefix="/api/v1/tenants", tags=["tenants"]) app.include_router(tenant.router, prefix="/api/v1/tenants", tags=["tenants"])
app.include_router(notification.router, prefix="/api/v1/notifications", tags=["notifications"]) app.include_router(notification.router, prefix="/api/v1/notifications", tags=["notifications"])
app.include_router(nominatim.router, prefix="/api/v1/nominatim", tags=["location"]) app.include_router(nominatim.router, prefix="/api/v1/nominatim", tags=["location"])

View File

@@ -59,7 +59,7 @@ class UserProxy:
try: try:
# Get auth service URL (with service discovery if available) # Get auth service URL (with service discovery if available)
auth_url = await self._get_auth_service_url() auth_url = await self._get_auth_service_url()
target_url = f"{auth_url}/api/v1/user/{path}" target_url = f"{auth_url}/api/v1/users/{path}"
# Prepare headers (remove hop-by-hop headers) # Prepare headers (remove hop-by-hop headers)
headers = self._prepare_headers(dict(request.headers)) headers = self._prepare_headers(dict(request.headers))
@@ -177,12 +177,12 @@ user_proxy = UserProxy()
@router.get("/me") @router.get("/me")
async def get_current_user(request: Request): async def get_current_user(request: Request):
"""Proxy get current user to auth service""" """Proxy get current user to auth service"""
return await user_proxy.forward_request("GET", "/me", request) return await user_proxy.forward_request("GET", "me", request)
@router.put("/me") @router.put("/me")
async def update_current_user(request: Request): async def update_current_user(request: Request):
"""Proxy update current user to auth service""" """Proxy update current user to auth service"""
return await user_proxy.forward_request("PUT", "/me", request) return await user_proxy.forward_request("PUT", "me", request)
# ================================================================ # ================================================================
# CATCH-ALL ROUTE for any other user endpoints # CATCH-ALL ROUTE for any other user endpoints

View File

@@ -13,6 +13,8 @@ from app.schemas.users import UserUpdate
from app.services.user_service import UserService from app.services.user_service import UserService
from app.models.users import User from app.models.users import User
from sqlalchemy.ext.asyncio import AsyncSession
# Import unified authentication from shared library # Import unified authentication from shared library
from shared.auth.decorators import ( from shared.auth.decorators import (
get_current_user_dep, get_current_user_dep,
@@ -30,18 +32,55 @@ async def get_current_user_info(
): ):
"""Get current user information""" """Get current user information"""
try: try:
return UserResponse( # Handle both User object (direct auth) and dict (from gateway headers)
id=str(current_user.id), if isinstance(current_user, dict):
email=current_user.email, # Coming from gateway headers - need to fetch user from DB
full_name=current_user.full_name, user_id = current_user.get("user_id")
is_active=current_user.is_active, if not user_id:
is_verified=current_user.is_verified, raise HTTPException(
phone=current_user.phone, status_code=status.HTTP_401_UNAUTHORIZED,
language=current_user.language, detail="Invalid user context"
timezone=current_user.timezone, )
created_at=current_user.created_at,
last_login=current_user.last_login # Fetch full user from database
) from sqlalchemy import select
from app.models.users import User
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
return UserResponse(
id=str(user.id),
email=user.email,
full_name=user.full_name,
is_active=user.is_active,
is_verified=user.is_verified,
phone=user.phone,
language=user.language,
timezone=user.timezone,
created_at=user.created_at,
last_login=user.last_login
)
else:
# Direct User object (when called directly)
return UserResponse(
id=str(current_user.id),
email=current_user.email,
full_name=current_user.full_name,
is_active=current_user.is_active,
is_verified=current_user.is_verified,
phone=current_user.phone,
language=current_user.language,
timezone=current_user.timezone,
created_at=current_user.created_at,
last_login=current_user.last_login
)
except Exception as e: except Exception as e:
logger.error(f"Get current user error: {e}") logger.error(f"Get current user error: {e}")
raise HTTPException( raise HTTPException(