Skip to content

API Dependency Injection (Autogenerated)

This page contains auto-generated documentation for the dependency injection utilities in the ReViewPoint backend.

api.deps

REQUEST_ID_HEADER = 'X-Request-ID' module-attribute

request_id_ctx_var = contextvars.ContextVar('request_id', default=None) module-attribute

current_user_id_ctx_var = contextvars.ContextVar('user_id', default=None) module-attribute

oauth2_scheme = OAuth2PasswordBearer(tokenUrl='/api/v1/auth/login') module-attribute

api_key_header = APIKeyHeader(name='X-API-Key', auto_error=False) module-attribute

MAX_LIMIT = 100 module-attribute

K = TypeVar('K') module-attribute

V = TypeVar('V') module-attribute

registry = DependencyRegistry() module-attribute

dependency_metrics = {} module-attribute

get_user_repository = lru_cache()(get_user_repository_func) module-attribute

DependencyEntry

Bases: TypedDict

factory instance-attribute

singleton instance-attribute

cache_ttl instance-attribute

instance instance-attribute

last_access instance-attribute

DependencyRegistry

register(key, factory, singleton=True, cache_ttl=None) classmethod

Source code in api/deps.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
@classmethod
def register(
    cls,
    key: str,
    factory: Callable[[], object],
    singleton: bool = True,
    cache_ttl: float | None = None,
) -> None:
    cls._instances[key] = {
        "factory": factory,
        "singleton": singleton,
        "cache_ttl": cache_ttl,
        "instance": None,
        "last_access": None,
    }

get(key) classmethod

Source code in api/deps.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
@classmethod
def get(cls, key: str) -> object:
    if key not in cls._instances:
        raise KeyError(f"Dependency {key} not registered")
    entry: DependencyEntry = cls._instances[key]
    # Use .get() with defaults for all optional keys
    singleton: bool = entry.get("singleton", True)
    instance: object | None = entry.get("instance", None)
    factory: Callable[[], object] | None = entry.get("factory")
    if factory is None:
        raise RuntimeError(f"Dependency entry for '{key}' is missing a factory.")
    cache_ttl: float | None = entry.get("cache_ttl", None)
    last_access: float | None = entry.get("last_access", None)

    if not singleton or instance is None:
        instance = factory()
        entry["instance"] = instance
    if cache_ttl is not None and last_access is not None:
        now: float = time.time()
        if now - last_access > cache_ttl:
            instance = factory()
            entry["instance"] = instance
    entry["last_access"] = time.time()
    return entry.get("instance")

FeatureFlagsProtocol

Bases: Protocol

is_enabled(feature_name)

Source code in api/deps.py
239
def is_enabled(self, feature_name: str) -> bool: ...

HealthCheck

register(name, check_func) classmethod

Source code in api/deps.py
271
272
273
274
275
276
277
@classmethod
def register(
    cls,
    name: str,
    check_func: Callable[[], bool | Awaitable[bool]],
) -> None:
    cls._checks[name] = check_func

check_all() async classmethod

Source code in api/deps.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
@classmethod
async def check_all(cls) -> dict[str, dict[str, str | bool]]:
    results: dict[str, dict[str, str | bool]] = {}
    import asyncio

    for name, check_func in cls._checks.items():
        try:
            result = check_func()
            if asyncio.iscoroutine(result):
                is_healthy = await result
            else:
                is_healthy = result
            results[name] = {"status": "healthy" if is_healthy else "unhealthy"}
        except Exception as exc:
            results[name] = {"status": "error", "message": str(exc)}
    return results

DependencyMetric

Bases: TypedDict

count instance-attribute

errors instance-attribute

total_time instance-attribute

PaginationParams(offset=0, limit=20)

Standardized pagination parameters for API endpoints.

Parameters:

Name Type Description Default
offset int

Number of items to skip (default 0, must be >= 0).

0
limit int

Number of items to return (default 20, 1 <= limit <= MAX_LIMIT).

20
Usage

params = Depends(pagination_params) items = repo.list(offset=params.offset, limit=params.limit)

