from typing import Optional 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.db.session import get_db from app.models.user import User from app.schemas.auth import TokenPayload from app.services.user import get_user, is_active_user oauth2_scheme = OAuth2PasswordBearer( tokenUrl="/api/v1/auth/token" ) def authenticate_user(db: Session, *, email: str, password: str) -> Optional[User]: """ Authenticate a user by email and password. """ from app.services.user import get_user_by_email, verify_password user = get_user_by_email(db, email=email) if not user: return None if not verify_password(password, user.hashed_password): return None return user 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] ) user_id: str = payload.get("sub") if user_id is None: raise credentials_exception token_data = TokenPayload(sub=int(user_id)) except JWTError: raise credentials_exception user = get_user(db, user_id=token_data.sub) if user is None: 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 is_active_user(current_user): raise HTTPException(status_code=400, detail="Inactive user") return current_user