from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from jose import jwt, JWTError from sqlalchemy.orm import Session from app.db.session import get_db from app.models.user import User from app.core.config import settings from app.core.security import ALGORITHM from app.schemas.token import TokenPayload oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_STR}/auth/login") def get_current_user( db: Session = Depends(get_db), token: str = Depends(oauth2_scheme) ) -> User: """ Get the current user based on the JWT token. """ 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=[ALGORITHM] ) user_id: str = payload.get("sub") if user_id is None: raise credentials_exception token_data = TokenPayload(sub=user_id, exp=payload.get("exp")) except JWTError: raise credentials_exception user = db.query(User).filter(User.id == token_data.sub).first() if user is None: raise credentials_exception if not user.is_active: raise HTTPException(status_code=400, detail="Inactive user") return user