- Add slowapi limiter with 100/minute default limit - Create CsrfSettings Pydantic model for fastapi-csrf-protect - Add deps.py with get_db re-export and validate_csrf dependency - Configure secure cookie settings (httponly, samesite=lax)
41 lines
1.1 KiB
Python
41 lines
1.1 KiB
Python
"""FastAPI dependency injection utilities."""
|
|
|
|
from typing import Annotated
|
|
|
|
from fastapi import Depends, Request
|
|
from fastapi_csrf_protect import CsrfProtect
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from backend.app.core.security import CsrfSettings
|
|
from backend.app.db.session import get_db as _get_db
|
|
|
|
# Re-export get_db for cleaner imports in endpoints
|
|
get_db = _get_db
|
|
|
|
|
|
# Type alias for common dependency
|
|
DbSession = Annotated[AsyncSession, Depends(get_db)]
|
|
|
|
|
|
@CsrfProtect.load_config
|
|
def get_csrf_config() -> CsrfSettings:
|
|
"""Load CSRF configuration for fastapi-csrf-protect."""
|
|
return CsrfSettings()
|
|
|
|
|
|
async def validate_csrf(
|
|
request: Request,
|
|
csrf_protect: CsrfProtect = Depends(),
|
|
) -> None:
|
|
"""Validate CSRF token for state-changing requests.
|
|
|
|
Use as dependency on POST/PUT/DELETE endpoints that need CSRF protection:
|
|
|
|
@router.post("/items")
|
|
async def create_item(
|
|
_: None = Depends(validate_csrf),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
...
|
|
"""
|
|
await csrf_protect.validate_csrf(request)
|