Spaces:
Running
Running
File size: 1,254 Bytes
bfa9638 c672e11 acdfb5c bfa9638 c672e11 831a016 c672e11 831a016 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
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"},
)
# 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
if not tinydb_helper.query_token(user_id, token):
raise credentials_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")}
|