Spaces:
Building
Building
import os | |
from datetime import datetime, timedelta | |
import jwt | |
# ===================== JWT Config ===================== | |
def get_jwt_config(): | |
"""Get JWT configuration based on environment""" | |
# Check if we're in HuggingFace Space | |
if os.getenv("SPACE_ID"): | |
# Cloud mode - use secrets from environment | |
jwt_secret = os.getenv("JWT_SECRET") | |
if not jwt_secret: | |
log("⚠️ WARNING: JWT_SECRET not found in environment, using fallback") | |
jwt_secret = "flare-admin-secret-key-change-in-production" # Fallback | |
else: | |
# On-premise mode - use .env file | |
from dotenv import load_dotenv | |
load_dotenv() | |
jwt_secret = os.getenv("JWT_SECRET", "flare-admin-secret-key-change-in-production") | |
return { | |
"secret": jwt_secret, | |
"algorithm": os.getenv("JWT_ALGORITHM", "HS256"), | |
"expiration_hours": int(os.getenv("JWT_EXPIRATION_HOURS", "24")) | |
} | |
# ===================== Auth Helpers ===================== | |
def create_token(username: str) -> str: | |
"""Create JWT token for user""" | |
config = get_jwt_config() | |
expiry = datetime.now(timezone.utc) + timedelta(hours=config["expiration_hours"]) | |
payload = { | |
"sub": username, | |
"exp": expiry, | |
"iat": datetime.now(timezone.utc) | |
} | |
return jwt.encode(payload, config["secret"], algorithm=config["algorithm"]) | |
def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)) -> str: | |
"""Verify JWT token and return username""" | |
token = credentials.credentials | |
config = get_jwt_config() | |
try: | |
payload = jwt.decode(token, config["secret"], algorithms=[config["algorithm"]]) | |
return payload["sub"] | |
except jwt.ExpiredSignatureError: | |
raise HTTPException(status_code=401, detail="Token expired") | |
except jwt.InvalidTokenError: | |
raise HTTPException(status_code=401, detail="Invalid token") |