Spaces:
Sleeping
Sleeping
| from fastapi import Depends, HTTPException, status | |
| from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials | |
| from jose import jwt, JWTError | |
| from sqlalchemy.orm import Session | |
| from core.config import settings | |
| from core.database import get_db | |
| from models.user import User | |
| security = HTTPBearer() | |
| def get_current_user( | |
| credentials: HTTPAuthorizationCredentials = Depends(security), | |
| db: Session = Depends(get_db) | |
| ): | |
| token = credentials.credentials | |
| try: | |
| payload = jwt.decode( | |
| token, | |
| settings.SECRET_KEY, | |
| algorithms=[settings.ALGORITHM] | |
| ) | |
| user_id: str = payload.get("sub") | |
| if user_id is None: | |
| raise HTTPException( | |
| status_code=401, | |
| detail="Invalid token" | |
| ) | |
| except JWTError: | |
| raise HTTPException( | |
| status_code=401, | |
| detail="Token is invalid or expired" | |
| ) | |
| user = db.query(User).filter(User.id == int(user_id)).first() | |
| if not user: | |
| raise HTTPException( | |
| status_code=404, | |
| detail="User not found" | |
| ) | |
| return user |