feat: save registered accounts to postgres

This commit is contained in:
mmc
2026-03-19 14:32:17 +08:00
parent 6a250fe6a1
commit 2904e43b1f
11 changed files with 235 additions and 4 deletions

73
account_store.py Normal file
View File

@@ -0,0 +1,73 @@
from __future__ import annotations
from typing import Any, Dict, Optional
import psycopg
def is_db_enabled(cfg: Dict[str, Any]) -> bool:
return bool(cfg.get("db_enabled", False))
def _dsn(cfg: Dict[str, Any]) -> str:
return (
f"host={cfg.get('db_host', '')} "
f"port={int(cfg.get('db_port', 5432) or 5432)} "
f"dbname={cfg.get('db_name', 'postgres')} "
f"user={cfg.get('db_user', '')} "
f"password={cfg.get('db_password', '')} "
"connect_timeout=10"
)
def save_registered_account(cfg: Dict[str, Any], record: Dict[str, Any]) -> Dict[str, Any]:
if not is_db_enabled(cfg):
return {"ok": False, "skipped": True, "reason": "db_disabled"}
table = str(cfg.get("db_table", "registered_accounts") or "registered_accounts").strip()
source = str(cfg.get("db_source", "standalone_cli") or "standalone_cli").strip()
payload = {
"email": str(record.get("email") or "").strip() or None,
"chatgpt_password": str(record.get("chatgpt_password") or "").strip() or None,
"mail_password": str(record.get("mail_password") or "").strip() or None,
"oauth_status": str(record.get("oauth_status") or "oauth=ok").strip() or "oauth=ok",
"mail_token": str(record.get("mail_token") or "").strip() or None,
"name": str(record.get("name") or "").strip() or None,
"birthdate": str(record.get("birthdate") or "").strip() or None,
"source": str(record.get("source") or source).strip() or source,
}
if not payload["email"]:
return {"ok": False, "error": "missing email"}
sql = f"""
INSERT INTO {table} (
email,
chatgpt_password,
mail_password,
oauth_status,
created_at,
updated_at,
mail_token,
name,
birthdate,
source
) VALUES (
%(email)s,
%(chatgpt_password)s,
%(mail_password)s,
%(oauth_status)s,
NOW(),
NOW(),
%(mail_token)s,
%(name)s,
%(birthdate)s,
%(source)s
)
"""
with psycopg.connect(_dsn(cfg)) as conn:
with conn.cursor() as cur:
cur.execute(sql, payload)
conn.commit()
return {"ok": True, "skipped": False, "table": table, "email": payload["email"]}