from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from jose import JWTError, jwt from sqlalchemy.orm import Session from app.core.config import settings from app.crud import user as user_crud from app.db.session import get_db from app.models.user import User security = HTTPBearer() def get_current_user( db: Session = Depends(get_db), credentials: HTTPAuthorizationCredentials = Depends(security), ) -> User: credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode( credentials.credentials, settings.SECRET_KEY, algorithms=[settings.ALGORITHM], ) email: str = payload.get("sub") if email is None: raise credentials_exception except JWTError: raise credentials_exception user = user_crud.get_by_email(db, email=email) if user is None: raise credentials_exception return user def get_current_active_user(current_user: User = Depends(get_current_user)) -> User: if not user_crud.is_active(current_user): raise HTTPException(status_code=400, detail="Inactive user") return current_user def get_current_active_superuser( current_user: User = Depends(get_current_user), ) -> User: if not user_crud.is_superuser(current_user): raise HTTPException( status_code=400, detail="The user doesn't have enough privileges" ) return current_user