keep get_authenticated_user and move conditional auth

This commit is contained in:
Daulet Amirkhanov 2025-09-01 13:06:38 +01:00
parent 73ff973565
commit 2a3ec5f762
13 changed files with 82 additions and 82 deletions

View file

@ -9,7 +9,7 @@ from fastapi import Form, File, UploadFile, Depends
from typing import List, Optional, Union, Literal from typing import List, Optional, Union, Literal
from cognee.modules.users.models import User from cognee.modules.users.models import User
from cognee.modules.users.methods import get_conditional_authenticated_user from cognee.modules.users.methods import get_authenticated_user
from cognee.shared.utils import send_telemetry from cognee.shared.utils import send_telemetry
from cognee.modules.pipelines.models import PipelineRunErrored from cognee.modules.pipelines.models import PipelineRunErrored
from cognee.shared.logging_utils import get_logger from cognee.shared.logging_utils import get_logger
@ -25,7 +25,7 @@ def get_add_router() -> APIRouter:
data: List[UploadFile] = File(default=None), data: List[UploadFile] = File(default=None),
datasetName: Optional[str] = Form(default=None), datasetName: Optional[str] = Form(default=None),
datasetId: Union[UUID, Literal[""], None] = Form(default=None, examples=[""]), datasetId: Union[UUID, Literal[""], None] = Form(default=None, examples=[""]),
user: User = Depends(get_conditional_authenticated_user), user: User = Depends(get_authenticated_user),
): ):
""" """
Add data to a dataset for processing and knowledge graph construction. Add data to a dataset for processing and knowledge graph construction.

View file

@ -10,7 +10,7 @@ from starlette.status import WS_1000_NORMAL_CLOSURE, WS_1008_POLICY_VIOLATION
from cognee.api.DTO import InDTO from cognee.api.DTO import InDTO
from cognee.modules.pipelines.methods import get_pipeline_run from cognee.modules.pipelines.methods import get_pipeline_run
from cognee.modules.users.models import User from cognee.modules.users.models import User
from cognee.modules.users.methods import get_conditional_authenticated_user from cognee.modules.users.methods import get_authenticated_user
from cognee.modules.users.get_user_db import get_user_db_context from cognee.modules.users.get_user_db import get_user_db_context
from cognee.modules.graph.methods import get_formatted_graph_data from cognee.modules.graph.methods import get_formatted_graph_data
from cognee.modules.users.get_user_manager import get_user_manager_context from cognee.modules.users.get_user_manager import get_user_manager_context
@ -47,7 +47,7 @@ def get_cognify_router() -> APIRouter:
@router.post("", response_model=dict) @router.post("", response_model=dict)
async def cognify( async def cognify(
payload: CognifyPayloadDTO, user: User = Depends(get_conditional_authenticated_user) payload: CognifyPayloadDTO, user: User = Depends(get_authenticated_user)
): ):
""" """
Transform datasets into structured knowledge graphs through cognitive processing. Transform datasets into structured knowledge graphs through cognitive processing.

View file

