Files
37duAutomation/desktop/electron-shell/electron/platform-auth.js
T

250 lines
8.6 KiB
JavaScript
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.
// 平台登录态(HR/OA):真实登录/登出/在线校验。
// 保持 Python 子进程执行登录自动化(shared/hr_login、oa_login,DrissionPage 滑块),
// Node 壳只负责拉起子进程与解析结果。
// ★ 按账号隔离:每个登录账号拥有独立的会话目录(.sessions/<账号>/)与独立 HR/OA 账号密码,
// 子进程通过 PLATFORM_ACCOUNT 环境变量 + hr_login_username/password 注入各自身份。
"use strict";
const fs = require("fs");
const path = require("path");
const { spawn } = require("child_process");
const config = require("./config");
const platformCreds = require("./platform-creds");
const { makeLogger } = require("./logger");
const logger = makeLogger("platform-auth");
const LABELS = { hr: "HR 系统", oa: "OA 系统" };
const COOKIE_FILES = {
hr: "hr_cookies.json",
oa: "oa_cookies.json",
};
const BASE_SESSIONS_DIR = path.join(config.APP_DATA, ".sessions");
const _onlineCache = new Map(); // `${account}:${pid}` -> {ts, value}
const ONLINE_CACHE_TTL = 15 * 1000;
function platforms() {
return Object.keys(LABELS).map((pid) => ({ id: pid, label: LABELS[pid] }));
}
// 账号隔离的会话目录;无账号时回退共享目录(兼容旧数据)
function sessionDir(account) {
const base = account ? path.join(BASE_SESSIONS_DIR, String(account)) : BASE_SESSIONS_DIR;
try {
fs.mkdirSync(base, { recursive: true });
} catch (e) {
/* 忽略 */
}
return base;
}
// spawn python 子进程执行 snippet,返回 stdout 最后一行 JSON(或文本)
function runPython(snippet, timeoutMs = 120000, extraEnv = {}) {
return new Promise((resolve, reject) => {
const args = ["-c", snippet];
const child = spawn(config.pythonExe(), args, {
// webhost 包解析:环境包模式 cwd=环境包根(webhost/ 在其中);dev = desktop/(仓库内 webhost)
cwd: config.runtimeRoot(),
windowsHide: true,
env: { ...process.env, PYTHONIOENCODING: "utf-8", PYTHONUTF8: "1", ...extraEnv },
stdio: ["ignore", "pipe", "pipe"],
});
let out = "";
let err = "";
const timer = setTimeout(() => {
try {
treeKill(child.pid);
} catch (e) {
/* 忽略 */
}
reject(new Error("平台登录子进程超时"));
}, timeoutMs);
child.stdout.on("data", (d) => (out += d.toString("utf-8")));
child.stderr.on("data", (d) => (err += d.toString("utf-8")));
child.on("error", (e) => {
clearTimeout(timer);
reject(new Error(`拉起 Python 子进程失败: ${e.message}`));
});
child.on("close", (code) => {
clearTimeout(timer);
if (code !== 0) {
reject(new Error(`平台子进程退出(${code}): ${err.slice(0, 300)}`));
return;
}
resolve(out.trim());
});
});
}
function treeKill(pid) {
try {
if (process.platform === "win32") {
const killer = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
windowsHide: true,
stdio: "ignore",
detached: true,
});
killer.unref();
} else {
try {
process.kill(-pid, "SIGKILL");
} catch (e) {
process.kill(pid, "SIGKILL");
}
}
} catch (e) {
/* 忽略 */
}
}
function extractJson(out) {
// 兼容模块 print("最终结果:", dict) 与纯 JSON 输出:取最后一个 JSON 对象
const lines = out.split(/\r?\n/).filter((l) => l.trim());
for (let i = lines.length - 1; i >= 0; i--) {
const line = lines[i];
const idx = line.indexOf("{");
if (idx >= 0) {
try {
return JSON.parse(line.slice(idx));
} catch (e) {
/* 继续找 */
}
}
}
return null;
}
// 真实校验平台登录态(发起轻量 API 校验,非内存假状态);结果短缓存避免频繁请求平台。
const VALIDATE = {
hr: {
url: "https://hr.37du.co/RedseaPlatform/PtUsers.mc?method=getCurUserInfo",
method: "POST",
},
oa: {
url: "https://oa.37du.co/sys/notify/sys_notify_todo/sysNotifyTodo.do?method=sumTodoCount",
method: "GET",
},
};
function loadCookies(pid, account) {
const file = path.join(sessionDir(account), COOKIE_FILES[pid]);
if (!fs.existsSync(file)) return [];
try {
const raw = JSON.parse(fs.readFileSync(file, "utf-8"));
return Array.isArray(raw) ? raw : [];
} catch (e) {
return [];
}
}
async function isOnline(pid, account) {
const cacheKey = `${account || ""}:${pid}`;
const cached = _onlineCache.get(cacheKey);
if (cached && Date.now() - cached.ts < ONLINE_CACHE_TTL) return cached.value;
let value = false;
const def = VALIDATE[pid];
if (!def) return false;
try {
const cookies = loadCookies(pid, account);
if (cookies.length === 0) {
value = false;
} else {
const pairs = [];
for (const c of cookies) {
if (c && c.name && c.value && (!c.domain || String(c.domain).includes("37du.co"))) {
pairs.push(`${c.name}=${c.value}`);
}
}
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 8000);
const resp = await fetch(def.url, {
method: def.method,
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded",
...(pairs.length ? { Cookie: pairs.join("; ") } : {}),
},
body: def.method === "POST" ? "" : undefined,
signal: ctrl.signal,
redirect: "manual",
});
clearTimeout(timer);
const text = await resp.text();
value = resp.status === 200 && text.trim().startsWith("{") || text.trim().startsWith("[");
}
} catch (e) {
logger.warning(`平台 ${pid} 在线校验失败:${e.message}`);
value = false;
}
_onlineCache.set(cacheKey, { ts: Date.now(), value });
return value;
}
// 真实登录:cookies 有效则复用(不弹浏览器),失效则浏览器自动化登录。
// account:当前登录账号;其个人 HR/OA 账号密码通过环境变量注入登录子进程。
async function login(pid, account) {
if (!LABELS[pid]) throw Object.assign(new Error(`未知平台: ${pid}`), { status: 404 });
const cacheKey = `${account || ""}:${pid}`;
_onlineCache.delete(cacheKey);
const extraEnv = { PLATFORM_ACCOUNT: account || "" };
const credEnv = platformCreds.envFor(account, pid);
if (credEnv) {
Object.assign(extraEnv, credEnv);
logger.info(`平台 ${pid} 使用账号「${credEnv[`${pid}_login_username`]}」登录(账号 ${account})`);
} else {
logger.warning(`平台 ${pid} 登录:账号 ${account} 未配置个人平台账号密码,将回退共享配置`);
}
try {
const snippet =
pid === "hr"
? `from webhost.backend.shared import hr_login; import json; print(json.dumps(hr_login.main({"force": False}), ensure_ascii=False))`
: `from webhost.backend.shared import oa_login; import json; print(json.dumps(oa_login.main(force=False), ensure_ascii=False))`;
const out = await runPython(snippet, 5 * 60 * 1000, extraEnv);
const result = extractJson(out) || {};
const ok = !!result.success;
const online = ok ? await isOnline(pid, account) : false;
return {
id: pid,
label: LABELS[pid],
online,
message: result.message || (ok ? "登录成功" : "登录失败"),
};
} catch (e) {
logger.error(`平台 ${pid} 登录失败(账号 ${account}):${e.message}`);
return { id: pid, label: LABELS[pid], online: false, message: `登录过程异常:${e.message}` };
}
}
// 登出平台:删除该账号的 cookies 文件,使该账号的平台登录态失效。
function logout(pid, account) {
if (!LABELS[pid]) throw Object.assign(new Error(`未知平台: ${pid}`), { status: 404 });
_onlineCache.delete(`${account || ""}:${pid}`);
const file = path.join(sessionDir(account), COOKIE_FILES[pid]);
try {
if (fs.existsSync(file)) fs.unlinkSync(file);
} catch (e) {
logger.warning(`清除平台 ${pid} cookies 失败(账号 ${account}):${e.message}`);
}
return { id: pid, label: LABELS[pid], online: false };
}
// 当前账号的平台状态(个人中心展示):在线态 + 是否已配置个人账号密码 + 已存用户名
async function status(account) {
const creds = platformCreds.get(account) || {};
const out = [];
for (const pid of Object.keys(LABELS)) {
const c = creds[pid] || {};
out.push({
id: pid,
label: LABELS[pid],
online: await isOnline(pid, account),
has_creds: !!(c.user && c.pass),
user: c.user || "",
});
}
return out;
}
module.exports = { platforms, sessionDir, isOnline, login, logout, status, BASE_SESSIONS_DIR };