from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from jose import JWTError, jwt from sqlalchemy.orm import Session from app.core.config import get_settings from app.core.database import SessionLocal from app.crud import user as user_crud from app.models.user import User settings = get_settings() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login") def get_db(): db = SessionLocal() try: yield db finally: db.close() def get_current_user( db: Session = Depends(get_db), token: str = Depends(oauth2_scheme), ) -> User: credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"]) subject = payload.get("sub") if subject is None: raise credentials_exception except JWTError: raise credentials_exception user = user_crud.get_by_email(db, subject) if not user: raise credentials_exception return user