Spaces:
Running
Running
from fastapi import Depends, HTTPException, status | |
from fastapi.security import OAuth2PasswordBearer | |
from jose import jwt, JWTError # Ensure this is correctly imported | |
from utils.db import tinydb_helper # Ensure this instance is correctly initialized elsewhere | |
from utils.jwt_utils import SECRET_KEY, ALGORITHM, decode_jwt | |
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"}, | |
) | |
expiry_exception = HTTPException( | |
status_code=status.HTTP_401_UNAUTHORIZED, | |
detail="No session found, please login again", | |
headers={"WWW-Authenticate": "Bearer"}, | |
) | |
# Utilize the centralized JWT decoding and catch any JWT-related errors | |
try: | |
payload = decode_jwt(token) | |
except JWTError: | |
raise credentials_exception | |
user_id: str = payload.get("sub") | |
if user_id is None: | |
raise credentials_exception | |
# Verify if the token is stored and valid as active session | |
if not tinydb_helper.query_token(user_id, token): | |
raise expiry_exception | |
# Payload is already obtained and validated, so just return it or its specific parts as needed | |
return {"user_id": user_id, "name": payload.get("name"), "role": payload.get("role")} | |