59 lines
1.7 KiB
Python
59 lines
1.7 KiB
Python
|
|
"""
|
||
|
|
FastAPI dependency for extracting and validating the current authenticated user.
|
||
|
|
"""
|
||
|
|
import uuid
|
||
|
|
|
||
|
|
from fastapi import Depends, HTTPException, status
|
||
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||
|
|
from jose import JWTError
|
||
|
|
from sqlalchemy import select
|
||
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
|
|
||
|
|
from app.auth.jwt import verify_access_token
|
||
|
|
from app.database import get_db
|
||
|
|
from app.models.user import User
|
||
|
|
|
||
|
|
bearer_scheme = HTTPBearer()
|
||
|
|
|
||
|
|
|
||
|
|
async def get_current_user(
|
||
|
|
credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
|
||
|
|
db: AsyncSession = Depends(get_db),
|
||
|
|
) -> User:
|
||
|
|
"""
|
||
|
|
Extract Bearer token from Authorization header, verify it,
|
||
|
|
and return the corresponding User from the database.
|
||
|
|
|
||
|
|
Raises:
|
||
|
|
401 HTTPException if token is missing, invalid, or expired.
|
||
|
|
401 HTTPException if the user no longer exists or is inactive.
|
||
|
|
"""
|
||
|
|
credentials_exception = HTTPException(
|
||
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||
|
|
detail="Could not validate credentials",
|
||
|
|
headers={"WWW-Authenticate": "Bearer"},
|
||
|
|
)
|
||
|
|
|
||
|
|
try:
|
||
|
|
payload = verify_access_token(credentials.credentials)
|
||
|
|
user_id: str = payload.get("sub")
|
||
|
|
if user_id is None:
|
||
|
|
raise credentials_exception
|
||
|
|
user_uuid = uuid.UUID(user_id)
|
||
|
|
except (JWTError, ValueError):
|
||
|
|
raise credentials_exception
|
||
|
|
|
||
|
|
result = await db.execute(select(User).where(User.id == user_uuid))
|
||
|
|
user = result.scalars().first()
|
||
|
|
|
||
|
|
if user is None:
|
||
|
|
raise credentials_exception
|
||
|
|
|
||
|
|
if not user.is_active:
|
||
|
|
raise HTTPException(
|
||
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||
|
|
detail="Inactive user account",
|
||
|
|
)
|
||
|
|
|
||
|
|
return user
|