Spaces:
Running
Running
| import logging | |
| from datetime import datetime, timedelta | |
| from jose import JWTError, jwt | |
| from fastapi import HTTPException, status, Depends | |
| from fastapi.security import OAuth2PasswordBearer | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| SECRET_KEY = "a866319fb3f839e693191763019cf0dd3d78473d4d3d06d99afb3ef0b14bd0d5" | |
| ALGORITHM = "HS256" | |
| ACCESS_TOKEN_EXPIRE_MINUTES = 30 | |
| oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/token") | |
| def create_access_token(data: dict): | |
| to_encode = data.copy() | |
| 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 | |
| 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"}, | |
| ) | |
| logger.info(f"Attempting to validate token: {token[:20]}...") # Log first 20 chars of token | |
| try: | |
| payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) | |
| username: str = payload.get("sub") | |
| logger.info(f"Decoded payload: username={username}") | |
| if username is None: | |
| logger.error("No username in payload") | |
| raise credentials_exception | |
| except JWTError as e: | |
| logger.error(f"JWTError during token decoding: {str(e)}") | |
| raise credentials_exception | |
| print("\n\n\n") | |
| logger.info(f"Token validated for username: {username}") | |
| print("\n\n\n") | |
| return {"username": username} |