@ -15,7 +15,7 @@ from cognee.modules.data.methods import create_dataset, get_datasets_by_name
from cognee.shared.logging_utils import get_logger from cognee.shared.logging_utils import get_logger
from cognee.api.v1.exceptions import DataNotFoundError, DatasetNotFoundError from cognee.api.v1.exceptions import DataNotFoundError, DatasetNotFoundError
from cognee.modules.users.models import User from cognee.modules.users.models import User
from cognee.modules.users.methods import get_conditional_authenticated_user from cognee.modules.users.methods import get_authenticated_user
from cognee.modules.users.permissions.methods import ( from cognee.modules.users.permissions.methods import (
get_all_user_permission_datasets, get_all_user_permission_datasets,
give_permission_on_dataset, give_permission_on_dataset,
@ -74,7 +74,7 @@ def get_datasets_router() -> APIRouter:
router = APIRouter() router = APIRouter()
@router.get("", response_model=list[DatasetDTO]) @router.get("", response_model=list[DatasetDTO])
async def get_datasets(user: User = Depends(get_conditional_authenticated_user)): async def get_datasets(user: User = Depends(get_authenticated_user)):
""" """
Get all datasets accessible to the authenticated user. Get all datasets accessible to the authenticated user.
@ -115,7 +115,7 @@ def get_datasets_router() -> APIRouter:
@router.post("", response_model=DatasetDTO) @router.post("", response_model=DatasetDTO)
async def create_new_dataset( async def create_new_dataset(
dataset_data: DatasetCreationPayload, dataset_data: DatasetCreationPayload,
user: User = Depends(get_conditional_authenticated_user), user: User = Depends(get_authenticated_user),
): ):
""" """
Create a new dataset or return existing dataset with the same name. Create a new dataset or return existing dataset with the same name.
@ -177,7 +177,7 @@ def get_datasets_router() -> APIRouter:
"/{dataset_id}", response_model=None, responses={404: {"model": ErrorResponseDTO}} "/{dataset_id}", response_model=None, responses={404: {"model": ErrorResponseDTO}}
) )
async def delete_dataset( async def delete_dataset(
dataset_id: UUID, user: User = Depends(get_conditional_authenticated_user) dataset_id: UUID, user: User = Depends(get_authenticated_user)
): ):
""" """
Delete a dataset by its ID. Delete a dataset by its ID.
@ -219,7 +219,7 @@ def get_datasets_router() -> APIRouter:
responses={404: {"model": ErrorResponseDTO}}, responses={404: {"model": ErrorResponseDTO}},
) )
async def delete_data( async def delete_data(
dataset_id: UUID, data_id: UUID, user: User = Depends(get_conditional_authenticated_user) dataset_id: UUID, data_id: UUID, user: User = Depends(get_authenticated_user)
): ):
""" """
Delete a specific data item from a dataset. Delete a specific data item from a dataset.
@ -267,7 +267,7 @@ def get_datasets_router() -> APIRouter:
@router.get("/{dataset_id}/graph", response_model=GraphDTO) @router.get("/{dataset_id}/graph", response_model=GraphDTO)
async def get_dataset_graph( async def get_dataset_graph(
dataset_id: UUID, user: User = Depends(get_conditional_authenticated_user) dataset_id: UUID, user: User = Depends(get_authenticated_user)
): ):
""" """
Get the knowledge graph visualization for a dataset. Get the knowledge graph visualization for a dataset.
@ -299,7 +299,7 @@ def get_datasets_router() -> APIRouter:
responses={404: {"model": ErrorResponseDTO}}, responses={404: {"model": ErrorResponseDTO}},
) )
async def get_dataset_data( async def get_dataset_data(
dataset_id: UUID, user: User = Depends(get_conditional_authenticated_user) dataset_id: UUID, user: User = Depends(get_authenticated_user)
): ):
""" """
Get all data items in a dataset. Get all data items in a dataset.
@ -355,7 +355,7 @@ def get_datasets_router() -> APIRouter:
@router.get("/status", response_model=dict[str, PipelineRunStatus]) @router.get("/status", response_model=dict[str, PipelineRunStatus])
async def get_dataset_status( async def get_dataset_status(
datasets: Annotated[List[UUID], Query(alias="dataset")] = [], datasets: Annotated[List[UUID], Query(alias="dataset")] = [],
user: User = Depends(get_conditional_authenticated_user), user: User = Depends(get_authenticated_user),
): ):
""" """
Get the processing status of datasets. Get the processing status of datasets.
@ -402,7 +402,7 @@ def get_datasets_router() -> APIRouter:
@router.get("/{dataset_id}/data/{data_id}/raw", response_class=FileResponse) @router.get("/{dataset_id}/data/{data_id}/raw", response_class=FileResponse)
async def get_raw_data( async def get_raw_data(
dataset_id: UUID, data_id: UUID, user: User = Depends(get_conditional_authenticated_user) dataset_id: UUID, data_id: UUID, user: User = Depends(get_authenticated_user)
): ):
""" """
Download the raw data file for a specific data item. Download the raw data file for a specific data item.

View file

