Spaces:
Sleeping
Sleeping
from fastapi import Depends, HTTPException, status | |
from fastapi.security import OAuth2PasswordBearer | |
from jose import jwt, JWTError | |
from .utils.db import tinydb_helper # Ensure correct import path | |
from .utils.jwt_utils import SECRET_KEY, ALGORITHM # Ensure these are defined in your jwt_utils.py | |
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") | |
async def get_current_user(token: str = Depends(oauth2_scheme)): | |
credentials_exception = HTTPException( | |
status_code=status.HTTP_401_UNAUTHORIZED, | |
detail="Could not validate credentials", | |
headers={"WWW-Authenticate": "Bearer"}, | |
) | |
try: | |
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) | |
user_id: str = payload.get("sub") | |
if user_id is None: | |
raise credentials_exception | |
token_data = tinydb_helper.query_token(user_id, token) | |
if not token_data: | |
raise credentials_exception | |
return token_data # Or return a user model based on the token_data | |
except JWTError: | |
raise credentials_exception | |