Source code in api/deps.py
397
398
399
def __init__(self, offset: int = 0, limit: int = 20) -> None:
    self.offset: int = offset
    self.limit: int = limit

offset = offset instance-attribute

limit = limit instance-attribute

get_user_service()

Source code in api/deps.py
178
179
def get_user_service() -> UserService:
    return UserService()

get_user_repository_func()

Source code in api/deps.py
182
183
def get_user_repository_func() -> object:
    return registry.get("user_repository")

get_blacklist_token()

Source code in api/deps.py
186
187
def get_blacklist_token() -> Callable[..., Awaitable[None]]:
    return cast("Callable[..., Awaitable[None]]", registry.get("blacklist_token"))

get_user_action_limiter()

Source code in api/deps.py
190
191
def get_user_action_limiter() -> Callable[..., Awaitable[None]]:
    return cast("Callable[..., Awaitable[None]]", registry.get("user_action_limiter"))

get_validate_email()

Source code in api/deps.py
194
195
def get_validate_email() -> Callable[[str], bool]:
    return cast("Callable[[str], bool]", registry.get("validate_email"))

get_password_validation_error()

Source code in api/deps.py
198
199
200
201
def get_password_validation_error() -> Callable[[str], str | None]:
    return cast(
        "Callable[[str], str | None]", registry.get("password_validation_error")
    )

get_async_refresh_access_token()

Source code in api/deps.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def get_async_refresh_access_token() -> (
    Callable[[AsyncSession, str], Awaitable[object]]
):
    async_refresh_access_token = cast(
        "Callable[[AsyncSession, str, str, str], Awaitable[object]]",
        registry.get("async_refresh_access_token"),
    )

    async def wrapper(session: AsyncSession, token: str) -> object:
        settings = get_settings()
        jwt_secret_key: str | None = settings.jwt_secret_key
        jwt_algorithm: str | None = settings.jwt_algorithm
        if jwt_secret_key is None or jwt_algorithm is None:
            raise RuntimeError("JWT secret key and algorithm must be set in settings.")
        return await async_refresh_access_token(
            session,
            token,
            jwt_secret_key,
            jwt_algorithm,
        )

    return wrapper

get_service(module_path)

Source code in api/deps.py
231
232
def get_service(module_path: str) -> object:
    return importlib.import_module(module_path)

get_feature_flags()

Source code in api/deps.py
242
243
244
245
def get_feature_flags() -> FeatureFlagsProtocol:
    from src.core.feature_flags import FeatureFlags

    return FeatureFlags()

require_feature(feature_name)

Source code in api/deps.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
def require_feature(
    feature_name: str,
) -> Callable[[FeatureFlagsProtocol], Awaitable[bool]]:
    async def dependency(
        flags: FeatureFlagsProtocol = Depends(get_feature_flags),
    ) -> bool:
        if not flags.is_enabled(feature_name):
            http_error(
                404,
                "This feature is not available",
                logger.warning,
            )
        return True

    return dependency

measure_dependency(func)

Source code in api/deps.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def measure_dependency(
    func: Callable[..., Awaitable[object]],
) -> Callable[..., Awaitable[object]]:
    @wraps(func)
    async def wrapper(*args: object, **kwargs: object) -> object:
        start: float = time.time()
        status: Literal["success", "error"] = "success"
        result: object | None = None
        try:
            result = await func(*args, **kwargs)
        except Exception:
            status = "error"
            raise
        finally:
            duration: float = time.time() - start
            name: str = func.__name__
            if name not in dependency_metrics:
                dependency_metrics[name] = {"count": 0, "errors": 0, "total_time": 0.0}
            dependency_metrics[name]["count"] += 1
            dependency_metrics[name]["total_time"] += duration
            if status == "error":
                dependency_metrics[name]["errors"] += 1
        return result

    return wrapper

get_refreshable_settings()

