"""FastAPI dependencies for authentication and security.""" from fastapi import Request, HTTPException from app.auth.session import verify_session from app.config import settings def get_current_user(request: Request) -> int: """ Dependency that extracts and validates the session cookie. Raises 401 if missing or invalid. Returns the user_id. """ token = request.cookies.get(settings.COOKIE_NAME) if not token: raise HTTPException(status_code=401, detail="Not authenticated") user_id = verify_session(token) if not user_id: raise HTTPException(status_code=401, detail="Session expired or invalid") return user_id def verify_csrf(request: Request) -> None: """ Dependency to mitigate CSRF for cookie-based auth. Requires X-Requested-With header on all mutating requests. """ if request.method in ["POST", "PUT", "PATCH", "DELETE"]: if request.headers.get("X-Requested-With") != "XMLHttpRequest": raise HTTPException( status_code=403, detail="CSRF check failed: missing X-Requested-With header" )