feat: simplify authentication logic and add logging for default user creation failures

This commit is contained in:
Daulet Amirkhanov 2025-09-03 14:12:37 +01:00
parent cd285d2f56
commit 21e48093ce

View file

@ -4,6 +4,10 @@ from fastapi import Depends, HTTPException
from ..models import User
from ..get_fastapi_users import get_fastapi_users
from .get_default_user import get_default_user
from cognee.shared.logging_utils import get_logger
logger = get_logger("get_authenticated_user")
# Check environment variable to determine authentication requirement
REQUIRE_AUTHENTICATION = (
@ -13,16 +17,7 @@ REQUIRE_AUTHENTICATION = (
fastapi_users = get_fastapi_users()
if REQUIRE_AUTHENTICATION:
# When REQUIRE_AUTHENTICATION=true, enforce authentication (original behavior)
_auth_dependency = fastapi_users.current_user(active=True)
else:
# When REQUIRE_AUTHENTICATION=false (default), make authentication optional
_auth_dependency = fastapi_users.current_user(
optional=True, # Returns None instead of raising HTTPException(401)
active=True, # Still require users to be active when authenticated
)
_auth_dependency = fastapi_users.current_user(active=True, optional=not REQUIRE_AUTHENTICATION)
async def get_authenticated_user(
user: Optional[User] = Depends(_auth_dependency),
@ -40,6 +35,7 @@ async def get_authenticated_user(
user = await get_default_user()
except Exception as e:
# Convert any get_default_user failure into a proper HTTP 500 error
logger.error(f"Failed to create default user: {str(e)}")
raise HTTPException(status_code=500, detail=f"Failed to create default user: {str(e)}")
return user