Source code in api/deps.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
def get_refreshable_settings() -> object:
    class RefreshableSettings:
        _last_refresh: float
        _refresh_interval: float
        _settings: object | None

        def __init__(self) -> None:
            self._last_refresh = 0.0
            self._refresh_interval = 60.0
            self._settings = None

        def _reload_if_needed(self) -> None:
            now: float = time.time()
            if (
                now - self._last_refresh > self._refresh_interval
                or self._settings is None
            ):
                import importlib

                import src.core.config

                importlib.reload(src.core.config)
                self._settings = src.core.config.settings
                self._last_refresh = now

        def __getattr__(self, name: str) -> object:
            self._reload_if_needed()
            if self._settings is None:
                raise AttributeError("Settings not loaded")
            return getattr(self._settings, name)

    return RefreshableSettings()

pagination_params(offset=Query(0, ge=0, description='Number of items to skip (offset)'), limit=Query(20, ge=1, le=MAX_LIMIT, description=f'Max number of items to return (max {MAX_LIMIT})'))

Dependency to standardize and validate pagination query parameters.

Parameters
offset (int): Number of items to skip (>=0, default 0)
limit (int): Number of items to return (1 to MAX_LIMIT, default 20)
Returns
PaginationParams: Validated pagination parameters.
Raises
HTTPException(400): If offset or limit is out of bounds.

Usage: params = Depends(pagination_params) items = repo.list(offset=params.offset, limit=params.limit)

Source code in api/deps.py
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
def pagination_params(
    offset: int = Query(0, ge=0, description="Number of items to skip (offset)"),
    limit: int = Query(
        20,
        ge=1,
        le=MAX_LIMIT,
        description=f"Max number of items to return (max {MAX_LIMIT})",
    ),
) -> PaginationParams:
    """Dependency to standardize and validate pagination query parameters.

    Parameters
    ----------
        offset (int): Number of items to skip (>=0, default 0)
        limit (int): Number of items to return (1 to MAX_LIMIT, default 20)

    Returns
    -------
        PaginationParams: Validated pagination parameters.

    Raises
    ------
        HTTPException(400): If offset or limit is out of bounds.
    Usage:
        params = Depends(pagination_params)
        items = repo.list(offset=params.offset, limit=params.limit)

    """
    if offset < 0:
        logger.error(f"Invalid offset: {offset}")
        http_error(400, "Offset must be >= 0", logger.error)
        raise RuntimeError("unreachable after http_error")
    if limit < 1 or limit > MAX_LIMIT:
        logger.error(f"Invalid limit: {limit}")
        http_error(
            400,
            f"Limit must be between 1 and {MAX_LIMIT}",
            logger.error,
        )
        raise RuntimeError("unreachable after http_error")
    logger.info(f"Pagination params accepted: offset={offset}, limit={limit}")
    return PaginationParams(offset=offset, limit=limit)

get_current_user(token=Depends(oauth2_scheme), session=Depends(get_async_session)) async

Dependency to extract and validate a JWT token from the request and fetch the current user from the database.

Parameters
token (str): JWT access token from the Authorization header.
session (AsyncSession): SQLAlchemy async session.
Returns
User: The authenticated and active user instance.
Raises
HTTPException(401): If token is invalid/expired, or user is not found/inactive/deleted.

Usage: user = Depends(get_current_user)

Source code in api/deps.py
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
async def get_current_user(
    token: str = Depends(oauth2_scheme),
    session: AsyncSession = Depends(get_async_session),
) -> User | None:
    """Dependency to extract and validate a JWT token from the request and fetch the current user from the database.

    Parameters
    ----------
        token (str): JWT access token from the Authorization header.
        session (AsyncSession): SQLAlchemy async session.

    Returns
    -------
        User: The authenticated and active user instance.

    Raises
    ------
        HTTPException(401): If token is invalid/expired, or user is not found/inactive/deleted.
    Usage:
        user = Depends(get_current_user)

    """
    settings = get_settings()
    if not settings.auth_enabled:
        logger.warning("Authentication is DISABLED! Returning development admin user.")
        return _get_dev_admin_user()
    user_id = None
    role = None
    try:
        payload = verify_access_token(token)
        if not payload:
            logger.error("Token verification returned empty payload")
            raise ValueError("Empty payload")
        user_id = payload.get("sub")
        role = payload.get("role")
        if not user_id:
            logger.error("Token payload missing 'sub' (user id)")
            raise ValueError("Missing user id")
    except (JWTError, ValueError, TypeError) as err:
        logger.error(f"Token validation failed: {err}")
        http_error(
            status.HTTP_401_UNAUTHORIZED,
            "Invalid token",
            logger.error,
            None,
            err,
        )
    # Support both int and str (email) user_id
    user = None
    if user_id is not None:
        user = await _resolve_user_from_id(session, user_id)
    if not user or not user.is_active or user.is_deleted:
        logger.error(f"User not found or inactive/deleted: user_id={user_id}")
        http_error(
            status.HTTP_401_UNAUTHORIZED,
            "User not found or inactive",
            logger.warning,
        )
        # mypy: unreachable after http_error, but needed for type checkers
        return None
    # Attach role from JWT if present
    if user is not None and role:
        user.role = role
    if user is not None:
        logger.info(f"User authenticated: user_id={user_id}, role={role}")
    return user

