Spaces:
Runtime error
Runtime error
Download backend/core/auth.py from Amitkasar/ai-api-testing: direct link, hf CLI and curl.
- Browser
- Download file 1.52 kB
-
https://huggingface.co/spaces/Amitkasar/ai-api-testing/resolve/main/backend/core/auth.py
- Command line
-
hf download hf://spaces/Amitkasar/ai-api-testing/backend/core/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/Amitkasar/ai-api-testing/resolve/main/backend/core/auth.py
1.52 kB
| import hashlib | |
| import os | |
| from datetime import datetime, timedelta, timezone | |
| import jwt | |
| from fastapi import Depends, HTTPException, status | |
| from fastapi.security import OAuth2PasswordBearer | |
| from backend.core.config import settings | |
| oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login") | |
| def hash_password(password: str) -> str: | |
| salt = os.urandom(16) | |
| dk = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 260_000) | |
| return salt.hex() + "$" + dk.hex() | |
| def verify_password(password: str, hashed: str) -> bool: | |
| try: | |
| salt_hex, dk_hex = hashed.split("$", 1) | |
| salt = bytes.fromhex(salt_hex) | |
| dk = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 260_000) | |
| return dk.hex() == dk_hex | |
| except Exception: | |
| return False | |
| def create_access_token(username: str) -> str: | |
| expire = datetime.now(timezone.utc) + timedelta(hours=settings.JWT_EXPIRE_HOURS) | |
| return jwt.encode({"sub": username, "exp": expire}, settings.JWT_SECRET, algorithm="HS256") | |
| def verify_token(token: str = Depends(oauth2_scheme)) -> str: | |
| try: | |
| payload = jwt.decode(token, settings.JWT_SECRET, algorithms=["HS256"]) | |
| username: str = payload.get("sub") | |
| if not username: | |
| raise ValueError("Missing subject") | |
| return username | |
| except Exception: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid or expired token", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |