Files
mtusi2026lab2/app/api/deps.py
T

47 lines
1.3 KiB
Python

from typing import Generator
from fastapi import Depends, Header, HTTPException
from sqlalchemy.orm import Session
from app.db.session import SessionLocal
from app.db.models import User
from app.services.auth_service import AuthService, InvalidSessionError
def get_db() -> Generator[Session, None, None]:
db = SessionLocal()
try:
yield db
finally:
db.close()
def get_current_user(
authorization: str | None = Header(default=None),
db: Session = Depends(get_db),
) -> User:
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(
status_code=401,
detail="Bearer token required",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
token = authorization[7:].strip()
if not token:
raise HTTPException(
status_code=401,
detail="Bearer token required",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
try:
return AuthService(db).authenticate(token)
except InvalidSessionError:
raise HTTPException(
status_code=401,
detail="Invalid or expired session",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
) from None