optional_get_current_user(token=Depends(oauth2_scheme), session=Depends(get_async_session)) async

Like get_current_user, but returns None instead of raising if token is invalid/missing.

Parameters
token (str): JWT access token from the Authorization header.
session (AsyncSession): SQLAlchemy async session.
Returns
User | None: The authenticated user, or None if not authenticated.

Usage: user = Depends(optional_get_current_user)

Source code in api/deps.py
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
async def optional_get_current_user(
    token: str = Depends(oauth2_scheme),
    session: AsyncSession = Depends(get_async_session),
) -> User | None:
    """Like get_current_user, but returns None instead of raising if token is invalid/missing.

    Parameters
    ----------
        token (str): JWT access token from the Authorization header.
        session (AsyncSession): SQLAlchemy async session.

    Returns
    -------
        User | None: The authenticated user, or None if not authenticated.
    Usage:
        user = Depends(optional_get_current_user)

    """
    settings = get_settings()
    if not settings.auth_enabled:
        return _get_dev_admin_user()
    try:
        payload = verify_access_token(
            token,
        )  # Only pass token, matches function signature
        user_id_raw = payload.get("sub")
        if user_id_raw is None:
            return None
        user_id = int(user_id_raw)
        user = await get_user_by_id(session, user_id)
        if not user or not user.is_active or user.is_deleted:
            return None
        return user
    except Exception:
        return None

get_db() async

Dependency that provides a SQLAlchemy AsyncSession for database operations.

Yields:

Name Type Description
AsyncSession AsyncGenerator[AsyncSession, None]

SQLAlchemy async session for DB operations.

Raises:

Type Description
HTTPException(500)

If database session cannot be established or used.

Usage: async def endpoint(db: AsyncSession = Depends(get_db)): ...

Source code in api/deps.py
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
async def get_db() -> AsyncGenerator[AsyncSession, None]:
    """Dependency that provides a SQLAlchemy AsyncSession for database operations.

    Yields:
        AsyncSession: SQLAlchemy async session for DB operations.

    Raises:
        HTTPException(500): If database session cannot be established or used.
    Usage:
        async def endpoint(db: AsyncSession = Depends(get_db)):
            ...

    """
    from src.core.database import AsyncSessionLocal, ensure_engine_initialized

    # Extra safety: ensure AsyncSessionLocal is initialized
    if AsyncSessionLocal is None:
        ensure_engine_initialized()
    if AsyncSessionLocal is None:
        # Defensive: if still None, raise error
        raise RuntimeError("AsyncSessionLocal is not initialized.")
    session = AsyncSessionLocal()
    logger.info("Database session created.")
    try:
        yield session
    except Exception as exc:
        logger.error(f"Database session error: {exc}")
        await session.rollback()
        raise  # Let FastAPI handle the exception properly
    finally:
        await session.close()
        logger.info("Database session closed.")

get_current_active_user(user=Depends(get_current_user)) async

Dependency to ensure the current user is active.

Parameters
user (User): The user instance from get_current_user.
Returns
User: The active user instance.
Raises
HTTPException(403): If the user is inactive or deleted.

Usage: user = Depends(get_current_active_user)