@ -4,7 +4,7 @@ from fastapi import APIRouter
from uuid import UUID from uuid import UUID
from cognee.shared.logging_utils import get_logger from cognee.shared.logging_utils import get_logger
from cognee.modules.users.models import User from cognee.modules.users.models import User
from cognee.modules.users.methods import get_conditional_authenticated_user from cognee.modules.users.methods import get_authenticated_user
from cognee.shared.utils import send_telemetry from cognee.shared.utils import send_telemetry
logger = get_logger() logger = get_logger()
@ -18,7 +18,7 @@ def get_delete_router() -> APIRouter:
data_id: UUID, data_id: UUID,
dataset_id: UUID, dataset_id: UUID,
mode: str = "soft", mode: str = "soft",
user: User = Depends(get_conditional_authenticated_user), user: User = Depends(get_authenticated_user),
): ):
"""Delete data by its ID from the specified dataset. """Delete data by its ID from the specified dataset.

View file

@ -5,7 +5,7 @@ from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from cognee.modules.users.models import User from cognee.modules.users.models import User
from cognee.modules.users.methods import get_conditional_authenticated_user from cognee.modules.users.methods import get_authenticated_user
from cognee.shared.utils import send_telemetry from cognee.shared.utils import send_telemetry
@ -17,7 +17,7 @@ def get_permissions_router() -> APIRouter:
permission_name: str, permission_name: str,
dataset_ids: List[UUID], dataset_ids: List[UUID],
principal_id: UUID, principal_id: UUID,
user: User = Depends(get_conditional_authenticated_user), user: User = Depends(get_authenticated_user),
): ):
""" """
Grant permission on datasets to a principal (user or role). Grant permission on datasets to a principal (user or role).
@ -65,7 +65,7 @@ def get_permissions_router() -> APIRouter:
) )
@permissions_router.post("/roles") @permissions_router.post("/roles")
async def create_role(role_name: str, user: User = Depends(get_conditional_authenticated_user)): async def create_role(role_name: str, user: User = Depends(get_authenticated_user)):
""" """
Create a new role. Create a new role.
@ -100,7 +100,7 @@ def get_permissions_router() -> APIRouter:
@permissions_router.post("/users/{user_id}/roles") @permissions_router.post("/users/{user_id}/roles")
async def add_user_to_role( async def add_user_to_role(
user_id: UUID, role_id: UUID, user: User = Depends(get_conditional_authenticated_user) user_id: UUID, role_id: UUID, user: User = Depends(get_authenticated_user)
): ):
""" """
Add a user to a role. Add a user to a role.
@ -142,7 +142,7 @@ def get_permissions_router() -> APIRouter:
@permissions_router.post("/users/{user_id}/tenants") @permissions_router.post("/users/{user_id}/tenants")
async def add_user_to_tenant( async def add_user_to_tenant(
user_id: UUID, tenant_id: UUID, user: User = Depends(get_conditional_authenticated_user) user_id: UUID, tenant_id: UUID, user: User = Depends(get_authenticated_user)
): ):
""" """
Add a user to a tenant. Add a user to a tenant.
@ -184,7 +184,7 @@ def get_permissions_router() -> APIRouter:
@permissions_router.post("/tenants") @permissions_router.post("/tenants")
async def create_tenant( async def create_tenant(
tenant_name: str, user: User = Depends(get_conditional_authenticated_user) tenant_name: str, user: User = Depends(get_authenticated_user)
): ):
""" """
Create a new tenant. Create a new tenant.

View file

@ -21,7 +21,7 @@ from cognee.infrastructure.llm.config import (
get_llm_config, get_llm_config,
) )
from cognee.modules.users.models import User from cognee.modules.users.models import User
from cognee.modules.users.methods import get_conditional_authenticated_user from cognee.modules.users.methods import get_authenticated_user
def get_responses_router() -> APIRouter: def get_responses_router() -> APIRouter:
@ -73,7 +73,7 @@ def get_responses_router() -> APIRouter:
@router.post("/", response_model=ResponseBody) @router.post("/", response_model=ResponseBody)
async def create_response( async def create_response(
request: ResponseRequest, request: ResponseRequest,
user: User = Depends(get_conditional_authenticated_user), user: User = Depends(get_authenticated_user),
) -> ResponseBody: ) -> ResponseBody:
""" """
OpenAI-compatible responses endpoint with function calling support. OpenAI-compatible responses endpoint with function calling support.

