from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from jose import JWTError, jwt from sqlalchemy.orm import Session from .core.config import settings from .crud import get_user_by_id from .db.session import get_db from .models import User oauth2_scheme = OAuth2PasswordBearer(tokenUrl='/auth/login') def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> User: credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail='Token inválido o expirado', headers={'WWW-Authenticate': 'Bearer'}, ) try: payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm]) user_id = payload.get('sub') if user_id is None: raise credentials_exception except JWTError as exc: raise credentials_exception from exc user = get_user_by_id(db, int(user_id)) if user is None: raise credentials_exception return user