Source code in api/deps.py
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
async def get_current_active_user(
    user: User | None = Depends(get_current_user),
) -> User | None:
    """Dependency to ensure the current user is active.

    Parameters
    ----------
        user (User): The user instance from get_current_user.

    Returns
    -------
        User: The active user instance.

    Raises
    ------
        HTTPException(403): If the user is inactive or deleted.
    Usage:
        user = Depends(get_current_active_user)

    """
    if not user or not user.is_active or user.is_deleted:
        logger.error(
            f"Inactive or deleted user tried to access: user_id={getattr(user, 'id', None)}",
        )
        http_error(
            status.HTTP_403_FORBIDDEN,
            "Inactive or deleted user.",
            logger.warning,
        )
        raise RuntimeError("unreachable after http_error")  # for type checkers
    logger.info(f"Active user check passed: user_id={user.id if user else None}")
    return user

get_request_id(request)

Dependency to extract or generate a request ID for tracing.

Parameters
request (Request): FastAPI request object.
Returns
str: The request ID (from header or generated UUID).

Usage: request_id = Depends(get_request_id)

Source code in api/deps.py
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
def get_request_id(request: Request) -> str:
    """Dependency to extract or generate a request ID for tracing.

    Parameters
    ----------
        request (Request): FastAPI request object.

    Returns
    -------
        str: The request ID (from header or generated UUID).
    Usage:
        request_id = Depends(get_request_id)

    """
    req_id = request.headers.get(REQUEST_ID_HEADER)
    # Basic validation: must be a valid UUID or a string of reasonable length
    try:
        if req_id:
            uuid.UUID(str(req_id))
        else:
            raise ValueError
    except (ValueError, TypeError):
        req_id = str(uuid.uuid4())
    request_id_ctx_var.set(req_id)
    return req_id

get_current_request_id()

Helper to get the current request ID from contextvar.

Returns:

Type Description
str | None

str | None: The current request ID, or None if not set.

Usage: req_id = get_current_request_id()

Source code in api/deps.py
668
669
670
671
672
673
674
675
676
677
def get_current_request_id() -> str | None:
    """Helper to get the current request ID from contextvar.

    Returns:
        str | None: The current request ID, or None if not set.
    Usage:
        req_id = get_current_request_id()

    """
    return request_id_ctx_var.get()

validate_api_key(api_key=Security(api_key_header)) async

Validate the API key from the X-API-Key header.

Parameters
api_key (str | None): API key from the X-API-Key header.
Returns
bool: True if the API key is valid, False otherwise.
Source code in api/deps.py
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
async def validate_api_key(
    api_key: str | None = Security(api_key_header),
) -> bool:
    """Validate the API key from the X-API-Key header.

    Parameters
    ----------
        api_key (str | None): API key from the X-API-Key header.

    Returns
    -------
        bool: True if the API key is valid, False otherwise.

    """
    settings = get_settings()

    if not settings.api_key_enabled:
        # API key validation is disabled, always return True
        return True

    # If API key validation is enabled but no key provided
    if not api_key:
        logger.warning(
            "API key validation is enabled but no API key provided in request",
        )
        return False

    # Get the configured API key from settings
    configured_api_key = settings.api_key
    if not configured_api_key:
        logger.warning("API key validation is enabled but no API key is configured")
        return False

    # Check if the provided API key matches the configured one
    return api_key == configured_api_key

require_api_key(api_key=Header(None, alias='X-API-Key'))

Dependency to require a valid API key.

Parameters
api_key (str | None): API key from the X-API-Key header.
Raises
HTTPException(401): If the API key is missing or invalid.

Usage: _ = Depends(require_api_key)

Source code in api/deps.py
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
def require_api_key(api_key: str | None = Header(None, alias="X-API-Key")) -> None:
    """Dependency to require a valid API key.

    Parameters
    ----------
        api_key (str | None): API key from the X-API-Key header.

    Raises
    ------
        HTTPException(401): If the API key is missing or invalid.
    Usage:
        _ = Depends(require_api_key)

    """
    settings = get_settings()

    if not settings.api_key_enabled:
        # API key validation is disabled, always pass
        return

    # If API key validation is enabled but no key provided
    if not api_key:
        http_error(
            status.HTTP_401_UNAUTHORIZED,
            "API key is required",
            logger.warning,
        )

    # Get the configured API key from settings
    configured_api_key = settings.api_key
    if not configured_api_key:
        logger.warning("API key validation is enabled but no API key is configured")
        http_error(
            status.HTTP_500_INTERNAL_SERVER_ERROR,
            "API key validation misconfigured",
            logger.error,
        )

    # Check if the provided API key matches the configured one
    if api_key != configured_api_key:
        http_error(
            status.HTTP_401_UNAUTHORIZED,
            "Invalid API key",
            logger.warning,
        )

