| from fastapi import HTTPException, Header | |
| import jwt | |
| from dotenv import load_dotenv | |
| import os | |
| load_dotenv() | |
| def get_secret_key(): | |
| return os.getenv("SECRET_KEY") | |
| async def verify_token(authorization: str = Header(...)): | |
| try: | |
| token_type, token = authorization.split() | |
| if token_type.lower() != "bearer": | |
| raise HTTPException(status_code=401, detail="Invalid token type") | |
| return jwt.decode(token, get_secret_key(), algorithms=["HS256"]) | |
| except jwt.ExpiredSignatureError: | |
| raise HTTPException(status_code=401, detail="Token has expired") | |
| except (jwt.InvalidTokenError, IndexError): | |
| raise HTTPException(status_code=401, detail="Invalid token") |