View file

@ -9,7 +9,7 @@ from cognee.api.DTO import InDTO, OutDTO
from cognee.modules.users.exceptions.exceptions import PermissionDeniedError from cognee.modules.users.exceptions.exceptions import PermissionDeniedError
from cognee.modules.users.models import User from cognee.modules.users.models import User
from cognee.modules.search.operations import get_history from cognee.modules.search.operations import get_history
from cognee.modules.users.methods import get_conditional_authenticated_user from cognee.modules.users.methods import get_authenticated_user
from cognee.shared.utils import send_telemetry from cognee.shared.utils import send_telemetry
@ -33,7 +33,7 @@ def get_search_router() -> APIRouter:
created_at: datetime created_at: datetime
@router.get("", response_model=list[SearchHistoryItem]) @router.get("", response_model=list[SearchHistoryItem])
async def get_search_history(user: User = Depends(get_conditional_authenticated_user)): async def get_search_history(user: User = Depends(get_authenticated_user)):
""" """
Get search history for the authenticated user. Get search history for the authenticated user.
@ -67,7 +67,7 @@ def get_search_router() -> APIRouter:
@router.post("", response_model=list) @router.post("", response_model=list)
async def search( async def search(
payload: SearchPayloadDTO, user: User = Depends(get_conditional_authenticated_user) payload: SearchPayloadDTO, user: User = Depends(get_authenticated_user)
): ):
""" """
Search for nodes in the graph database. Search for nodes in the graph database.

View file

@ -1,7 +1,7 @@
from fastapi import APIRouter from fastapi import APIRouter
from cognee.api.DTO import InDTO, OutDTO from cognee.api.DTO import InDTO, OutDTO
from typing import Union, Optional, Literal from typing import Union, Optional, Literal
from cognee.modules.users.methods import get_conditional_authenticated_user from cognee.modules.users.methods import get_authenticated_user
from fastapi import Depends from fastapi import Depends
from cognee.modules.users.models import User from cognee.modules.users.models import User
from cognee.modules.settings.get_settings import LLMConfig, VectorDBConfig from cognee.modules.settings.get_settings import LLMConfig, VectorDBConfig
@ -45,7 +45,7 @@ def get_settings_router() -> APIRouter:
router = APIRouter() router = APIRouter()
@router.get("", response_model=SettingsDTO) @router.get("", response_model=SettingsDTO)
async def get_settings(user: User = Depends(get_conditional_authenticated_user)): async def get_settings(user: User = Depends(get_authenticated_user)):
""" """
Get the current system settings. Get the current system settings.
@ -67,7 +67,7 @@ def get_settings_router() -> APIRouter:
@router.post("", response_model=None) @router.post("", response_model=None)
async def save_settings( async def save_settings(
new_settings: SettingsPayloadDTO, user: User = Depends(get_conditional_authenticated_user) new_settings: SettingsPayloadDTO, user: User = Depends(get_authenticated_user)
): ):
""" """
Save or update system settings. Save or update system settings.

View file

@ -2,7 +2,7 @@ from fastapi import APIRouter, Depends
from fastapi.responses import HTMLResponse, JSONResponse from fastapi.responses import HTMLResponse, JSONResponse
from uuid import UUID from uuid import UUID
from cognee.shared.logging_utils import get_logger from cognee.shared.logging_utils import get_logger
from cognee.modules.users.methods import get_conditional_authenticated_user from cognee.modules.users.methods import get_authenticated_user
from cognee.modules.data.methods import get_authorized_existing_datasets from cognee.modules.data.methods import get_authorized_existing_datasets
from cognee.modules.users.models import User from cognee.modules.users.models import User
@ -16,7 +16,7 @@ def get_visualize_router() -> APIRouter:
router = APIRouter() router = APIRouter()
@router.get("", response_model=None) @router.get("", response_model=None)
async def visualize(dataset_id: UUID, user: User = Depends(get_conditional_authenticated_user)): async def visualize(dataset_id: UUID, user: User = Depends(get_authenticated_user)):
""" """
Generate an HTML visualization of the dataset's knowledge graph. Generate an HTML visualization of the dataset's knowledge graph.