get_current_user_with_api_key(token=Depends(oauth2_scheme), session=Depends(get_async_session), _=Depends(require_api_key)) async

Like get_current_user, but also requires a valid API key. This function should be used for endpoints that require both JWT authentication and API key validation.

Source code in api/deps.py
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
async def get_current_user_with_api_key(
    token: str = Depends(oauth2_scheme),
    session: AsyncSession = Depends(get_async_session),
    _: None = Depends(require_api_key),
) -> User:
    """Like get_current_user, but also requires a valid API key.
    This function should be used for endpoints that require both
    JWT authentication and API key validation.
    """
    user = await get_current_user(token, session)
    if user is None:
        http_error(
            status.HTTP_401_UNAUTHORIZED,
            "Invalid or missing user.",
            logger.error,
        )
        raise RuntimeError(
            "Invalid or missing user.",
        )  # Defensive, should never reach here
    return user

require_admin(current_user=Depends(get_current_active_user))

Dependency that ensures the current user is an admin. Raises 403 if not.

Source code in api/deps.py
788
789
790
791
792
793
794
795
796
797
def require_admin(current_user: User = Depends(get_current_active_user)) -> User:
    """Dependency that ensures the current user is an admin.
    Raises 403 if not.
    """
    if not current_user or not getattr(current_user, "is_admin", False):
        raise HTTPException(
            status.HTTP_403_FORBIDDEN,
            detail="Admin privileges required.",
        )
    return current_user

require_api_key_for_exports(api_key=Header(None, alias='X-API-Key'))

Dependency to validate API key for export endpoints based on global settings. If REVIEWPOINT_API_KEY_ENABLED is true, this requires a valid API key. If REVIEWPOINT_API_KEY_ENABLED is false, this function does nothing and allows access.

NOTE: This function is deprecated. Use get_current_user_with_export_api_key instead which handles both JWT and API key validation in one dependency.

Parameters
api_key (str): API key from the X-API-Key header.
Raises
HTTPException(401): If API keys are enabled and the API key is missing or invalid.

Usage: _ = Depends(require_api_key_for_exports)

Source code in api/deps.py
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
def require_api_key_for_exports(
    api_key: str | None = Header(None, alias="X-API-Key"),
) -> None:
    """Dependency to validate API key for export endpoints based on global settings.
    If REVIEWPOINT_API_KEY_ENABLED is true, this requires a valid API key.
    If REVIEWPOINT_API_KEY_ENABLED is false, this function does nothing and allows access.

    NOTE: This function is deprecated. Use get_current_user_with_export_api_key instead
    which handles both JWT and API key validation in one dependency.

    Parameters
    ----------
        api_key (str): API key from the X-API-Key header.

    Raises
    ------
        HTTPException(401): If API keys are enabled and the API key is missing or invalid.
    Usage:
        _ = Depends(require_api_key_for_exports)

    """
    settings = get_settings()

    # If API key validation is disabled globally, allow access
    if not settings.api_key_enabled:
        return

    # API key validation is enabled, so require it
    if not api_key:
        logger.warning(
            "Export endpoint accessed without API key when API key validation is enabled",
        )
        http_error(
            status.HTTP_401_UNAUTHORIZED,
            "API key required for export endpoints",
            logger.warning,
        )

    # Get the configured API key from settings
    configured_api_key = settings.api_key
    if not configured_api_key:
        logger.warning("API key validation required but no API key is configured")
        http_error(
            status.HTTP_401_UNAUTHORIZED,
            "API key validation is not properly configured",
            logger.warning,
        )

    # Check if the provided API key matches the configured one
    if api_key != configured_api_key:
        logger.warning("Invalid API key provided for export endpoint")
        http_error(
            status.HTTP_401_UNAUTHORIZED,
            "Invalid API key",
            logger.warning,
        )

