nomadro/apps/api/services/ebook_svc/services/google_oauth.py
Eric abdcafb1eb Ship Work access gate, pads/boards upgrades, and locale hydration fix on .com.
Gate /social/work behind join/login/profile; harden Work UX and LanguageSwitcher SSR; deploy portal, admin, and work API.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-08 00:14:39 +08:00

431 lines
14 KiB
Python

"""Google OAuth 授权 + 拉取 GA4 / AdSense / Search Console 标识。"""
from __future__ import annotations
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any
import jwt
from ebook_svc.config import settings
AUTH_URI = "https://accounts.google.com/o/oauth2/v2/auth"
TOKEN_URI = "https://oauth2.googleapis.com/token"
SCOPES = (
"openid",
"email",
"https://www.googleapis.com/auth/analytics.readonly",
"https://www.googleapis.com/auth/adsense.readonly",
"https://www.googleapis.com/auth/webmasters.readonly",
"https://www.googleapis.com/auth/siteverification",
)
def _data_dir() -> Path:
raw = (os.getenv("GOOGLE_OAUTH_DATA_DIR") or "").strip()
if raw:
return Path(raw)
try:
from ebook_svc.services.tt_platform_config import resolve_config_file
return resolve_config_file().parent
except Exception:
return Path("/var/www/nomadro-data")
def _client_path() -> Path:
raw = (os.getenv("GOOGLE_OAUTH_CLIENT_PATH") or "").strip()
if raw:
return Path(raw)
return _data_dir() / "google_oauth_client.json"
def _token_path() -> Path:
raw = (os.getenv("GOOGLE_OAUTH_TOKEN_PATH") or "").strip()
if raw:
return Path(raw)
return _data_dir() / "google_oauth_tokens.json"
def load_client_credentials() -> dict[str, str]:
"""Prefer env; fall back to server-only JSON written from admin UI."""
cid = (os.getenv("GOOGLE_OAUTH_CLIENT_ID") or "").strip()
secret = (os.getenv("GOOGLE_OAUTH_CLIENT_SECRET") or "").strip()
if cid and secret:
return {"clientId": cid, "clientSecret": secret, "source": "env"}
path = _client_path()
if path.is_file():
try:
data = json.loads(path.read_text(encoding="utf-8"))
if isinstance(data, dict):
cid2 = str(data.get("clientId") or data.get("client_id") or "").strip()
secret2 = str(
data.get("clientSecret") or data.get("client_secret") or ""
).strip()
if cid2 and secret2:
return {
"clientId": cid2,
"clientSecret": secret2,
"source": "file",
}
except Exception:
pass
return {}
def save_client_credentials(client_id: str, client_secret: str) -> dict[str, str]:
cid = client_id.strip()
secret = client_secret.strip()
if not cid or not secret:
raise RuntimeError("client_id_and_secret_required")
path = _client_path()
path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"clientId": cid,
"clientSecret": secret,
"updatedAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
}
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
try:
os.chmod(path, 0o600)
except Exception:
pass
return {"clientId": cid, "source": "file", "path": str(path)}
def client_id() -> str:
return load_client_credentials().get("clientId") or ""
def client_secret() -> str:
return load_client_credentials().get("clientSecret") or ""
def oauth_configured() -> bool:
return bool(client_id() and client_secret())
def redirect_uri() -> str:
return (
os.getenv("GOOGLE_OAUTH_REDIRECT_URI")
or "https://api.nomadro.com/api/admin/google/oauth/callback"
).strip()
def admin_return_base() -> str:
return (
os.getenv("GOOGLE_OAUTH_ADMIN_RETURN")
or "https://admin.nomadro.com"
).rstrip("/")
def _http_json(
url: str,
*,
method: str = "GET",
headers: dict[str, str] | None = None,
form: dict[str, str] | None = None,
body: dict[str, Any] | None = None,
timeout: float = 25,
) -> dict[str, Any]:
data: bytes | None = None
hdrs = {"Accept": "application/json", **(headers or {})}
if form is not None:
data = urllib.parse.urlencode(form).encode("utf-8")
hdrs["Content-Type"] = "application/x-www-form-urlencoded"
elif body is not None:
data = json.dumps(body).encode("utf-8")
hdrs["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=hdrs, method=method)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
raw = resp.read().decode("utf-8", "replace")
if not raw:
return {}
parsed = json.loads(raw)
return parsed if isinstance(parsed, dict) else {"data": parsed}
except urllib.error.HTTPError as exc:
detail = exc.read().decode("utf-8", "replace")[:500]
raise RuntimeError(f"google_http_{exc.code}:{detail}") from exc
def build_auth_url(*, admin: str, lane: str = "intl") -> str:
if not oauth_configured():
raise RuntimeError("oauth_not_configured")
state = jwt.encode(
{
"sub": admin,
"lane": lane if lane in ("cn", "intl") else "intl",
"purpose": "google_oauth",
"exp": int(time.time()) + 600,
},
settings.jwt_secret,
algorithm="HS256",
)
cid = client_id()
if not cid:
raise RuntimeError("oauth_not_configured")
params = {
"client_id": cid,
"redirect_uri": redirect_uri(),
"response_type": "code",
"scope": " ".join(SCOPES),
"access_type": "offline",
"prompt": "consent",
"include_granted_scopes": "true",
"state": state,
}
return f"{AUTH_URI}?{urllib.parse.urlencode(params)}"
def decode_state(state: str) -> dict[str, Any]:
try:
data = jwt.decode(state, settings.jwt_secret, algorithms=["HS256"])
except Exception as exc:
raise RuntimeError("invalid_oauth_state") from exc
if data.get("purpose") != "google_oauth":
raise RuntimeError("invalid_oauth_state")
return data
def exchange_code(code: str) -> dict[str, Any]:
creds = load_client_credentials()
if not creds.get("clientId") or not creds.get("clientSecret"):
raise RuntimeError("oauth_not_configured")
return _http_json(
TOKEN_URI,
method="POST",
form={
"code": code,
"client_id": creds["clientId"],
"client_secret": creds["clientSecret"],
"redirect_uri": redirect_uri(),
"grant_type": "authorization_code",
},
)
def refresh_access_token(refresh_token: str) -> dict[str, Any]:
creds = load_client_credentials()
if not creds.get("clientId") or not creds.get("clientSecret"):
raise RuntimeError("oauth_not_configured")
return _http_json(
TOKEN_URI,
method="POST",
form={
"client_id": creds["clientId"],
"client_secret": creds["clientSecret"],
"refresh_token": refresh_token,
"grant_type": "refresh_token",
},
)
def save_tokens(admin: str, token_payload: dict[str, Any]) -> None:
path = _token_path()
path.parent.mkdir(parents=True, exist_ok=True)
existing: dict[str, Any] = {}
if path.is_file():
try:
existing = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(existing, dict):
existing = {}
except Exception:
existing = {}
prev = existing.get(admin) if isinstance(existing.get(admin), dict) else {}
merged = {
**prev,
**{k: token_payload[k] for k in ("access_token", "refresh_token", "expires_in", "scope", "token_type", "id_token") if k in token_payload},
"updatedAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
}
if not merged.get("refresh_token") and prev.get("refresh_token"):
merged["refresh_token"] = prev["refresh_token"]
existing[admin] = merged
path.write_text(json.dumps(existing, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
try:
os.chmod(path, 0o600)
except Exception:
pass
def load_tokens(admin: str) -> dict[str, Any] | None:
path = _token_path()
if not path.is_file():
return None
try:
data = json.loads(path.read_text(encoding="utf-8"))
row = data.get(admin) if isinstance(data, dict) else None
return row if isinstance(row, dict) else None
except Exception:
return None
def access_token_for(admin: str) -> str:
row = load_tokens(admin)
if not row:
raise RuntimeError("google_not_connected")
token = str(row.get("access_token") or "")
refresh = str(row.get("refresh_token") or "")
# Always refresh when we have refresh_token to keep it simple/reliable
if refresh:
fresh = refresh_access_token(refresh)
save_tokens(admin, fresh)
token = str(fresh.get("access_token") or token)
if not token:
raise RuntimeError("google_token_missing")
return token
def _auth_headers(token: str) -> dict[str, str]:
return {"Authorization": f"Bearer {token}"}
def fetch_ga_measurement_ids(token: str) -> list[dict[str, str]]:
out: list[dict[str, str]] = []
summaries = _http_json(
"https://analyticsadmin.googleapis.com/v1beta/accountSummaries",
headers=_auth_headers(token),
)
for account in summaries.get("accountSummaries") or []:
if not isinstance(account, dict):
continue
for prop in account.get("propertySummaries") or []:
if not isinstance(prop, dict):
continue
property_name = str(prop.get("property") or "")
if not property_name:
continue
try:
streams = _http_json(
f"https://analyticsadmin.googleapis.com/v1beta/{property_name}/dataStreams",
headers=_auth_headers(token),
)
except Exception:
continue
for stream in streams.get("dataStreams") or []:
if not isinstance(stream, dict):
continue
web = stream.get("webStreamData") if isinstance(stream.get("webStreamData"), dict) else {}
mid = str(web.get("measurementId") or "").strip()
if mid.startswith("G-"):
out.append(
{
"measurementId": mid,
"property": property_name,
"displayName": str(prop.get("displayName") or stream.get("displayName") or mid),
}
)
return out
def fetch_adsense_publisher(token: str) -> dict[str, str]:
data = _http_json(
"https://adsense.googleapis.com/v2/accounts",
headers=_auth_headers(token),
)
accounts = data.get("accounts") or []
if not accounts:
return {}
first = accounts[0] if isinstance(accounts[0], dict) else {}
name = str(first.get("name") or "") # accounts/pub-xxx
pub = name.split("/")[-1] if name else str(first.get("displayName") or "")
if pub.startswith("pub-"):
return {"adsensePublisherId": pub, "adsenseClientId": f"ca-{pub}"}
return {}
def fetch_search_console(token: str, site: str) -> dict[str, str]:
"""Prefer existing site listing; try site verification meta token for our domain."""
out: dict[str, str] = {}
try:
sites = _http_json(
"https://www.googleapis.com/webmasters/v3/sites",
headers=_auth_headers(token),
)
entries = sites.get("siteEntry") or []
wanted = site.rstrip("/") + "/"
for entry in entries:
if not isinstance(entry, dict):
continue
url = str(entry.get("siteUrl") or "")
if url.rstrip("/") == site.rstrip("/") or url == wanted:
out["searchConsoleSite"] = url
break
if not out and entries:
first = entries[0] if isinstance(entries[0], dict) else {}
if first.get("siteUrl"):
out["searchConsoleSite"] = str(first["siteUrl"])
except Exception:
pass
try:
token_body = _http_json(
"https://www.googleapis.com/siteVerification/v1/token",
method="POST",
headers=_auth_headers(token),
body={
"site": {"type": "SITE", "identifier": site.rstrip("/") + "/"},
"verificationMethod": "META",
},
)
meta = str(token_body.get("token") or "").strip()
if meta:
# token may be full meta tag or just content value
if "content=" in meta.lower():
import re
m = re.search(r'content=["\']([^"\']+)["\']', meta, re.I)
if m:
out["googleSiteVerification"] = m.group(1)
else:
out["googleSiteVerification"] = meta
except Exception:
pass
return out
def collect_google_flags(token: str, site: str) -> tuple[dict[str, str], dict[str, Any]]:
"""Pull IDs from Google APIs after OAuth. Ads conversion still often needs Ads API / manual."""
meta: dict[str, Any] = {"gaOptions": [], "warnings": []}
flags: dict[str, str] = {}
try:
ga_list = fetch_ga_measurement_ids(token)
meta["gaOptions"] = ga_list
if ga_list:
flags["gaMeasurementId"] = ga_list[0]["measurementId"]
except Exception as exc:
meta["warnings"].append(f"ga:{exc}")
try:
adsense = fetch_adsense_publisher(token)
flags.update(adsense)
except Exception as exc:
meta["warnings"].append(f"adsense:{exc}")
try:
sc = fetch_search_console(token, site)
if sc.get("googleSiteVerification"):
flags["googleSiteVerification"] = sc["googleSiteVerification"]
meta["searchConsole"] = sc
except Exception as exc:
meta["warnings"].append(f"search_console:{exc}")
if not flags.get("googleAdsId"):
meta["warnings"].append(
"google_ads:转化 ID 需 Google Ads API / 开发者令牌,授权后请手填 AW-"
)
return flags, meta
def return_url(lane: str, *, ok: bool, error: str = "") -> str:
base = f"{admin_return_base()}/{lane}/google"
q = {"oauth": "ok" if ok else "err"}
if error:
q["reason"] = error[:120]
return f"{base}?{urllib.parse.urlencode(q)}"