import time import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from urllib.parse import quote from flask import request, session from core.config import auth as _auth_cfg SCOPE_ADMIN = "kittyrec.admin" SCOPE_MOD = "kittyrec.mod" SCOPE_EMERGENCY = "kittyrec.emergency" AUTH_LOGIN_URL = _auth_cfg["login_url"] AUTH_ME_URL = AUTH_LOGIN_URL + "/api/account/me" AUTH_REFRESH_URL = AUTH_LOGIN_URL + "/api/account/refresh/session" EMERGENCY_LOGIN_URL = "/admin/emergency_login" EMERGENCY_PASSWORD = _auth_cfg["emergency_password"] _EMERGENCY_SESSION_TTL = 8 * 3600 _CACHE_TTL = 86400 FORCE_EMERGENCY_MODE = False _auth_down_until = 0.0 _AUTH_DOWN_TTL = 45 def _mark_auth_down(): global _auth_down_until _auth_down_until = time.time() + _AUTH_DOWN_TTL def is_auth_server_down() -> bool: return time.time() < _auth_down_until def probe_auth_server() -> bool: if is_auth_server_down(): return True try: resp = requests.get(AUTH_ME_URL, timeout=(2, 4)) if resp.status_code >= 500: print(f"[Admin Auth] Probe: auth server returned {resp.status_code} — marking down") _mark_auth_down() return True return False except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e: print(f"[Admin Auth] Probe: unreachable ({e}) — marking down") _mark_auth_down() return True except Exception: return False def _get_me(sess, token): return sess.get(AUTH_ME_URL, cookies={"Authorization": token}, timeout=(2, 6)) def _authenticate_token(token): if is_auth_server_down(): return None, None sess = requests.Session() retry = Retry(total=1, backoff_factor=0, status_forcelist=[502, 503, 504], allowed_methods=["GET"]) sess.mount("https://", HTTPAdapter(max_retries=retry)) try: resp = _get_me(sess, token) if resp.status_code in (401, 403): print("[Admin Auth] Token expired, attempting refresh...") refresh = sess.get(AUTH_REFRESH_URL, cookies={"Authorization": token}, timeout=(2, 6)) if refresh.status_code != 200: print("[Admin Auth] Refresh failed") return None, [] new_token = refresh.cookies.get("Authorization", token) resp = _get_me(sess, new_token) if resp.status_code == 200: try: account = resp.json() except Exception: _mark_auth_down() return None, None scopes = account.get("scopes", []) session["admin_cache"] = { "account": account, "scopes": scopes, "token_hint": token[-16:], "cached_at": time.time(), } return account, scopes elif resp.status_code >= 500: print(f"[Admin Auth] Auth server returned {resp.status_code} — treating as down") _mark_auth_down() return None, None except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e: print(f"[Admin Auth] Auth server unreachable: {e}") _mark_auth_down() return None, None except Exception as e: print(f"[Admin Auth] {e}") finally: sess.close() return None, [] def _get_cached(token): cache = session.get("admin_cache") if not cache: return None, None if time.time() - cache.get("cached_at", 0) > _CACHE_TTL: session.pop("admin_cache", None) return None, None if cache.get("token_hint") != token[-16:]: session.pop("admin_cache", None) return None, None return cache["account"], cache["scopes"] def get_admin_account(): if FORCE_EMERGENCY_MODE: return {"username": "Emergency", "scopes": [SCOPE_ADMIN]}, [SCOPE_ADMIN] emerg = session.get("emergency_admin") if emerg and emerg.get("expires", 0) > time.time(): return {"username": "Emergency", "scopes": [SCOPE_ADMIN]}, [SCOPE_ADMIN] token = request.cookies.get("Authorization") or request.headers.get("Authorization") if not token: if is_auth_server_down(): return None, None return None, [] account, scopes = _get_cached(token) if account is not None: return account, scopes return _authenticate_token(token) def has_any_admin_scope(scopes): if scopes is None: return False return SCOPE_ADMIN in scopes or SCOPE_MOD in scopes def make_login_redirect(target_url=None): url = target_url or request.url url = url.replace("http://", "https://", 1) return AUTH_LOGIN_URL + "?redirect=" + quote(url, safe="")