Spaces:
No application file
No application file
| from datetime import datetime, timedelta | |
| from typing import Optional | |
| import os | |
| from jose import JWTError, jwt | |
| from schemas.user import UserRead | |
| # Secret key and algorithm from environment variables | |
| SECRET_KEY = os.getenv("SECRET_KEY", "your-super-secret-key-change-in-production") | |
| ALGORITHM = os.getenv("ALGORITHM", "HS256") | |
| ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "30")) | |
| def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): | |
| """ | |
| Create a new access token with the provided data | |
| """ | |
| to_encode = data.copy() | |
| if expires_delta: | |
| expire = datetime.utcnow() + expires_delta | |
| else: | |
| expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) | |
| to_encode.update({"exp": expire}) | |
| encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) | |
| return encoded_jwt | |
| def verify_token(token: str) -> Optional[dict]: | |
| """ | |
| Verify the provided token and return the payload if valid | |
| """ | |
| try: | |
| payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) | |
| return payload | |
| except JWTError: | |
| return None |