Spaces:
Sleeping
Sleeping
| from jose import jwt | |
| import os | |
| from dotenv import load_dotenv | |
| from datetime import datetime, timedelta | |
| load_dotenv() | |
| SECRET_KEY = os.getenv("SECRET_KEY") | |
| ALGORITHM = os.getenv("ALGORITHM") | |
| def encode_jwt(user_id: str, access_token: str, expires_delta: timedelta = timedelta(days=130)) -> str: | |
| """Encode user_id and access_token into a JWT.""" | |
| payload = { | |
| "user_id": user_id, | |
| "access_token": access_token, | |
| "exp": datetime.now() + expires_delta # Expiration time | |
| } | |
| return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM) | |
| def decode_jwt(encoded: str) -> tuple[str, str]: | |
| """Decode the JWT back into user_id and access_token.""" | |
| try: | |
| payload = jwt.decode(encoded, SECRET_KEY, algorithms=[ALGORITHM]) | |
| return payload["user_id"], payload["access_token"] | |
| except jwt.JWTError as e: | |
| raise ValueError(f"Invalid or expired token: {str(e)}") | |