Eliminates XSS token theft by storing JWT in httpOnly Secure cookie instead of localStorage. Backend sets cookie on login and clears on logout. Token extraction uses cookie-first with Authorization header fallback for backward compatibility with existing tests. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
54 lines
1.5 KiB
Python
54 lines
1.5 KiB
Python
"""
|
|
API dependencies.
|
|
"""
|
|
from typing import Annotated, Optional
|
|
|
|
from fastapi import Cookie, Depends, HTTPException, Request, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.database import get_db
|
|
from app.core.security import decode_access_token
|
|
from app.models.user import User
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login", auto_error=False)
|
|
|
|
|
|
async def get_current_user(
|
|
request: Request,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
bearer_token: Annotated[Optional[str], Depends(oauth2_scheme)] = None,
|
|
) -> User:
|
|
"""Get the current authenticated user.
|
|
|
|
Token extraction order: httpOnly cookie first, then Authorization header fallback.
|
|
"""
|
|
credentials_exception = HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
# Cookie first, then Authorization header fallback
|
|
token = request.cookies.get("access_token") or bearer_token
|
|
if token is None:
|
|
raise credentials_exception
|
|
|
|
payload = decode_access_token(token)
|
|
if payload is None:
|
|
raise credentials_exception
|
|
|
|
username: str = payload.get("sub")
|
|
if username is None:
|
|
raise credentials_exception
|
|
|
|
user = db.query(User).filter(User.username == username).first()
|
|
if user is None:
|
|
raise credentials_exception
|
|
|
|
return user
|
|
|
|
|
|
CurrentUser = Annotated[User, Depends(get_current_user)]
|
|
DbSession = Annotated[Session, Depends(get_db)]
|