Download app/services/security.py from isold/MeloonTop: direct link, hf CLI and curl.
- Browser
- Download file 1.61 kB
-
https://huggingface.co/spaces/isold/MeloonTop/resolve/main/app/services/security.py
- Command line
-
hf download hf://spaces/isold/MeloonTop/app/services/security.py
-
curl -L -o security.py https://huggingface.co/spaces/isold/MeloonTop/resolve/main/app/services/security.py
1.61 kB
| import os | |
| from datetime import datetime, timedelta, timezone | |
| from typing import Optional | |
| import jwt | |
| from fastapi import Depends, HTTPException, status | |
| from fastapi.security import OAuth2PasswordBearer | |
| from pydantic import BaseModel | |
| # Secret key to sign JWT tokens | |
| # In production, this should be a strong, randomly generated secret | |
| SECRET_KEY = os.getenv("JWT_SECRET_KEY", "your-super-secret-key-for-dev-only") | |
| ALGORITHM = "HS256" | |
| ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 1 week | |
| oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/auth/login") | |
| class TokenData(BaseModel): | |
| user_id: Optional[str] = None | |
| email: Optional[str] = None | |
| def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): | |
| to_encode = data.copy() | |
| if expires_delta: | |
| expire = datetime.now(timezone.utc) + expires_delta | |
| else: | |
| expire = datetime.now(timezone.utc) + 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 get_current_user_id(token: str = Depends(oauth2_scheme)): | |
| credentials_exception = HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Could not validate credentials", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| try: | |
| payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) | |
| user_id: str = payload.get("sub") | |
| if user_id is None: | |
| raise credentials_exception | |
| return user_id | |
| except jwt.PyJWTError: | |
| raise credentials_exception | |