Download modules/auth.py from deanpowers/blind-monkeys: direct link, hf CLI and curl.
- Browser
- Download file 8.93 kB
-
https://huggingface.co/deanpowers/blind-monkeys/resolve/main/modules/auth.py
- Command line
-
hf download hf://deanpowers/blind-monkeys/modules/auth.py
-
curl -L -o auth.py https://huggingface.co/deanpowers/blind-monkeys/resolve/main/modules/auth.py
8.93 kB
| """ | |
| Auth module — pbkdf2 password hashing, manually-provisioned users, | |
| session-based login, per-user recovery codes. | |
| Storage: reads USERS_JSON env var first (Cloud Run), falls back to users.json (local). | |
| """ | |
| import os | |
| import json | |
| import time | |
| import hmac | |
| import base64 | |
| import hashlib | |
| import secrets | |
| from functools import wraps | |
| from flask import session, jsonify, redirect, url_for, request | |
| # ---------- Hashing (pbkdf2, stdlib) ---------- | |
| PBKDF2_ITERATIONS = 200_000 | |
| def hash_password(password, salt=None): | |
| """Hash a password with pbkdf2_hmac + random salt. Returns base64 string.""" | |
| salt = salt or os.urandom(16) | |
| dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, PBKDF2_ITERATIONS) | |
| return base64.b64encode(salt + dk).decode("ascii") | |
| def check_password(password, stored): | |
| """Verify password against stored pbkdf2 hash.""" | |
| try: | |
| raw = base64.b64decode(stored.encode("ascii")) | |
| salt, expected = raw[:16], raw[16:] | |
| dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, PBKDF2_ITERATIONS) | |
| return hmac.compare_digest(dk, expected) | |
| except Exception: | |
| return False | |
| # ---------- Storage ---------- | |
| _DATA_DIR = os.environ.get("DATA_DIR", ".") | |
| LOCAL_USERS_FILE = os.environ.get("USERS_FILE", "users.json") | |
| from modules.storage import load_json, save_json | |
| def _load_users_raw(): | |
| data = load_json(LOCAL_USERS_FILE, default=None) | |
| if data is None: | |
| return [] | |
| return data.get("users", []) | |
| def _save_users_raw(users): | |
| return save_json(LOCAL_USERS_FILE, {"users": users}) | |
| def get_user_alerts(email): | |
| """Return user's alert preferences with defaults for missing fields.""" | |
| u = get_user(email) | |
| if not u: | |
| return None | |
| return { | |
| "alert_btc_1pct": bool(u.get("alert_btc_1pct", True)), | |
| "alert_eth_1pct": bool(u.get("alert_eth_1pct", True)), | |
| "high_score_alerts": bool(u.get("high_score_alerts", True)), | |
| } | |
| def update_user_alerts(email, prefs): | |
| """Update alert preferences for a user. Returns True on success.""" | |
| email = (email or "").strip().lower() | |
| users = _load_users_raw() | |
| for u in users: | |
| if u.get("email", "").lower() == email: | |
| if "alert_btc_1pct" in prefs: | |
| u["alert_btc_1pct"] = bool(prefs["alert_btc_1pct"]) | |
| if "alert_eth_1pct" in prefs: | |
| u["alert_eth_1pct"] = bool(prefs["alert_eth_1pct"]) | |
| if "high_score_alerts" in prefs: | |
| u["high_score_alerts"] = bool(prefs["high_score_alerts"]) | |
| return _save_users_raw(users) | |
| return False | |
| def get_dismissed_alerts(email): | |
| u = get_user(email) | |
| if not u: | |
| return {} | |
| d = u.get("dismissed_alerts") or {} | |
| return d if isinstance(d, dict) else {} | |
| def add_dismissed_alert(email, symbol): | |
| import time as _t | |
| email = (email or "").strip().lower() | |
| symbol = (symbol or "").strip().upper() | |
| if not email or not symbol: | |
| return False | |
| users = _load_users_raw() | |
| for u in users: | |
| if u.get("email", "").lower() == email: | |
| d = u.get("dismissed_alerts") or {} | |
| if not isinstance(d, dict): | |
| d = {} | |
| d[symbol] = int(_t.time()) | |
| u["dismissed_alerts"] = d | |
| return _save_users_raw(users) | |
| return False | |
| # ---------- Lookups ---------- | |
| def get_user(email): | |
| email = (email or "").strip().lower() | |
| for u in _load_users_raw(): | |
| if u.get("email", "").lower() == email: | |
| return u | |
| return None | |
| def verify_login(email, password): | |
| """Returns (user, error_code). error_code is None on success.""" | |
| user = get_user(email) | |
| if not user: | |
| return None, "invalid" | |
| if not check_password(password or "", user.get("password_hash", "")): | |
| return None, "invalid" | |
| status = user.get("status", "active") | |
| if status == "pending": | |
| return None, "pending" | |
| if status == "rejected": | |
| return None, "rejected" | |
| if status != "active": | |
| return None, "invalid" | |
| return user, None | |
| def verify_recovery(email, code): | |
| user = get_user(email) | |
| if not user: | |
| return None | |
| stored = user.get("recovery_code", "") | |
| if not stored: | |
| return None | |
| if not hmac.compare_digest(str(stored), str(code or "")): | |
| return None | |
| return user | |
| def update_password(email, new_password): | |
| email = (email or "").strip().lower() | |
| users = _load_users_raw() | |
| for u in users: | |
| if u.get("email", "").lower() == email: | |
| u["password_hash"] = hash_password(new_password) | |
| u["password_updated_at"] = int(time.time()) | |
| return _save_users_raw(users) | |
| return False | |
| # ---------- User management (Phase 11) ---------- | |
| def create_user(email, password, first_name="", last_name="", role="user", status="pending", reg_message=""): | |
| """Create a new user. Returns the user dict, or None if email exists.""" | |
| email = (email or "").strip().lower() | |
| if not email: | |
| return None | |
| if get_user(email): | |
| return None | |
| users = _load_users_raw() | |
| recovery = secrets.token_hex(16) | |
| user = { | |
| "email": email, | |
| "password_hash": hash_password(password), | |
| "recovery_code": recovery, | |
| "role": role, | |
| "status": status, | |
| "alert_btc_1pct": True, | |
| "alert_eth_1pct": True, | |
| "first_name": first_name, | |
| "last_name": last_name, | |
| "reg_message": (reg_message or "").strip()[:80], | |
| "created_at": int(time.time()), | |
| "approved_at": int(time.time()) if status == "active" else None, | |
| "approved_by": None, | |
| "approved_note": None, | |
| "rejected_note": None, | |
| } | |
| users.append(user) | |
| _save_users_raw(users) | |
| return user | |
| def update_user_status(email, status, by_email=None, note=""): | |
| """Set status for a user. Statuses: pending / active / rejected. Stores admin note.""" | |
| email = (email or "").strip().lower() | |
| note = (note or "").strip()[:80] | |
| users = _load_users_raw() | |
| for u in users: | |
| if u.get("email", "").lower() == email: | |
| u["status"] = status | |
| u["reviewed_at"] = int(time.time()) | |
| u["reviewed_by"] = by_email | |
| if status == "active": | |
| u["approved_at"] = int(time.time()) | |
| u["approved_by"] = by_email | |
| u["approved_note"] = note or None | |
| elif status == "rejected": | |
| u["rejected_note"] = note or None | |
| _save_users_raw(users) | |
| return True | |
| return False | |
| def list_all_users(): | |
| """Return all users, sorted: pending first, then active, then rejected.""" | |
| users = _load_users_raw() | |
| order = {"pending": 0, "active": 1, "rejected": 2} | |
| users = list(users) | |
| users.sort(key=lambda u: (order.get(u.get("status", "active"), 99), | |
| -u.get("created_at", 0))) | |
| return users | |
| def delete_user(email): | |
| """Remove a user by email. Returns True if removed.""" | |
| email = (email or "").strip().lower() | |
| users = _load_users_raw() | |
| before = len(users) | |
| users = [u for u in users if u.get("email", "").lower() != email] | |
| if len(users) < before: | |
| _save_users_raw(users) | |
| return True | |
| return False | |
| # ---------- Session ---------- | |
| SESSION_TTL = 60 * 60 * 12 # 12 hours | |
| def login_user(user): | |
| session.permanent = True | |
| session["user_email"] = user["email"] | |
| session["user_role"] = user.get("role", "user") | |
| session["login_at"] = int(time.time()) | |
| def logout_user(): | |
| session.clear() | |
| def current_user(): | |
| email = session.get("user_email") | |
| login_at = session.get("login_at", 0) | |
| if not email: | |
| return None | |
| if time.time() - login_at > SESSION_TTL: | |
| session.clear() | |
| return None | |
| return get_user(email) | |
| def is_admin(): | |
| u = current_user() | |
| return bool(u and u.get("role") == "admin") | |
| def public_mode(): | |
| """True if PUBLIC_MODE env var is 'true', OR no one is logged in.""" | |
| if os.environ.get("PUBLIC_MODE", "false").lower() == "true": | |
| return True | |
| return current_user() is None | |
| # ---------- Decorators ---------- | |
| def require_login(f): | |
| def wrapper(*args, **kwargs): | |
| if not current_user(): | |
| if request.path.startswith("/api/"): | |
| return jsonify({"error": "login required"}), 401 | |
| return redirect(url_for("login_page", next=request.path)) | |
| return f(*args, **kwargs) | |
| return wrapper | |
| def require_admin(f): | |
| def wrapper(*args, **kwargs): | |
| if not current_user(): | |
| if request.path.startswith("/api/"): | |
| return jsonify({"error": "login required"}), 401 | |
| return redirect(url_for("login_page", next=request.path)) | |
| if not is_admin(): | |
| return jsonify({"error": "admin only"}), 403 | |
| return f(*args, **kwargs) | |
| return wrapper | |