get_current_user_with_export_api_key(request, session=Depends(get_async_session)) async

Authentication dependency for export endpoints that respects global API key settings.

When REVIEWPOINT_AUTH_ENABLED is false
  • Returns development admin user regardless of token validity
When REVIEWPOINT_AUTH_ENABLED is true and REVIEWPOINT_API_KEY_ENABLED is true
  • Requires both valid JWT token and API key
  • Returns the authenticated User
When REVIEWPOINT_AUTH_ENABLED is true and REVIEWPOINT_API_KEY_ENABLED is false
  • Only requires JWT token (if provided)
  • If JWT token is provided, validates it and returns User
  • If JWT token is invalid, raises 401 error
  • If no JWT token is provided, returns None (unauthenticated access allowed)
Source code in api/deps.py
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
async def get_current_user_with_export_api_key(
    request: Request,
    session: AsyncSession = Depends(get_async_session),
) -> User | None:
    """Authentication dependency for export endpoints that respects global API key settings.

    When REVIEWPOINT_AUTH_ENABLED is false:
        - Returns development admin user regardless of token validity

    When REVIEWPOINT_AUTH_ENABLED is true and REVIEWPOINT_API_KEY_ENABLED is true:
        - Requires both valid JWT token and API key
        - Returns the authenticated User

    When REVIEWPOINT_AUTH_ENABLED is true and REVIEWPOINT_API_KEY_ENABLED is false:
        - Only requires JWT token (if provided)
        - If JWT token is provided, validates it and returns User
        - If JWT token is invalid, raises 401 error
        - If no JWT token is provided, returns None (unauthenticated access allowed)
    """
    settings = get_settings()

    # Check if authentication is disabled globally
    if not settings.auth_enabled:
        logger.warning("Authentication is DISABLED! Returning development admin user.")
        return _get_dev_admin_user()

    # Check JWT token first (regardless of API key setting)
    authorization = request.headers.get("Authorization")

    if authorization:
        # If Authorization header is provided, validate it
        try:
            scheme, token = authorization.split()
            if scheme.lower() != "bearer":
                http_error(
                    status.HTTP_401_UNAUTHORIZED,
                    "Invalid authentication scheme",
                    logger.warning,
                )
                return None
        except ValueError:
            http_error(
                status.HTTP_401_UNAUTHORIZED,
                "Invalid authorization header format",
                logger.warning,
            )
            return None

        # Validate JWT token - always do full validation when auth is enabled
        current_user = await get_current_user(token, session)

        # If API key validation is enabled, also check API key
        if settings.api_key_enabled:
            api_key = request.headers.get("X-API-Key")
            if not api_key:
                logger.warning(
                    "Export endpoint accessed without API key when API key validation is enabled",
                )
                http_error(
                    status.HTTP_401_UNAUTHORIZED,
                    "API key required for export endpoints",
                    logger.warning,
                )

            # Get the configured API key from settings
            configured_api_key = settings.api_key
            if not configured_api_key:
                logger.warning(
                    "API key validation required but no API key is configured",
                )
                http_error(
                    status.HTTP_401_UNAUTHORIZED,
                    "API key validation is not properly configured",
                    logger.warning,
                )

            # Check if the provided API key matches the configured one
            if api_key != configured_api_key:
                logger.warning("Invalid API key provided for export endpoint")
                http_error(
                    status.HTTP_401_UNAUTHORIZED,
                    "Invalid API key",
                    logger.warning,
                )

        return current_user
    # No Authorization header provided
    if settings.api_key_enabled:
        # API key validation is enabled, so authentication is required
        http_error(
            status.HTTP_401_UNAUTHORIZED,
            "Authentication required",
            logger.warning,
        )
        return None
    # API key validation is disabled, allow unauthenticated access
    return None

handler: python options: show_root_heading: true show_source: true heading_level: 2 docstring_style: google members_order: source merge_init_into_class: true show_if_no_docstring: true separate_signature: true