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 settings from app.core.database import get_db from app.crud.user import get_user from app.models.user import User 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 from the 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=[settings.ALGORITHM] ) token_data = TokenPayload(**payload) except JWTError as e: raise credentials_exception from e user = get_user(db, user_id=token_data.sub) if not user: raise credentials_exception return user def get_current_active_user( current_user: User = Depends(get_current_user), ) -> User: """ Get the current active user """ if not current_user.is_active: raise HTTPException(status_code=400, detail="Inactive user") return current_user