Created content endpoint to serve files from content directory

This commit is contained in:
2025-05-05 16:14:13 -05:00
parent 2ad1d713cb
commit cc95e35c7f
8 changed files with 78 additions and 52 deletions

33
src/routers/content.py Normal file
View File

@@ -0,0 +1,33 @@
from fastapi import APIRouter, Depends, Path, HTTPException
from fastapi.responses import FileResponse
from utils.auth import authenticate_user_query
from pathlib import Path as FilePath
from config import CONTENT_PATH
router = APIRouter(prefix="/content", tags=["content"])
@router.get("/{filename}")
async def serve_content(
username: str = Depends(authenticate_user_query),
filename: str = Path(..., min_length=1), # Ensure filename is not empty
):
"""
Serves a specific file from the configured content directory by filename only.
Prevents directory traversal and ensures files are served from the base content directory.
"""
base_dir = FilePath(CONTENT_PATH).resolve()
requested_file = base_dir / filename
print(f"Requested file: {requested_file}")
# Security checks
try:
# Resolve the full path and check it's within base directory
requested_file = requested_file.resolve()
if not requested_file.is_relative_to(base_dir):
raise ValueError("Invalid path")
except (ValueError, FileNotFoundError):
raise HTTPException(status_code=404, detail="File not found")
if not requested_file.is_file():
raise HTTPException(status_code=404, detail="File not found")
return FileResponse(requested_file)