View file

@ -4,7 +4,7 @@ from .delete_user import delete_user
from .get_default_user import get_default_user from .get_default_user import get_default_user
from .get_user_by_email import get_user_by_email from .get_user_by_email import get_user_by_email
from .create_default_user import create_default_user from .create_default_user import create_default_user
from .get_conditional_authenticated_user import ( from .get_authenticated_user import (
get_conditional_authenticated_user, get_authenticated_user,
REQUIRE_AUTHENTICATION, REQUIRE_AUTHENTICATION,
) )

View file

@ -24,7 +24,7 @@ else:
) )
async def get_conditional_authenticated_user( async def get_authenticated_user(
user: Optional[User] = Depends(_auth_dependency), user: Optional[User] = Depends(_auth_dependency),
) -> User: ) -> User:
""" """

View file

@ -69,7 +69,7 @@ class TestConditionalAuthenticationEndpoints:
@patch("cognee.api.v1.add.add") @patch("cognee.api.v1.add.add")
@patch("cognee.modules.users.methods.get_default_user.get_default_user", new_callable=AsyncMock) @patch("cognee.modules.users.methods.get_default_user.get_default_user", new_callable=AsyncMock)
@patch( @patch(
"cognee.modules.users.methods.get_conditional_authenticated_user.REQUIRE_AUTHENTICATION", "cognee.modules.users.methods.get_authenticated_user.REQUIRE_AUTHENTICATION",
False, False,
) )
def test_add_endpoint_with_conditional_auth( def test_add_endpoint_with_conditional_auth(
@ -95,7 +95,7 @@ class TestConditionalAuthenticationEndpoints:
@patch("cognee.modules.users.methods.get_default_user.get_default_user", new_callable=AsyncMock) @patch("cognee.modules.users.methods.get_default_user.get_default_user", new_callable=AsyncMock)
@patch( @patch(
"cognee.modules.users.methods.get_conditional_authenticated_user.REQUIRE_AUTHENTICATION", "cognee.modules.users.methods.get_authenticated_user.REQUIRE_AUTHENTICATION",
False, False,
) )
def test_conditional_authentication_works_with_current_environment( def test_conditional_authentication_works_with_current_environment(
@ -131,13 +131,13 @@ class TestConditionalAuthenticationEndpoints:
) )
# Simulate authenticated request by directly testing the conditional function # Simulate authenticated request by directly testing the conditional function
from cognee.modules.users.methods.get_conditional_authenticated_user import ( from cognee.modules.users.methods.get_authenticated_user import (
get_conditional_authenticated_user, get_authenticated_user,
) )
async def test_logic(): async def test_logic():
# When user is provided (authenticated), should not call get_default_user # When user is provided (authenticated), should not call get_default_user
result = await get_conditional_authenticated_user(user=mock_authenticated_user) result = await get_authenticated_user(user=mock_authenticated_user)
assert result == mock_authenticated_user assert result == mock_authenticated_user
mock_get_default.assert_not_called() mock_get_default.assert_not_called()
@ -248,7 +248,7 @@ class TestConditionalAuthenticationErrorHandling:
def test_current_environment_configuration(self): def test_current_environment_configuration(self):
"""Test that current environment configuration is working properly.""" """Test that current environment configuration is working properly."""
# This tests the actual module state without trying to change it # This tests the actual module state without trying to change it
from cognee.modules.users.methods.get_conditional_authenticated_user import ( from cognee.modules.users.methods.get_authenticated_user import (
REQUIRE_AUTHENTICATION, REQUIRE_AUTHENTICATION,
) )

View file

@ -20,17 +20,17 @@ class TestConditionalAuthentication:
mock_default_user = SimpleNamespace(id=uuid4(), email="default@example.com", is_active=True) mock_default_user = SimpleNamespace(id=uuid4(), email="default@example.com", is_active=True)
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}): with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
from cognee.modules.users.methods.get_conditional_authenticated_user import ( from cognee.modules.users.methods.get_authenticated_user import (
get_conditional_authenticated_user, get_authenticated_user,
) )
with patch( with patch(
"cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user" "cognee.modules.users.methods.get_authenticated_user.get_default_user"
) as mock_get_default: ) as mock_get_default:
mock_get_default.return_value = mock_default_user mock_get_default.return_value = mock_default_user
# Test with None user (no authentication) # Test with None user (no authentication)
result = await get_conditional_authenticated_user(user=None) result = await get_authenticated_user(user=None)
assert result == mock_default_user assert result == mock_default_user
mock_get_default.assert_called_once() mock_get_default.assert_called_once()
@ -47,15 +47,15 @@ class TestConditionalAuthentication:
) )
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}): with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
from cognee.modules.users.methods.get_conditional_authenticated_user import ( from cognee.modules.users.methods.get_authenticated_user import (
get_conditional_authenticated_user, get_authenticated_user,
) )
with patch( with patch(
"cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user" "cognee.modules.users.methods.get_authenticated_user.get_default_user"
) as mock_get_default: ) as mock_get_default:
# Test with authenticated user # Test with authenticated user
result = await get_conditional_authenticated_user(user=mock_authenticated_user) result = await get_authenticated_user(user=mock_authenticated_user)
assert result == mock_authenticated_user assert result == mock_authenticated_user
mock_get_default.assert_not_called() mock_get_default.assert_not_called()
@ -72,11 +72,11 @@ class TestConditionalAuthentication:
) )
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "true"}): with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "true"}):
from cognee.modules.users.methods.get_conditional_authenticated_user import ( from cognee.modules.users.methods.get_authenticated_user import (
get_conditional_authenticated_user, get_authenticated_user,
) )
result = await get_conditional_authenticated_user(user=mock_authenticated_user) result = await get_authenticated_user(user=mock_authenticated_user)
assert result == mock_authenticated_user assert result == mock_authenticated_user
@ -88,11 +88,11 @@ class TestConditionalAuthentication:
# Since REQUIRE_AUTHENTICATION is currently false (set at import time), # Since REQUIRE_AUTHENTICATION is currently false (set at import time),
# we expect it to return the default user, not None # we expect it to return the default user, not None
from cognee.modules.users.methods.get_conditional_authenticated_user import ( from cognee.modules.users.methods.get_authenticated_user import (
get_conditional_authenticated_user, get_authenticated_user,
) )
result = await get_conditional_authenticated_user(user=None) result = await get_authenticated_user(user=None)
# The current implementation will return default user because REQUIRE_AUTHENTICATION is false # The current implementation will return default user because REQUIRE_AUTHENTICATION is false
assert result is not None # Should get default user assert result is not None # Should get default user
@ -120,13 +120,13 @@ class TestConditionalAuthenticationIntegration:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_conditional_authentication_function_exists(self): async def test_conditional_authentication_function_exists(self):
"""Test that the conditional authentication function can be imported and used.""" """Test that the conditional authentication function can be imported and used."""
from cognee.modules.users.methods.get_conditional_authenticated_user import ( from cognee.modules.users.methods.get_authenticated_user import (
get_conditional_authenticated_user, get_authenticated_user,
REQUIRE_AUTHENTICATION, REQUIRE_AUTHENTICATION,
) )
# Should be callable # Should be callable
assert callable(get_conditional_authenticated_user) assert callable(get_authenticated_user)
# REQUIRE_AUTHENTICATION should be a boolean # REQUIRE_AUTHENTICATION should be a boolean
assert isinstance(REQUIRE_AUTHENTICATION, bool) assert isinstance(REQUIRE_AUTHENTICATION, bool)
@ -142,12 +142,12 @@ class TestConditionalAuthenticationEnvironmentVariables:
"""Test that REQUIRE_AUTHENTICATION defaults to false when imported with no env var.""" """Test that REQUIRE_AUTHENTICATION defaults to false when imported with no env var."""
with patch.dict(os.environ, {}, clear=True): with patch.dict(os.environ, {}, clear=True):
# Remove module from cache to force fresh import # Remove module from cache to force fresh import
module_name = "cognee.modules.users.methods.get_conditional_authenticated_user" module_name = "cognee.modules.users.methods.get_authenticated_user"
if module_name in sys.modules: if module_name in sys.modules:
del sys.modules[module_name] del sys.modules[module_name]
# Import after patching environment - module will see empty environment # Import after patching environment - module will see empty environment
from cognee.modules.users.methods.get_conditional_authenticated_user import ( from cognee.modules.users.methods.get_authenticated_user import (
REQUIRE_AUTHENTICATION, REQUIRE_AUTHENTICATION,
) )
@ -157,12 +157,12 @@ class TestConditionalAuthenticationEnvironmentVariables:
"""Test that REQUIRE_AUTHENTICATION=true is parsed correctly when imported.""" """Test that REQUIRE_AUTHENTICATION=true is parsed correctly when imported."""
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "true"}): with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "true"}):
# Remove module from cache to force fresh import # Remove module from cache to force fresh import
module_name = "cognee.modules.users.methods.get_conditional_authenticated_user" module_name = "cognee.modules.users.methods.get_authenticated_user"
if module_name in sys.modules: if module_name in sys.modules:
del sys.modules[module_name] del sys.modules[module_name]
# Import after patching environment - module will see REQUIRE_AUTHENTICATION=true # Import after patching environment - module will see REQUIRE_AUTHENTICATION=true
from cognee.modules.users.methods.get_conditional_authenticated_user import ( from cognee.modules.users.methods.get_authenticated_user import (
REQUIRE_AUTHENTICATION, REQUIRE_AUTHENTICATION,
) )
@ -172,12 +172,12 @@ class TestConditionalAuthenticationEnvironmentVariables:
"""Test that REQUIRE_AUTHENTICATION=false is parsed correctly when imported.""" """Test that REQUIRE_AUTHENTICATION=false is parsed correctly when imported."""
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}): with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
# Remove module from cache to force fresh import # Remove module from cache to force fresh import
module_name = "cognee.modules.users.methods.get_conditional_authenticated_user" module_name = "cognee.modules.users.methods.get_authenticated_user"
if module_name in sys.modules: if module_name in sys.modules:
del sys.modules[module_name] del sys.modules[module_name]
# Import after patching environment - module will see REQUIRE_AUTHENTICATION=false # Import after patching environment - module will see REQUIRE_AUTHENTICATION=false
from cognee.modules.users.methods.get_conditional_authenticated_user import ( from cognee.modules.users.methods.get_authenticated_user import (
REQUIRE_AUTHENTICATION, REQUIRE_AUTHENTICATION,
) )
@ -190,12 +190,12 @@ class TestConditionalAuthenticationEnvironmentVariables:
for case in test_cases: for case in test_cases:
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": case}): with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": case}):
# Remove module from cache to force fresh import # Remove module from cache to force fresh import
module_name = "cognee.modules.users.methods.get_conditional_authenticated_user" module_name = "cognee.modules.users.methods.get_authenticated_user"
if module_name in sys.modules: if module_name in sys.modules:
del sys.modules[module_name] del sys.modules[module_name]
# Import after patching environment # Import after patching environment
from cognee.modules.users.methods.get_conditional_authenticated_user import ( from cognee.modules.users.methods.get_authenticated_user import (
REQUIRE_AUTHENTICATION, REQUIRE_AUTHENTICATION,
) )
@ -204,7 +204,7 @@ class TestConditionalAuthenticationEnvironmentVariables:
def test_current_require_authentication_value(self): def test_current_require_authentication_value(self):
"""Test that the current REQUIRE_AUTHENTICATION module value is as expected.""" """Test that the current REQUIRE_AUTHENTICATION module value is as expected."""
from cognee.modules.users.methods.get_conditional_authenticated_user import ( from cognee.modules.users.methods.get_authenticated_user import (
REQUIRE_AUTHENTICATION, REQUIRE_AUTHENTICATION,
) )
@ -219,25 +219,25 @@ class TestConditionalAuthenticationEdgeCases:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_get_default_user_raises_exception(self): async def test_get_default_user_raises_exception(self):
"""Test behavior when get_default_user raises an exception.""" """Test behavior when get_default_user raises an exception."""
from cognee.modules.users.methods.get_conditional_authenticated_user import ( from cognee.modules.users.methods.get_authenticated_user import (
get_conditional_authenticated_user, get_authenticated_user,
) )
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}): with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
with patch( with patch(
"cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user" "cognee.modules.users.methods.get_authenticated_user.get_default_user"
) as mock_get_default: ) as mock_get_default:
mock_get_default.side_effect = Exception("Database error") mock_get_default.side_effect = Exception("Database error")
# This should propagate the exception # This should propagate the exception
with pytest.raises(Exception, match="Database error"): with pytest.raises(Exception, match="Database error"):
await get_conditional_authenticated_user(user=None) await get_authenticated_user(user=None)
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_user_type_consistency(self): async def test_user_type_consistency(self):
"""Test that the function always returns the same type.""" """Test that the function always returns the same type."""
from cognee.modules.users.methods.get_conditional_authenticated_user import ( from cognee.modules.users.methods.get_authenticated_user import (
get_conditional_authenticated_user, get_authenticated_user,
) )
mock_user = User( mock_user = User(
@ -252,16 +252,16 @@ class TestConditionalAuthenticationEdgeCases:
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}): with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
with patch( with patch(
"cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user" "cognee.modules.users.methods.get_authenticated_user.get_default_user"
) as mock_get_default: ) as mock_get_default:
mock_get_default.return_value = mock_default_user mock_get_default.return_value = mock_default_user
# Test with user # Test with user
result1 = await get_conditional_authenticated_user(user=mock_user) result1 = await get_authenticated_user(user=mock_user)
assert result1 == mock_user assert result1 == mock_user
# Test with None # Test with None
result2 = await get_conditional_authenticated_user(user=None) result2 = await get_authenticated_user(user=None)
assert result2 == mock_default_user assert result2 == mock_default_user
# Both should have user-like interface # Both should have user-like interface
@ -287,18 +287,18 @@ class TestAuthenticationScenarios:
which should trigger fallback to default user. which should trigger fallback to default user.
""" """
mock_default_user = SimpleNamespace(id=uuid4(), email="default@example.com") mock_default_user = SimpleNamespace(id=uuid4(), email="default@example.com")
from cognee.modules.users.methods.get_conditional_authenticated_user import ( from cognee.modules.users.methods.get_authenticated_user import (
get_conditional_authenticated_user, get_authenticated_user,
) )
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}): with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
with patch( with patch(
"cognee.modules.users.methods.get_conditional_authenticated_user.get_default_user" "cognee.modules.users.methods.get_authenticated_user.get_default_user"
) as mock_get_default: ) as mock_get_default:
mock_get_default.return_value = mock_default_user mock_get_default.return_value = mock_default_user
# All the above scenarios result in user=None being passed to our function # All the above scenarios result in user=None being passed to our function
result = await get_conditional_authenticated_user(user=None) result = await get_authenticated_user(user=None)
assert result == mock_default_user assert result == mock_default_user
mock_get_default.assert_called_once() mock_get_default.assert_called_once()
@ -312,10 +312,10 @@ class TestAuthenticationScenarios:
is_verified=True, is_verified=True,
) )
from cognee.modules.users.methods.get_conditional_authenticated_user import ( from cognee.modules.users.methods.get_authenticated_user import (
get_conditional_authenticated_user, get_authenticated_user,
) )
with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}): with patch.dict(os.environ, {"REQUIRE_AUTHENTICATION": "false"}):
result = await get_conditional_authenticated_user(user=mock_user) result = await get_authenticated_user(user=mock_user)
assert result == mock_user assert result == mock_user