acupedia-api/app/features/content/deps.py

121 lines
3.7 KiB
Python

from __future__ import annotations
from uuid import UUID
from fastapi import Depends, Header, HTTPException, Query, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.cache.content_cache import ContentCache
from app.cache.deps import (
get_cache_service,
get_content_cache_invalidator,
)
from app.cache.invalidation import ContentCacheInvalidator
from app.cache.service import CacheService
from app.core.config import settings
from app.db.models import AppUser, Role, UserRole
from app.db.session import get_db_session
from app.features.auth.security import decode_access_token
from app.features.media_storage import MediaUrlResolver, get_media_url_resolver
from app.features.search.deps import get_search_repository
from app.features.search.repository import SearchRepository
from .repository import ContentRepository
from .service import ContentService
def get_content_repository(
session: AsyncSession = Depends(get_db_session),
) -> ContentRepository:
return ContentRepository(session)
def get_content_service(
session: AsyncSession = Depends(get_db_session),
repository: ContentRepository = Depends(get_content_repository),
cache_service: CacheService = Depends(get_cache_service),
invalidator: ContentCacheInvalidator = Depends(
get_content_cache_invalidator
),
search_repository: SearchRepository = Depends(get_search_repository),
media_url_resolver: MediaUrlResolver = Depends(get_media_url_resolver),
) -> ContentService:
return ContentService(
session=session,
repository=repository,
cache=ContentCache(cache_service),
invalidator=invalidator,
search_projection_writer=search_repository,
media_url_resolver=media_url_resolver,
)
async def get_content_preview_mode(
preview: bool = Query(default=False),
authorization: str | None = Header(default=None),
session: AsyncSession = Depends(get_db_session),
) -> bool:
if not preview:
return False
if not settings.content_preview_enabled:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Content preview is disabled.",
)
if not authorization:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Preview requires authentication.",
)
scheme, separator, token = authorization.partition(" ")
if separator != " " or scheme.lower() != "bearer" or not token.strip():
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid session token.",
)
try:
user_id = UUID(str(decode_access_token(token.strip())["sub"]))
except Exception as exc:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid session token.",
) from exc
user = (
await session.execute(
select(AppUser).where(
AppUser.id == user_id,
AppUser.is_active.is_(True),
)
)
).scalar_one_or_none()
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User profile not found.",
)
roles = set(
(
await session.execute(
select(Role.role_name)
.join(UserRole, UserRole.role_id == Role.id)
.where(UserRole.user_id == user.id)
)
).scalars().all()
)
if not ({"admin", "super_admin"} & roles):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Content preview requires admin privileges.",
)
return True