Support per-channel Google OAuth Client for multi-account YouTube auth.
Existing channels keep using the global Client; optional per-channel Client ID/Secret isolates A/B/C/D OAuth apps without changing Douyin monitor paths. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
cb9042cbe6
commit
4f144f3daf
@ -348,11 +348,20 @@ def _public_shorts_channel(ch: dict[str, Any]) -> dict[str, Any]:
|
||||
out = dict(ch)
|
||||
secret = str(out.get("client_secret") or "")
|
||||
refresh = str(out.get("refresh_token") or "")
|
||||
client_id = str(out.get("client_id") or "").strip()
|
||||
out["has_client_id"] = bool(client_id)
|
||||
out["has_client_secret"] = bool(secret.strip())
|
||||
out["has_refresh_token"] = bool(refresh.strip())
|
||||
out["authorized"] = bool(refresh.strip())
|
||||
# Multi OAuth app (A/B/C/D): channel-level Client overrides global settings
|
||||
oauth_meta = shorts_oauth.resolve_oauth_client(ch)
|
||||
out["oauth_client_source"] = str(oauth_meta.get("source") or "none")
|
||||
out["has_custom_oauth"] = out["oauth_client_source"] == "channel"
|
||||
out["can_authorize"] = shorts_oauth.channel_can_authorize(ch)
|
||||
out["client_secret"] = ("***" + secret[-4:]) if len(secret) > 4 else ("***" if secret else "")
|
||||
out["refresh_token"] = ("***" + refresh[-4:]) if len(refresh) > 4 else ("***" if refresh else "")
|
||||
# client_id is not secret; keep for edit form (empty means use global)
|
||||
out["client_id"] = client_id
|
||||
try:
|
||||
out["oauth_ok"] = int(out.get("oauth_ok") if out.get("oauth_ok") is not None else -1)
|
||||
except Exception:
|
||||
|
||||
@ -1,5 +1,13 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""YouTube OAuth for Shorts — click-to-authorize, stores refresh_token on channel."""
|
||||
"""YouTube OAuth for Shorts — click-to-authorize, stores refresh_token on channel.
|
||||
|
||||
Supports multiple Google OAuth apps (Client ID/Secret pairs):
|
||||
- Global default in settings (shorts_oauth_client_id / secret)
|
||||
- Per-channel override on shorts_channels.client_id / client_secret
|
||||
|
||||
Use case: Google account A/B/C/D each with its own Cloud OAuth client
|
||||
(or same client with different login — channel override still isolates tokens).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
@ -26,8 +34,8 @@ YOUTUBE_SCOPES = " ".join(
|
||||
]
|
||||
)
|
||||
|
||||
# state -> (channel_pk, expires_at)
|
||||
_oauth_states: dict[str, tuple[str, float]] = {}
|
||||
# state -> (channel_pk, expires_at, client_id, client_secret)
|
||||
_oauth_states: dict[str, tuple[str, float, str, str]] = {}
|
||||
|
||||
|
||||
def _cfg() -> dict[str, Any]:
|
||||
@ -50,20 +58,52 @@ def resolve_redirect_uri(request_base: str = "") -> str:
|
||||
return "https://dylive.nomadro.com/api/shorts/oauth/callback"
|
||||
|
||||
|
||||
def resolve_oauth_client(
|
||||
channel: dict[str, Any] | None = None,
|
||||
cfg: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Prefer per-channel Client ID/Secret; fall back to global settings.
|
||||
|
||||
Returns:
|
||||
client_id, client_secret, source ("channel"|"global"|"none")
|
||||
"""
|
||||
settings = cfg or _cfg()
|
||||
ch = channel or {}
|
||||
ch_id = str(ch.get("client_id") or "").strip()
|
||||
ch_secret = str(ch.get("client_secret") or "").strip()
|
||||
if ch_id and ch_secret:
|
||||
return {"client_id": ch_id, "client_secret": ch_secret, "source": "channel"}
|
||||
g_id = str(settings.get("shorts_oauth_client_id") or "").strip()
|
||||
g_secret = str(settings.get("shorts_oauth_client_secret") or "").strip()
|
||||
if g_id and g_secret:
|
||||
return {"client_id": g_id, "client_secret": g_secret, "source": "global"}
|
||||
return {"client_id": "", "client_secret": "", "source": "none"}
|
||||
|
||||
|
||||
def channel_can_authorize(channel: dict[str, Any] | None, cfg: dict[str, Any] | None = None) -> bool:
|
||||
return resolve_oauth_client(channel, cfg).get("source") != "none"
|
||||
|
||||
|
||||
def build_authorize_url(*, channel_pk: str, request_base: str = "") -> str:
|
||||
cfg = _cfg()
|
||||
client_id = str(cfg.get("shorts_oauth_client_id") or "").strip()
|
||||
if not client_id:
|
||||
raise ValueError("请先在设置里填写 Google OAuth Client ID / Secret")
|
||||
if not db.get_shorts_channel(channel_pk):
|
||||
channel = db.get_shorts_channel(channel_pk)
|
||||
if not channel:
|
||||
raise ValueError("频道不存在")
|
||||
client = resolve_oauth_client(channel, cfg)
|
||||
client_id = str(client.get("client_id") or "")
|
||||
client_secret = str(client.get("client_secret") or "")
|
||||
if not client_id or not client_secret:
|
||||
raise ValueError(
|
||||
"请先在「设置」填写全局 Google OAuth Client,或在本频道填写专属 Client ID/Secret"
|
||||
)
|
||||
# purge expired
|
||||
now = time.time()
|
||||
for k, (_pk, exp) in list(_oauth_states.items()):
|
||||
if exp < now:
|
||||
for k, packed in list(_oauth_states.items()):
|
||||
if len(packed) < 2 or packed[1] < now:
|
||||
_oauth_states.pop(k, None)
|
||||
state = secrets.token_urlsafe(24)
|
||||
_oauth_states[state] = (channel_pk, now + 600)
|
||||
# Bind the exact client used for authorize so exchange matches (A/B/C/D apps)
|
||||
_oauth_states[state] = (channel_pk, now + 600, client_id, client_secret)
|
||||
params = {
|
||||
"client_id": client_id,
|
||||
"redirect_uri": resolve_redirect_uri(request_base),
|
||||
@ -85,12 +125,24 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
|
||||
packed = _oauth_states.pop(state, None)
|
||||
if not packed:
|
||||
raise ValueError("授权 state 无效或已过期,请重新点击授权")
|
||||
channel_pk, exp = packed
|
||||
channel_pk = packed[0]
|
||||
exp = packed[1]
|
||||
if exp < time.time():
|
||||
raise ValueError("授权已过期,请重新点击授权")
|
||||
cfg = _cfg()
|
||||
client_id = str(cfg.get("shorts_oauth_client_id") or "").strip()
|
||||
client_secret = str(cfg.get("shorts_oauth_client_secret") or "").strip()
|
||||
channel = db.get_shorts_channel(channel_pk) or {}
|
||||
if len(packed) >= 4 and packed[2] and packed[3]:
|
||||
client_id, client_secret = packed[2], packed[3]
|
||||
source = "channel" if (
|
||||
str(channel.get("client_id") or "").strip() == client_id
|
||||
and str(channel.get("client_secret") or "").strip() == client_secret
|
||||
) else "bound"
|
||||
else:
|
||||
# Legacy state tuple — re-resolve from channel/global
|
||||
client = resolve_oauth_client(channel, cfg)
|
||||
client_id = str(client.get("client_id") or "")
|
||||
client_secret = str(client.get("client_secret") or "")
|
||||
source = str(client.get("source") or "none")
|
||||
if not client_id or not client_secret:
|
||||
raise ValueError("缺少 OAuth Client 配置")
|
||||
redirect_uri = resolve_redirect_uri(request_base)
|
||||
@ -112,8 +164,7 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
|
||||
refresh = str(token.get("refresh_token") or "").strip()
|
||||
if not refresh:
|
||||
# Google may omit refresh if previously granted; keep existing if any
|
||||
existing = db.get_shorts_channel(channel_pk) or {}
|
||||
refresh = str(existing.get("refresh_token") or "").strip()
|
||||
refresh = str(channel.get("refresh_token") or "").strip()
|
||||
if not refresh:
|
||||
raise ValueError("未拿到 refresh_token,请在 Google 账号权限里撤销本应用后重试")
|
||||
|
||||
@ -130,6 +181,7 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
|
||||
yt_id = str(items[0].get("id") or "")
|
||||
yt_title = str((items[0].get("snippet") or {}).get("title") or "")
|
||||
|
||||
# Persist the Client that issued this token (critical for multi-app A/B/C/D)
|
||||
patch: dict[str, Any] = {
|
||||
"client_id": client_id,
|
||||
"client_secret": client_secret,
|
||||
@ -137,9 +189,8 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
|
||||
}
|
||||
if yt_id:
|
||||
patch["youtube_channel_id"] = yt_id
|
||||
existing = db.get_shorts_channel(channel_pk) or {}
|
||||
# auto-fill name if still placeholder
|
||||
name = str(existing.get("name") or "").strip()
|
||||
name = str(channel.get("name") or "").strip()
|
||||
if yt_title and (not name or name.startswith("Shorts") or name == "未命名频道"):
|
||||
patch["name"] = yt_title
|
||||
updated = db.update_shorts_channel(channel_pk, **patch)
|
||||
@ -148,15 +199,16 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
|
||||
"channel": updated,
|
||||
"youtube_channel_id": yt_id,
|
||||
"youtube_title": yt_title,
|
||||
"oauth_client_source": source,
|
||||
}
|
||||
|
||||
|
||||
def channel_oauth_creds(channel: dict[str, Any], cfg: dict[str, Any] | None = None) -> dict[str, str]:
|
||||
"""Resolve upload credentials: channel token + global client fallback."""
|
||||
settings = cfg or _cfg()
|
||||
"""Resolve upload credentials: channel token + channel/global client."""
|
||||
client = resolve_oauth_client(channel, cfg)
|
||||
return {
|
||||
"client_id": str(channel.get("client_id") or settings.get("shorts_oauth_client_id") or "").strip(),
|
||||
"client_secret": str(channel.get("client_secret") or settings.get("shorts_oauth_client_secret") or "").strip(),
|
||||
"client_id": str(client.get("client_id") or ""),
|
||||
"client_secret": str(client.get("client_secret") or ""),
|
||||
"refresh_token": str(channel.get("refresh_token") or "").strip(),
|
||||
}
|
||||
|
||||
|
||||
@ -449,7 +449,8 @@ export default function SettingsPage() {
|
||||
</label>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500">
|
||||
只需配置一次 Client。各上传频道在「Shorts」页点「Google 授权」自动写入 refresh_token,无需手填。
|
||||
全局只需配置一次默认 Client。各上传频道可在编辑里覆盖专属 Client ID/Secret(谷歌账号 A/B/C/D /
|
||||
不同 Cloud 项目),再点「Google 授权」写入该频道的 refresh_token。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@ -46,6 +46,12 @@ type Channel = {
|
||||
note?: string;
|
||||
authorized?: boolean;
|
||||
has_refresh_token?: boolean;
|
||||
client_id?: string;
|
||||
has_client_id?: boolean;
|
||||
has_client_secret?: boolean;
|
||||
has_custom_oauth?: boolean;
|
||||
can_authorize?: boolean;
|
||||
oauth_client_source?: "channel" | "global" | "none" | string;
|
||||
};
|
||||
|
||||
type BoardChannel = {
|
||||
@ -90,6 +96,9 @@ const emptyForm = {
|
||||
description_template: "{anchor}\n{url}\n#Shorts #直播",
|
||||
privacy: "public",
|
||||
note: "",
|
||||
/** Per-channel Google OAuth app (A/B/C/D). Empty = use global settings. */
|
||||
client_id: "",
|
||||
client_secret: "",
|
||||
};
|
||||
|
||||
const STATUS_STYLE: Record<string, string> = {
|
||||
@ -307,11 +316,16 @@ export default function ShortsPage() {
|
||||
}
|
||||
|
||||
function goAuthorize(channelId: string) {
|
||||
if (!status?.oauth_configured) {
|
||||
const ch = channels.find((c) => c.id === channelId);
|
||||
// Stale state after create is fine — only block when we know this channel cannot auth
|
||||
if (ch && !ch.can_authorize) {
|
||||
setShowWizard(true);
|
||||
setError("请先配置 Google OAuth Client");
|
||||
setError("请先配置全局 Google OAuth,或在该频道填写专属 Client ID/Secret(用于 A/B/C/D 多套应用)");
|
||||
return;
|
||||
}
|
||||
if (!ch && !status?.oauth_configured) {
|
||||
// Channel list not refreshed yet; still try — backend validates channel/global client
|
||||
}
|
||||
window.location.href = `/api/shorts/oauth/start?channel_pk=${encodeURIComponent(channelId)}`;
|
||||
}
|
||||
|
||||
@ -320,8 +334,32 @@ export default function ShortsPage() {
|
||||
setMsg("");
|
||||
setError("");
|
||||
try {
|
||||
const body = { ...form, daily_min: 9, daily_max: 9 };
|
||||
if (!body.name.trim()) body.name = "未命名频道";
|
||||
const body: Record<string, unknown> = {
|
||||
name: form.name,
|
||||
enabled: form.enabled,
|
||||
daily_min: 9,
|
||||
daily_max: 9,
|
||||
title_template: form.title_template,
|
||||
description_template: form.description_template,
|
||||
privacy: form.privacy,
|
||||
note: form.note,
|
||||
};
|
||||
if (!String(body.name || "").trim()) body.name = "未命名频道";
|
||||
// Per-channel OAuth app: only send when user typed something (empty secret keeps existing)
|
||||
if (form.client_id.trim()) body.client_id = form.client_id.trim();
|
||||
if (form.client_secret.trim() && !form.client_secret.startsWith("***")) {
|
||||
body.client_secret = form.client_secret.trim();
|
||||
}
|
||||
const hasChannelClient = Boolean(
|
||||
(body.client_id as string | undefined)?.trim() &&
|
||||
((body.client_secret as string | undefined)?.trim() ||
|
||||
(editId && form.client_secret.startsWith("***"))),
|
||||
);
|
||||
if (andAuth && !status?.oauth_configured && !hasChannelClient && !(editId && channels.find((c) => c.id === editId)?.can_authorize)) {
|
||||
setShowWizard(true);
|
||||
setError("授权前请配置全局 OAuth,或为本频道填写成对的 Client ID/Secret");
|
||||
return;
|
||||
}
|
||||
let id = editId;
|
||||
if (editId) {
|
||||
await fetchJson(`/api/shorts/channels/${editId}`, { method: "PATCH", body: JSON.stringify(body) });
|
||||
@ -336,7 +374,8 @@ export default function ShortsPage() {
|
||||
setShowForm(false);
|
||||
await load();
|
||||
if (andAuth && id) {
|
||||
goAuthorize(id);
|
||||
// Direct redirect — avoid stale can_authorize from React state
|
||||
window.location.href = `/api/shorts/oauth/start?channel_pk=${encodeURIComponent(id)}`;
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
@ -358,6 +397,8 @@ export default function ShortsPage() {
|
||||
description_template: ch.description_template || "",
|
||||
privacy: ch.privacy || "public",
|
||||
note: ch.note || "",
|
||||
client_id: ch.client_id || "",
|
||||
client_secret: ch.has_client_secret ? "***" : "",
|
||||
});
|
||||
}
|
||||
|
||||
@ -973,6 +1014,15 @@ export default function ShortsPage() {
|
||||
? "已授权"
|
||||
: "未授权"}
|
||||
</span>
|
||||
{full?.has_custom_oauth ? (
|
||||
<span className="text-violet-300" title="使用频道专属 OAuth Client">
|
||||
专属 Client
|
||||
</span>
|
||||
) : full?.oauth_client_source === "global" ? (
|
||||
<span className="text-slate-500" title="使用全局 OAuth Client">
|
||||
全局 Client
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative mt-3 h-1.5 overflow-hidden rounded-full bg-white/10">
|
||||
@ -1113,9 +1163,40 @@ export default function ShortsPage() {
|
||||
value={form.note}
|
||||
onChange={(e) => setForm((p) => ({ ...p, note: e.target.value }))}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
|
||||
placeholder="如:谷歌账号 B / OAuth 应用 B"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="mt-4 rounded-xl border border-amber-500/20 bg-amber-500/5 p-3">
|
||||
<p className="text-xs font-medium text-amber-100">专属 OAuth 应用(可选 · 区分谷歌账号 A/B/C/D)</p>
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-slate-400">
|
||||
留空则用设置里的全局 Client。若频道在另一个谷歌账号 / Cloud 项目下,在此填写该项目的 Client ID/Secret;
|
||||
每个 OAuth 应用都须登记同一回调 URI。授权时选对应谷歌账号登录。
|
||||
</p>
|
||||
<div className="mt-2 grid gap-2 sm:grid-cols-2">
|
||||
<label className="block text-xs text-slate-400">
|
||||
Client ID
|
||||
<input
|
||||
value={form.client_id}
|
||||
onChange={(e) => setForm((p) => ({ ...p, client_id: e.target.value }))}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-xs"
|
||||
placeholder="xxxx.apps.googleusercontent.com(空=全局)"
|
||||
autoComplete="off"
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-xs text-slate-400">
|
||||
Client Secret
|
||||
<input
|
||||
type="password"
|
||||
value={form.client_secret}
|
||||
onChange={(e) => setForm((p) => ({ ...p, client_secret: e.target.value }))}
|
||||
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-xs"
|
||||
placeholder={editId ? "留空或 *** 表示不修改" : "与 Client ID 成对填写"}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<button
|
||||
type="button"
|
||||
|
||||
Loading…
Reference in New Issue
Block a user