Files
37duAutomation/desktop/webhost/backend/apis/dingtalk.py
T
puddy 1e533dd1b3 refactor: 完成项目目录重构与代码迁移
本次提交完成了整体项目的目录梳理与代码迁移:
1.  将根级controlplane、webhost等目录的代码迁移至desktop/对应子目录,统一桌面端架构
2.  移动并整理了插件目录结构,将插件统一放入根级plugins/
3.  调整了前端项目的路径与配置,统一前后端开发构建流程
4.  清理了废弃的旧版app/目录与冗余的构建中间文件
5.  更新了.gitignore与README.md,适配新的项目结构
2026-09-14 17:46:09 +08:00

224 lines
9.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""webhost 宿主「钉钉」路由:账号工号登录、内嵌二维码登录、链接授权回跳、真实扫码回调。
- 账号密码登录与两种钉钉扫码(链接授权 / 内嵌二维码)共用 _dingtalk_establish 建会话。
- 云端(cp)只参与换 token,AppSecret 不出云端;会话存本机、重启不掉。
"""
from __future__ import annotations
import logging
import secrets
import threading
import time
import uuid
from urllib.parse import urlencode
from fastapi import APIRouter, HTTPException, Request, Response
from fastapi.responses import HTMLResponse, RedirectResponse
from pydantic import BaseModel
from webhost.backend import config
from webhost.backend.core.cpapi import _cp_call, _sync_licensing
from webhost.backend.core.session import (SESSION_COOKIE, _ACCT_CLOUD_TOKEN, _SESS,
_SESS_LOCK, _sess_persist)
_LOGGER = logging.getLogger(__name__)
router = APIRouter()
# 登录回跳 state 有效期与缓存(防 CSRF 回跳伪造)
_LOGIN_STATE_TTL = 5 * 60 # state 有效期(秒)
_LOGIN_STATES: dict[str, float] = {} # state -> expiry(待回跳校验)
_LOGIN_LOCK = threading.Lock()
class _DingTalkIn(BaseModel):
account: str # 钉钉工号(作为统一账号)
nickname: str = "" # 钉钉姓名
dingtalk_uid: str = "" # 钉钉 userid/openId(便于二次扫码精确复用)
class _InlineIn(BaseModel):
code: str # 内嵌二维码扫码后钉钉 JS 返回的 loginTmpCode
def _login_state_new() -> str:
with _LOGIN_LOCK:
_now = time.time()
for s in [s for s, e in _LOGIN_STATES.items() if e < _now]:
_LOGIN_STATES.pop(s, None)
state = secrets.token_urlsafe(24)
_LOGIN_STATES[state] = _now + _LOGIN_STATE_TTL
return state
def _login_state_take(state: str) -> bool:
with _LOGIN_LOCK:
exp = _LOGIN_STATES.pop(state, None)
return bool(exp and exp >= time.time())
def _auth_done_page(text: str) -> HTMLResponse:
return HTMLResponse(f"""<!doctype html><html><head><meta charset="utf-8"><title>登录</title></head>
<body style="font-family:sans-serif;text-align:center;padding:60px">
<p>{text}</p><p><a href="/">返回</a></p></body></html>""")
def _dingtalk_establish(account: str, nickname: str, dingtalk_uid: str, response: Response) -> dict:
"""统一建立钉钉账号会话:中心机找建账号 → 写本机会话 cookie → 同步离线票据。
账号密码登录与两种钉钉扫码(链接授权 / 内嵌二维码)共用此通路,保证登录态一致。
"""
r = _cp_call(
"POST", "/api/admin/dingtalk/auth",
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}),
json={"account": account, "nickname": nickname, "dingtalk_uid": dingtalk_uid})
acct = r.get("account") or account
token = uuid.uuid4().hex
with _SESS_LOCK:
_SESS[token] = (acct, time.time())
_sess_persist()
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
if config.CONTROLPLANE_URL:
try:
_sync_licensing(acct)
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
return {"ok": True, "account": acct, "is_admin": bool(r.get("is_admin")),
"created": bool(r.get("created")), "must_change_pwd": bool(r.get("must_change_pwd"))}
@router.post("/api/admin/dingtalk/login")
def admin_dingtalk_login(d: _DingTalkIn, response: Response) -> dict:
"""钉钉扫码登录(链接授权后回跳):account/nickname 已由中心机换取,直接建立会话。"""
if not d.account:
raise HTTPException(400, "工号不能为空")
return _dingtalk_establish(d.account.strip(), d.nickname, d.dingtalk_uid, response)
@router.post("/api/admin/dingtalk/inline")
def admin_dingtalk_inline(d: _InlineIn, response: Response) -> dict:
"""内嵌二维码扫码登录:loginTmpCode → 中心机换工号/姓名 → 建立会话。
登录页用钉钉 DDLogin 在本页内渲染二维码,扫码后前端拿到 loginTmpCode 传本接口,
由中心机换出工号/姓名(可信身份源),再走 _dingtalk_establish 建会话——全程不弹浏览器。
"""
if not d.code.strip():
raise HTTPException(400, "缺少扫码截图码")
if not config.CONTROLPLANE_URL:
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
info = _cp_call(
"POST", "/api/admin/dingtalk/sns",
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}),
json={"code": d.code.strip()})
account = (info.get("account") or "").strip()
if not account:
raise HTTPException(401, "扫码未解析到有效账号,请重新扫码")
return _dingtalk_establish(account, info.get("nickname") or "", info.get("unionid") or "", response)
@router.get("/api/admin/dingtalk/inline_qr")
def admin_dingtalk_inline_qr(request: Request) -> dict:
"""内嵌二维码登录:代理中心机构造 DDLogin 的 goto 参数(登录页在本页内渲染二维码)。"""
if not config.CONTROLPLANE_URL:
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
return _cp_call(
"GET", "/api/admin/dingtalk/inline_qr",
params={"back": back},
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}))
@router.get("/api/auth/dingtalk")
def auth_dingtalk_url() -> dict:
"""生成并返回钉钉扫码授权 URL(redirect_uri=本机 /auth/done)。前端「钉钉登录」当前窗口跳转该 URL。"""
if not config.DINGTALK_APP_KEY:
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY)")
if not config.CONTROLPLANE_URL:
raise HTTPException(503, "未配置中心机地址(CONTROLPLANE_URL)")
state = _login_state_new()
redirect_uri = f"http://localhost:{config.PORT}/auth/done"
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
"redirect_uri": redirect_uri,
"response_type": "code",
"client_id": config.DINGTALK_APP_KEY,
"scope": "openid",
"prompt": "consent",
"state": state})
return {"url": login_url, "state": state}
@router.get("/auth/done")
def auth_done(code: str = "", state: str = "", error: str = "") -> Response:
"""钉钉回跳落点(浏览器):收 code+state → 校验 state → 云端 /auth/exchange 换工号 → 建本机会话。
成功后写会话 cookie 并 302 回主页;任何失败给 HTML 提示,不建立会话。
"""
if error:
return _auth_done_page("钉钉登录被取消或失败,请返回重试。")
if not (code and state) or not _login_state_take(state):
return _auth_done_page("登录状态无效或已过期,请返回重新扫码。")
try:
info = _cp_call("POST", "/auth/exchange", json={"code": code})
except HTTPException as e:
return _auth_done_page(f"登录失败:{e.detail}")
account = (info.get("account") or "").strip()
if not account or not info.get("exists"):
return _auth_done_page("账号未开通或未解析到有效工号,请联系管理员。")
# 建本机会话(写内存+落盘+set-cookie),并存云端 token 供后续调云端 API(§2.2)。
_token = uuid.uuid4().hex
with _SESS_LOCK:
_SESS[_token] = (account, time.time())
_sess_persist()
if info.get("token"):
_ACCT_CLOUD_TOKEN[account] = info["token"]
resp = RedirectResponse("/")
resp.set_cookie(SESSION_COOKIE, _token, httponly=True, samesite="lax")
if config.CONTROLPLANE_URL:
try:
_sync_licensing(account)
except Exception as _exc: # noqa: BLE001 同步失败不影响登录
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
return resp
_DINGTALK_CB_HTML = """<!doctype html><html><head><meta charset="utf-8"><title>登录中</title></head>
<body style="margin:0;background:#f5f6fa;font-family:system-ui,-apple-system,sans-serif">
<div style="padding:60px 20px;text-align:center;color:#5c6470">钉钉登录中,请稍候…</div>
<script>
(async function(){
var q = new URLSearchParams(location.search);
var account = q.get('account') || '';
var nickname = q.get('nickname') || '';
if (account) {
try {
await fetch('/api/admin/dingtalk/login', {
method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify({ account: account, nickname: nickname })
});
} catch (e) {}
}
try { window.opener && window.opener.location.reload(); } catch (e) {}
setTimeout(function(){ try { window.close(); } catch (e) {} }, 500);
})();
</script></body></html>"""
@router.get("/api/admin/dingtalk/qr")
def dingtalk_qr(request: Request) -> dict:
"""返回中心机扫码登录 URL。
扫码换取工号/姓名在中心机完成(中心机 .env 的 DINGTALK_APP_KEY),
部署机只需能访问中心机即可,无需自带钉钉应用凭证。
未配置中心机(CONTROLPLANE_URL)时返回空串,前端隐藏扫码入口。
"""
if not config.CONTROLPLANE_URL:
return {"url": ""}
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
return {"url": f"{config.CONTROLPLANE_URL}/api/admin/dingtalk/scan?{urlencode({'back': back})}"}
@router.get("/api/admin/dingtalk/cb")
def dingtalk_cb() -> HTMLResponse:
"""钉钉扫码成功后的静默回调页:建会话并刷新父窗口。"""
return HTMLResponse(_DINGTALK_CB_HTML)