Spaces:
Sleeping
Sleeping
from fastapi import Header, HTTPException | |
import os | |
import jwt | |
from dotenv import load_dotenv | |
load_dotenv() | |
secret_token = os.getenv("AUTH_TOKEN") | |
async def authenticate_token(authorization: str = Header(...)): | |
token_type, token = authorization.split() | |
if token_type != "Bearer": | |
raise HTTPException(status_code=401, detail="Unauthorized") | |
try: | |
return jwt.decode(token, secret_token, algorithms=["HS256"]) | |
except jwt.ExpiredSignatureError: | |
raise HTTPException(status_code=401, detail="Token has expired") from None | |
except (jwt.InvalidTokenError, IndexError): | |
raise HTTPException(status_code=401, detail="Invalid token") from None | |