2026-02-02 23:20:32 +09:00
|
|
|
"""
|
|
|
|
|
API dependencies.
|
|
|
|
|
"""
|
2026-03-18 22:30:47 +09:00
|
|
|
from typing import Annotated, Optional
|
2026-02-02 23:20:32 +09:00
|
|
|
|
2026-03-18 22:30:47 +09:00
|
|
|
from fastapi import Cookie, Depends, HTTPException, Request, status
|
2026-02-02 23:20:32 +09:00
|
|
|
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
|
|
|
|
|
|
2026-03-18 22:30:47 +09:00
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login", auto_error=False)
|
2026-02-02 23:20:32 +09:00
|
|
|
|
|
|
|
|
|
|
|
|
|
async def get_current_user(
|
2026-03-18 22:30:47 +09:00
|
|
|
request: Request,
|
2026-02-02 23:20:32 +09:00
|
|
|
db: Annotated[Session, Depends(get_db)],
|
2026-03-18 22:30:47 +09:00
|
|
|
bearer_token: Annotated[Optional[str], Depends(oauth2_scheme)] = None,
|
2026-02-02 23:20:32 +09:00
|
|
|
) -> User:
|
2026-03-18 22:30:47 +09:00
|
|
|
"""Get the current authenticated user.
|
|
|
|
|
|
|
|
|
|
Token extraction order: httpOnly cookie first, then Authorization header fallback.
|
|
|
|
|
"""
|
2026-02-02 23:20:32 +09:00
|
|
|
credentials_exception = HTTPException(
|
|
|
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
|
|
|
detail="Could not validate credentials",
|
|
|
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
|
|
|
)
|
|
|
|
|
|
2026-03-18 22:30:47 +09:00
|
|
|
# Cookie first, then Authorization header fallback
|
|
|
|
|
token = request.cookies.get("access_token") or bearer_token
|
|
|
|
|
if token is None:
|
|
|
|
|
raise credentials_exception
|
|
|
|
|
|
2026-02-02 23:20:32 +09:00
|
|
|
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)]
|