Spaces:
Running
Running
Download auth.py from Shadowfilebot/Bot: direct link, hf CLI and curl.
- Browser
- Download file 11.1 kB
-
https://huggingface.co/spaces/Shadowfilebot/Bot/resolve/main/auth.py
- Command line
-
hf download hf://spaces/Shadowfilebot/Bot/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/Shadowfilebot/Bot/resolve/main/auth.py
11.1 kB
| """ | |
| Authentication & Authorization for PanelThTuanIT. | |
| Supports: | |
| 1. Standalone local authentication (self-hosted, no external worker needed). | |
| - Local user database in users.json. | |
| - Secure PBKDF2-HMAC-SHA256 password hashing. | |
| - Built-in HS256 JWT generation and validation with persistent secret key. | |
| 2. Optional fallback to external ADMIN_API_URL if configured. | |
| """ | |
| import base64 | |
| import hashlib | |
| import hmac | |
| import json | |
| import os | |
| import secrets | |
| import time | |
| import uuid | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| try: | |
| import httpx | |
| except ImportError: | |
| httpx = None | |
| try: | |
| from fastapi import Request, WebSocket, HTTPException | |
| except ImportError: | |
| Request = WebSocket = HTTPException = object | |
| from config import ADMIN_API_URL, USERS_FILE, SETTINGS_FILE, JWT_SECRET_FILE | |
| class AuthUser: | |
| """Authenticated user extracted from JWT.""" | |
| sub: str # user ID | |
| username: str | |
| role: str # "admin" or "user" | |
| # ── Secret Key Management ───────────────────── | |
| def _get_jwt_secret() -> bytes: | |
| """Retrieve or generate persistent JWT secret key.""" | |
| env_secret = os.environ.get("JWT_SECRET") | |
| if env_secret: | |
| return env_secret.encode("utf-8") | |
| if JWT_SECRET_FILE.exists(): | |
| return JWT_SECRET_FILE.read_text(encoding="utf-8").strip().encode("utf-8") | |
| # Generate and persist new secret | |
| new_secret = secrets.token_hex(32) | |
| try: | |
| JWT_SECRET_FILE.parent.mkdir(parents=True, exist_ok=True) | |
| JWT_SECRET_FILE.write_text(new_secret, encoding="utf-8") | |
| except Exception: | |
| pass | |
| return new_secret.encode("utf-8") | |
| _JWT_SECRET = _get_jwt_secret() | |
| # ── JWT Utility Functions (HS256) ───────────── | |
| def _b64url_encode(data: bytes) -> str: | |
| return base64.urlsafe_b64encode(data).decode("utf-8").rstrip("=") | |
| def _b64url_decode(s: str) -> bytes: | |
| padding = "=" * ((4 - len(s) % 4) % 4) | |
| return base64.urlsafe_b64decode(s + padding) | |
| def create_jwt(user: AuthUser, expires_in: int = 86400 * 30) -> str: | |
| """Generate a standard HS256 JWT valid for 30 days by default.""" | |
| header = {"alg": "HS256", "typ": "JWT"} | |
| payload = { | |
| "sub": user.sub, | |
| "username": user.username, | |
| "role": user.role, | |
| "exp": int(time.time()) + expires_in, | |
| "iat": int(time.time()), | |
| } | |
| hdr_b64 = _b64url_encode(json.dumps(header, separators=(",", ":")).encode("utf-8")) | |
| payload_b64 = _b64url_encode(json.dumps(payload, separators=(",", ":")).encode("utf-8")) | |
| signing_input = f"{hdr_b64}.{payload_b64}".encode("utf-8") | |
| sig = hmac.new(_JWT_SECRET, signing_input, hashlib.sha256).digest() | |
| sig_b64 = _b64url_encode(sig) | |
| return f"{hdr_b64}.{payload_b64}.{sig_b64}" | |
| def decode_jwt(token: str) -> dict | None: | |
| """Verify and decode a local HS256 JWT.""" | |
| try: | |
| parts = token.split(".") | |
| if len(parts) != 3: | |
| return None | |
| hdr_b64, payload_b64, sig_b64 = parts | |
| signing_input = f"{hdr_b64}.{payload_b64}".encode("utf-8") | |
| expected_sig = hmac.new(_JWT_SECRET, signing_input, hashlib.sha256).digest() | |
| actual_sig = _b64url_decode(sig_b64) | |
| if not hmac.compare_digest(expected_sig, actual_sig): | |
| return None | |
| payload = json.loads(_b64url_decode(payload_b64).decode("utf-8")) | |
| exp = payload.get("exp") | |
| if exp and exp < time.time(): | |
| return None | |
| return payload | |
| except Exception: | |
| return None | |
| # ── Password Hashing (PBKDF2-HMAC-SHA256) ────── | |
| def hash_password(password: str) -> str: | |
| """Hash password using salt + PBKDF2-HMAC-SHA256.""" | |
| salt = secrets.token_bytes(16) | |
| pw_hash = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 100_000) | |
| return f"{salt.hex()}${pw_hash.hex()}" | |
| def verify_password(password: str, stored_hash: str) -> bool: | |
| """Verify password against salt$hash string.""" | |
| try: | |
| salt_hex, hash_hex = stored_hash.split("$") | |
| salt = bytes.fromhex(salt_hex) | |
| expected_hash = bytes.fromhex(hash_hex) | |
| actual_hash = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 100_000) | |
| return hmac.compare_digest(expected_hash, actual_hash) | |
| except Exception: | |
| return False | |
| # ── Local User Database ─────────────────────── | |
| _users_cache: dict[str, dict] = {} | |
| _users_mtime: float = 0.0 | |
| _settings_cache: dict = {} | |
| _settings_mtime: float = 0.0 | |
| def load_users() -> dict[str, dict]: | |
| """Load users mapping from USERS_FILE with in-memory mtime cache.""" | |
| global _users_cache, _users_mtime | |
| if USERS_FILE.exists(): | |
| try: | |
| mtime = os.path.getmtime(USERS_FILE) | |
| if mtime != _users_mtime: | |
| _users_cache = json.loads(USERS_FILE.read_text(encoding="utf-8")) | |
| _users_mtime = mtime | |
| return _users_cache | |
| except Exception: | |
| return _users_cache | |
| return {} | |
| def save_users(users: dict): | |
| """Save users mapping atomically to USERS_FILE and update cache.""" | |
| global _users_cache, _users_mtime | |
| tmp = USERS_FILE.with_suffix(".tmp") | |
| tmp.parent.mkdir(parents=True, exist_ok=True) | |
| tmp.write_text(json.dumps(users, indent=2, default=str), encoding="utf-8") | |
| tmp.replace(USERS_FILE) | |
| _users_cache = users | |
| try: | |
| _users_mtime = os.path.getmtime(USERS_FILE) | |
| except Exception: | |
| pass | |
| def load_settings() -> dict: | |
| """Load global settings with in-memory mtime cache.""" | |
| global _settings_cache, _settings_mtime | |
| defaults = { | |
| "max_zones": 0, | |
| "motd": "", | |
| "disable_registration": False, | |
| "hf_token": "", | |
| "hf_repo": "", | |
| } | |
| if SETTINGS_FILE.exists(): | |
| try: | |
| mtime = os.path.getmtime(SETTINGS_FILE) | |
| if mtime != _settings_mtime or not _settings_cache: | |
| saved = json.loads(SETTINGS_FILE.read_text(encoding="utf-8")) | |
| defaults.update(saved) | |
| _settings_cache = defaults | |
| _settings_mtime = mtime | |
| return _settings_cache | |
| except Exception: | |
| return _settings_cache or defaults | |
| return defaults | |
| def save_settings(settings: dict): | |
| """Save settings atomically and update cache.""" | |
| global _settings_cache, _settings_mtime | |
| tmp = SETTINGS_FILE.with_suffix(".tmp") | |
| tmp.parent.mkdir(parents=True, exist_ok=True) | |
| tmp.write_text(json.dumps(settings, indent=2, default=str), encoding="utf-8") | |
| tmp.replace(SETTINGS_FILE) | |
| _settings_cache = settings | |
| try: | |
| _settings_mtime = os.path.getmtime(SETTINGS_FILE) | |
| except Exception: | |
| pass | |
| def create_user(username: str, email: str, password: str) -> AuthUser: | |
| """Create a new local user. First user is automatically assigned 'admin' role.""" | |
| uname = username.strip().lower() | |
| if not uname or len(uname) < 3: | |
| raise ValueError("Username phải có ít nhất 3 ký tự") | |
| if not password or len(password) < 6: | |
| raise ValueError("Mật khẩu phải có ít nhất 6 ký tự") | |
| users = load_users() | |
| if uname in users: | |
| raise ValueError(f"Username '{uname}' đã tồn tại") | |
| email_clean = email.strip().lower() | |
| for u in users.values(): | |
| if email_clean and u.get("email") == email_clean: | |
| raise ValueError(f"Email '{email}' đã được sử dụng") | |
| # First user created is admin | |
| role = "admin" if len(users) == 0 else "user" | |
| user_id = uuid.uuid4().hex | |
| users[uname] = { | |
| "id": user_id, | |
| "username": uname, | |
| "email": email_clean, | |
| "password_hash": hash_password(password), | |
| "role": role, | |
| "created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), | |
| } | |
| save_users(users) | |
| return AuthUser(sub=user_id, username=uname, role=role) | |
| def authenticate_user(username_or_email: str, password: str) -> AuthUser | None: | |
| """Authenticate user with username/email and password.""" | |
| target = username_or_email.strip().lower() | |
| users = load_users() | |
| found = None | |
| if target in users: | |
| found = users[target] | |
| else: | |
| for u in users.values(): | |
| if u.get("email") == target: | |
| found = u | |
| break | |
| if not found: | |
| return None | |
| if not verify_password(password, found.get("password_hash", "")): | |
| return None | |
| return AuthUser( | |
| sub=found.get("id", ""), | |
| username=found.get("username", ""), | |
| role=found.get("role", "user"), | |
| ) | |
| # ── Token Verification (Local first, fallback to Worker if configured) ── | |
| def verify_token(token: str) -> AuthUser | None: | |
| """Verify token locally; fall back to external worker if configured and local fails.""" | |
| if not token: | |
| return None | |
| # 1. Try local decode first | |
| payload = decode_jwt(token) | |
| if payload and "sub" in payload and "username" in payload: | |
| return AuthUser( | |
| sub=payload["sub"], | |
| username=payload["username"], | |
| role=payload.get("role", "user"), | |
| ) | |
| # 2. If ADMIN_API_URL is configured, try remote worker | |
| if ADMIN_API_URL: | |
| try: | |
| resp = httpx.get( | |
| f"{ADMIN_API_URL}/auth/me", | |
| headers={"Authorization": f"Bearer {token}"}, | |
| timeout=10, | |
| ) | |
| if resp.status_code == 200: | |
| user_data = resp.json().get("user", {}) | |
| if user_data.get("id") and user_data.get("username"): | |
| return AuthUser( | |
| sub=user_data.get("id"), | |
| username=user_data.get("username"), | |
| role=user_data.get("role", "user"), | |
| ) | |
| except Exception: | |
| pass | |
| return None | |
| # ── FastAPI Dependencies ────────────────────── | |
| def get_current_user(request: Request) -> AuthUser: | |
| """FastAPI dependency: extract and verify JWT from Authorization header, query param, or cookie.""" | |
| token = "" | |
| auth_header = request.headers.get("Authorization", "") | |
| if auth_header.startswith("Bearer "): | |
| token = auth_header[7:] | |
| elif "token" in request.query_params: | |
| token = request.query_params["token"] | |
| elif "panelthtuanit_token" in request.cookies: | |
| token = request.cookies["panelthtuanit_token"] | |
| if not token: | |
| raise HTTPException(401, "Chưa đăng nhập") | |
| user = verify_token(token) | |
| if not user: | |
| raise HTTPException(401, "Token không hợp lệ hoặc đã hết hạn") | |
| return user | |
| def get_ws_user(websocket: WebSocket) -> AuthUser | None: | |
| """Extract and verify JWT from WebSocket query parameter ?token=... or cookie.""" | |
| token = websocket.query_params.get("token", "") | |
| if not token: | |
| token = websocket.cookies.get("panelthtuanit_token", "") | |
| if not token: | |
| return None | |
| return verify_token(token) | |