35 lines
1.2 KiB
Python
35 lines
1.2 KiB
Python
from typing import Generator, Optional
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
from sqlalchemy.orm import Session
|
|
from app.core.database import SessionLocal
|
|
from app.core.security import decode_access_token
|
|
|
|
security = HTTPBearer(auto_error=False)
|
|
|
|
def get_db() -> Generator:
|
|
"""Dependency that yields a database session and ensures closure."""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
def get_current_user_token(credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)) -> Optional[dict]:
|
|
"""Extracts and verifies JWT token payload from Authorization header."""
|
|
if not credentials:
|
|
return None
|
|
token = credentials.credentials
|
|
payload = decode_access_token(token)
|
|
return payload
|
|
|
|
def require_current_user(payload: Optional[dict] = Depends(get_current_user_token)) -> dict:
|
|
"""Ensures request is authenticated with a valid token."""
|
|
if not payload:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials or token expired",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
return payload
|