Spaces:
Runtime error
Runtime error
Oviya commited on
Commit ·
707d3fc
1
Parent(s): 8e485f9
fix
Browse filesFiles changed (4)
123version https://git-lfs.github.com/spec/v1oid sha256:d6a4c4d53359423150f4f21fa4bb976d16f34587b0e8d2925da3a6cc0505f3fasize 4000123version https://git-lfs.github.com/spec/v1oid sha256:c467497f6e6f489256b14d0a00d70cdc3736a24e198d87e3b5abbef0a407cf99size 4000
1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950513 unmodified lines55565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413516 unmodified lines1521531541551561571586 unmodified lines1651661671681691701711721731741751761771781791801812 unmodified lines18418518618718818919016 unmodified lines20720820921021121221326 unmodified lines2402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443451 unmodified lineJSON file-based database moduleHandles:- JSON file storage for users, refresh tokens, and blacklisted tokens- User management and authentication- Token blacklist management- Refresh token storage- Thread-safe JSON operations with file lockingHugging Face notes:- Use AUTH_DB_DIR=/data/auth_db to store runtime JSON files.- Optionally set AUTH_SEED_DIR=/home/user/app/data (repo data folder) to seed initial users.json."""import osimport jsonimport threadingfrom typing import Optional, Dict, Any, List, Tuplefrom pathlib import Pathfrom datetime import datetimeimport tempfileimport shutil# =========================================================# STORAGE LOCATION (LOCAL DEFAULT + HUGGING FACE OVERRIDE)# =========================================================# Local default: repo_root/data (auth/../data)DEFAULT_DB_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "data"))# Runtime DB directory (HF: /data/auth_db)DB_DIR = os.path.abspath(os.getenv("AUTH_DB_DIR", DEFAULT_DB_DIR))# Seed directory (where you keep committed JSONs in repo)# HF typical repo path is /home/user/appDEFAULT_SEED_DIR = os.path.abspath(os.getenv("AUTH_SEED_DIR", DEFAULT_DB_DIR))USERS_FILE = os.path.join(DB_DIR, "users.json")BLACKLISTED_TOKENS_FILE = os.path.join(DB_DIR, "blacklisted_tokens.json")REFRESH_TOKENS_FILE = os.path.join(DB_DIR, "refresh_tokens.json")SEED_USERS_FILE = os.path.join(DEFAULT_SEED_DIR, "users.json")SEED_BLACKLISTED_FILE = os.path.join(DEFAULT_SEED_DIR, "blacklisted_tokens.json")SEED_REFRESH_FILE = os.path.join(DEFAULT_SEED_DIR, "refresh_tokens.json")# Thread-safe file locks_file_locks = {"users": threading.Lock(),"blacklisted_tokens": threading.Lock(),3 unmodified lines_db_init_done = False_db_init_lock = threading.Lock()# -----------------------------# Helpers# -----------------------------def ensure_data_directory() -> None:Path(DB_DIR).mkdir(parents=True, exist_ok=True)def load_json_file(filepath: str) -> Dict[str, Any]:"""Load JSON file. Returns empty dict if file doesn't exist or is invalid."""if not os.path.exists(filepath):return {}try:with open(filepath, "r", encoding="utf-8") as f:data = json.load(f)return data if isinstance(data, dict) else {}except Exception:return {}def _atomic_write_json(filepath: str, data: Dict[str, Any]) -> None:"""Atomic JSON write:write to temp file in same directory, then replace."""directory = os.path.dirname(filepath)Path(directory).mkdir(parents=True, exist_ok=True)fd, tmp_path = tempfile.mkstemp(prefix=".tmp_", dir=directory)try:with os.fdopen(fd, "w", encoding="utf-8") as f:json.dump(data, f, indent=2, ensure_ascii=False)os.replace(tmp_path, filepath) # atomic on POSIXfinally:try:if os.path.exists(tmp_path):os.remove(tmp_path)except Exception:passdef save_json_file(filepath: str, data: Dict[str, Any]) -> None:_atomic_write_json(filepath, data)def _is_empty_or_missing(filepath: str) -> bool:if not os.path.exists(filepath):return Truetry:d = load_json_file(filepath)return len(d) == 0except Exception:return Truedef _copy_seed_file_if_needed(seed_path: str, target_path: str, *, only_if_missing_or_empty: bool = True) -> bool:"""Copy seed json into runtime DB.Returns True if copied."""if not os.path.exists(seed_path):return Falseif only_if_missing_or_empty and not _is_empty_or_missing(target_path):return Falseensure_data_directory()Path(os.path.dirname(target_path)).mkdir(parents=True, exist_ok=True)shutil.copy2(seed_path, target_path)return True# -----------------------------# Data Access Classes# -----------------------------class JSONUsers:@staticmethoddef load_all() -> Dict[str, Any]:16 unmodified linesreturn Falseusers[username_lower] = {"id": (max([u.get("id", 0) for u in users.values()], default=0) + 1),"username": username_lower,"password_hash": password_hash,"role": role,6 unmodified lines@staticmethoddef get_all_users() -> List[Dict[str, Any]]:users = JSONUsers.load_all()return [{"id": u["id"], "username": u["username"], "role": u["role"]} for u in users.values()]@staticmethoddef promote_to_admin(username: str) -> bool:username_lower = username.lower()with _file_locks["users"]:users = load_json_file(USERS_FILE)if username_lower not in users:return Falseusers[username_lower]["role"] = "admin"save_json_file(USERS_FILE, users)return True2 unmodified linesdef user_count() -> int:return len(JSONUsers.load_all())class JSONBlacklistedTokens:@staticmethoddef load_all() -> Dict[str, Any]:16 unmodified linessave_json_file(BLACKLISTED_TOKENS_FILE, tokens)return Trueclass JSONRefreshTokens:@staticmethoddef load_all() -> Dict[str, Any]:26 unmodified linesusername_lower = username.lower()with _file_locks["refresh_tokens"]:tokens = load_json_file(REFRESH_TOKENS_FILE)keys = [k for k, v in tokens.items() if v.get("username") == username_lower]for k in keys:tokens.pop(k, None)save_json_file(REFRESH_TOKENS_FILE, tokens)return True# -----------------------------# Init / Seed# -----------------------------def init_db_files() -> None:"""Create runtime json files if missing.Also seeds users.json from repo data folder into runtime DB if runtime is empty."""ensure_data_directory()# Seed users first if runtime missing/empty_copy_seed_file_if_needed(SEED_USERS_FILE, USERS_FILE, only_if_missing_or_empty=True)# For tokens: usually you want them empty on first boot. If you want to seed them, set SEED_TOKENS=1seed_tokens = os.getenv("SEED_TOKENS", "0") == "1"if seed_tokens:_copy_seed_file_if_needed(SEED_BLACKLISTED_FILE, BLACKLISTED_TOKENS_FILE, only_if_missing_or_empty=True)_copy_seed_file_if_needed(SEED_REFRESH_FILE, REFRESH_TOKENS_FILE, only_if_missing_or_empty=True)# Create missing files (keep existing)if not os.path.exists(USERS_FILE):save_json_file(USERS_FILE, {})if not os.path.exists(BLACKLISTED_TOKENS_FILE):save_json_file(BLACKLISTED_TOKENS_FILE, {})if not os.path.exists(REFRESH_TOKENS_FILE):save_json_file(REFRESH_TOKENS_FILE, {})def ensure_database_initialized() -> bool:"""Ensure JSON database is initialized (thread-safe).Controlled by RUN_INIT_DB (default 1)."""global _db_init_doneshould_init = os.getenv("RUN_INIT_DB", "1") == "1"if not should_init:return Falseif _db_init_done:return Truewith _db_init_lock:if _db_init_done:return Trueinit_db_files()_db_init_done = Truereturn Truedef get_database_info() -> Dict[str, Any]:"""Return non-sensitive diagnostics."""def _file_info(path: str) -> Dict[str, Any]:if not os.path.exists(path):return {"exists": False}return {"exists": True,"path": path,"size_bytes": os.path.getsize(path),"count": len(load_json_file(path)),}info = {"database_type": "JSON","db_dir": DB_DIR,"seed_dir": DEFAULT_SEED_DIR,"files": {"users": _file_info(USERS_FILE),"blacklisted_tokens": _file_info(BLACKLISTED_TOKENS_FILE),"refresh_tokens": _file_info(REFRESH_TOKENS_FILE),},}return infodef test_database_connection() -> Tuple[bool, str]:"""Test read/write access to DB_DIR."""try:ensure_data_directory()# Read users_ = JSONUsers.load_all()# Write temp filetest_file = os.path.join(DB_DIR, ".test_write")save_json_file(test_file, {"ok": True})os.remove(test_file)return True, "JSON database connection successful"except Exception as e:return False, f"JSON database connection failed: {e}"1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152533 unmodified lines5758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216 unmodified lines1791801811821831841856 unmodified lines1921931941951961971981992002012022032042052062072082092 unmodified lines21221321421521621716 unmodified lines23423523623723823926 unmodified lines2662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743751 unmodified lineJSON file-based database moduleHandles:- JSON file storage for users, tokens, and blacklisted tokens- User management and authentication- Token blacklist management- Refresh token storage- Thread-safe JSON operations with file locking- Hugging Face friendly seeding + writable fallback"""import osimport jsonimport threadingimport shutilfrom typing import Optional, Dict, Any, List, Tuplefrom pathlib import Pathfrom datetime import datetime# =========================================================# PATHS# =========================================================def _project_root() -> Path:# auth/json_database.py -> auth (parent) -> project root (parent)return Path(__file__).resolve().parent.parentDEFAULT_DB_DIR = str((_project_root() / "data").resolve()) # <project>/dataDB_DIR_ENV = os.getenv("AUTH_DB_DIR", DEFAULT_DB_DIR)# Seed dir (where your repo JSON files exist)SEED_DIR_ENV = os.getenv("AUTH_SEED_DIR", DEFAULT_DB_DIR)# Seeding controlsSEED_ON_START = os.getenv("AUTH_SEED_ON_START", "1") == "1"SEED_IF_EMPTY = os.getenv("AUTH_SEED_IF_EMPTY", "1") == "1"# Initialize DB files on startupRUN_INIT_DB = os.getenv("RUN_INIT_DB", "1") == "1"# Resolve target db dirDB_DIR = str(Path(DB_DIR_ENV).expanduser().resolve())SEED_DIR = str(Path(SEED_DIR_ENV).expanduser().resolve())USERS_FILE = os.path.join(DB_DIR, "users.json")BLACKLISTED_TOKENS_FILE = os.path.join(DB_DIR, "blacklisted_tokens.json")REFRESH_TOKENS_FILE = os.path.join(DB_DIR, "refresh_tokens.json")# Thread locks_file_locks = {"users": threading.Lock(),"blacklisted_tokens": threading.Lock(),3 unmodified lines_db_init_done = False_db_init_lock = threading.Lock()# =========================================================# HELPERS# =========================================================def _log(msg: str):# Simple stdout logging (Hugging Face logs show this)print(msg, flush=True)def ensure_data_directory():"""Create DB directory. If not writable, fallback to /tmp/auth_db."""global DB_DIR, USERS_FILE, BLACKLISTED_TOKENS_FILE, REFRESH_TOKENS_FILEtry:Path(DB_DIR).mkdir(parents=True, exist_ok=True)# write testtest_file = os.path.join(DB_DIR, ".write_test")with open(test_file, "w", encoding="utf-8") as f:f.write("ok")os.remove(test_file)returnexcept Exception as e:_log(f"[AUTH][WARN] DB_DIR not writable: {DB_DIR}. Error: {e}")fallback = "/tmp/auth_db"_log(f"[AUTH][WARN] Falling back to: {fallback}")DB_DIR = fallbackPath(DB_DIR).mkdir(parents=True, exist_ok=True)USERS_FILE = os.path.join(DB_DIR, "users.json")BLACKLISTED_TOKENS_FILE = os.path.join(DB_DIR, "blacklisted_tokens.json")REFRESH_TOKENS_FILE = os.path.join(DB_DIR, "refresh_tokens.json")def load_json_file(filepath: str) -> Dict[str, Any]:"""Load JSON file with error handling.Returns {} if file does not exist."""if not os.path.exists(filepath):return {}try:with open(filepath, "r", encoding="utf-8") as f:return json.load(f)except (json.JSONDecodeError, IOError) as e:_log(f"[AUTH][ERROR] Error loading {filepath}: {e}")return {}def save_json_file(filepath: str, data: Dict[str, Any]):"""Atomic save JSON file (prevents partial writes)."""parent = os.path.dirname(filepath)os.makedirs(parent, exist_ok=True)tmp_path = filepath + ".tmp"try:with open(tmp_path, "w", encoding="utf-8") as f:json.dump(data, f, indent=2, ensure_ascii=False)os.replace(tmp_path, filepath)except Exception as e:_log(f"[AUTH][ERROR] Error saving {filepath}: {e}")# cleanup temp if existstry:if os.path.exists(tmp_path):os.remove(tmp_path)except Exception:passraisedef _file_is_empty_json(filepath: str) -> bool:if not os.path.exists(filepath):return Truetry:data = load_json_file(filepath)return not bool(data)except Exception:return Truedef _seed_file_if_needed(target_path: str, seed_path: str):"""Copy seed file -> target if:- target missing, OR- target exists but empty AND SEED_IF_EMPTY=1"""if not SEED_ON_START:returnseed_exists = os.path.exists(seed_path)target_exists = os.path.exists(target_path)if (not target_exists and seed_exists) or (target_exists and SEED_IF_EMPTY and seed_exists and _file_is_empty_json(target_path)):os.makedirs(os.path.dirname(target_path), exist_ok=True)shutil.copy2(seed_path, target_path)_log(f"[AUTH][SEED] Copied seed: {seed_path} -> {target_path}")# =========================================================# STORAGE CLASSES# =========================================================class JSONUsers:@staticmethoddef load_all() -> Dict[str, Any]:16 unmodified linesreturn Falseusers[username_lower] = {"id": len(users) + 1,"username": username_lower,"password_hash": password_hash,"role": role,6 unmodified lines@staticmethoddef get_all_users() -> List[Dict[str, Any]]:users = JSONUsers.load_all()return [{"id": u.get("id"), "username": u.get("username"), "role": u.get("role")}for u in users.values()]@staticmethoddef promote_to_admin(username: str) -> bool:username_lower = username.lower()with _file_locks["users"]:users = load_json_file(USERS_FILE)if username_lower not in users:return Falseusers[username_lower]["role"] = "admin"save_json_file(USERS_FILE, users)return True2 unmodified linesdef user_count() -> int:return len(JSONUsers.load_all())class JSONBlacklistedTokens:@staticmethoddef load_all() -> Dict[str, Any]:16 unmodified linessave_json_file(BLACKLISTED_TOKENS_FILE, tokens)return Trueclass JSONRefreshTokens:@staticmethoddef load_all() -> Dict[str, Any]:26 unmodified linesusername_lower = username.lower()with _file_locks["refresh_tokens"]:tokens = load_json_file(REFRESH_TOKENS_FILE)to_remove = [k for k, v in tokens.items() if v.get("username") == username_lower]for k in to_remove:del tokens[k]save_json_file(REFRESH_TOKENS_FILE, tokens)return True# =========================================================# INIT / DIAG# =========================================================def init_db():"""Initialize JSON database files.If AUTH_SEED_ON_START=1, seed from AUTH_SEED_DIR when missing or empty."""ensure_data_directory()# seed pathsseed_users = os.path.join(SEED_DIR, "users.json")seed_blacklist = os.path.join(SEED_DIR, "blacklisted_tokens.json")seed_refresh = os.path.join(SEED_DIR, "refresh_tokens.json")# Seed (if needed)_seed_file_if_needed(USERS_FILE, seed_users)_seed_file_if_needed(BLACKLISTED_TOKENS_FILE, seed_blacklist)_seed_file_if_needed(REFRESH_TOKENS_FILE, seed_refresh)# Ensure files exist (create empty if still missing)if not os.path.exists(USERS_FILE):save_json_file(USERS_FILE, {})_log(f"[AUTH][INIT] Created empty {USERS_FILE}")if not os.path.exists(BLACKLISTED_TOKENS_FILE):save_json_file(BLACKLISTED_TOKENS_FILE, {})_log(f"[AUTH][INIT] Created empty {BLACKLISTED_TOKENS_FILE}")if not os.path.exists(REFRESH_TOKENS_FILE):save_json_file(REFRESH_TOKENS_FILE, {})_log(f"[AUTH][INIT] Created empty {REFRESH_TOKENS_FILE}")# Startup log (very useful in HF logs)try:users_count = len(load_json_file(USERS_FILE))_log(f"[AUTH][READY] DB_DIR={DB_DIR} | users={users_count}")except Exception as e:_log(f"[AUTH][WARN] Could not read users count: {e}")def ensure_database_initialized() -> bool:"""Ensure JSON DB is initialized once (thread-safe).Controlled by RUN_INIT_DB."""global _db_init_doneif not RUN_INIT_DB:return Falseif not _db_init_done:with _db_init_lock:if not _db_init_done:init_db()_db_init_done = Truereturn Truedef get_database_info() -> Dict[str, Any]:info = {"database_type": "JSON","storage_location": DB_DIR,"seed_location": SEED_DIR,"files": {},}def _file_info(path: str, label: str):if not os.path.exists(path):info["files"][label] = {"exists": False}returndata = load_json_file(path)info["files"][label] = {"exists": True,"path": path,"size_bytes": os.path.getsize(path),"count": len(data) if isinstance(data, dict) else 0,}try:_file_info(USERS_FILE, "users")_file_info(BLACKLISTED_TOKENS_FILE, "blacklisted_tokens")_file_info(REFRESH_TOKENS_FILE, "refresh_tokens")info["connection_status"] = "ok"except Exception as e:info["connection_status"] = "error"info["error"] = str(e)return infodef test_database_connection() -> Tuple[bool, str]:try:ensure_data_directory()_ = JSONUsers.load_all()test_file = os.path.join(DB_DIR, ".test")save_json_file(test_file, {"test": "ok"})os.remove(test_file)return True, "JSON database connection successful"except Exception as e:return False, f"JSON database connection failed: {str(e)}"
57 unmodified lines585960616257 unmodified lines"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNzY5NTgwNTIwfQ.xaovVHywd_uCUPkkEN0C9juXhZuBzEwvnotk4LgMTa8": {"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNzY5NTgwNTIwfQ.xaovVHywd_uCUPkkEN0C9juXhZuBzEwvnotk4LgMTa8","created_at": "2026-01-28T11:23:48.110513"}}57 unmodified lines58596061626364656657 unmodified lines"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNzY5NTgwNTIwfQ.xaovVHywd_uCUPkkEN0C9juXhZuBzEwvnotk4LgMTa8": {"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNzY5NTgwNTIwfQ.xaovVHywd_uCUPkkEN0C9juXhZuBzEwvnotk4LgMTa8","created_at": "2026-01-28T11:23:48.110513"},"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNzY5NTgyMDQ3fQ.SjH67H5hTvAr0A2X9UeFy9BTzkMoeRAv2AQideORr2w": {"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNzY5NTgyMDQ3fQ.SjH67H5hTvAr0A2X9UeFy9BTzkMoeRAv2AQideORr2w","created_at": "2026-01-28T11:49:25.157795"}}
1{}1234567{"admin_1": {"username": "admin","token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNzcwMTg1OTgwfQ.meq8kajfaFjc4ne6xfR-Pf1WzUvxybUvyseI16N7ztM","created_at": "2026-01-28T11:49:40.529887"}}
assets/chroma_db/88b01f33-9f9f-4ac5-b7a5-c6afecf476d2/length.bin+1-1
auth/json_database.py+156-126
data/blacklisted_tokens.json+4
data/refresh_tokens.json+7-1