# -*- coding: utf-8 -*- """平台登录态管理(webhost 宿主壳 · 复用 desktop/shared 单一真源) - cookies 与 desktop/影刀版共用同一份共享文件(%LOCALAPPDATA%\37duAutomation\.sessions), 任一端登录成功后,webhost 直接复用,无需重复登录 - is_online():真实校验(轻量 API 校验 cookies 有效性),不是内存假状态 - login():真实登录(cookies 有效则秒级复用;失效则浏览器自动化滑块登录) - build_session():从共享 cookies 构建 requests.Session,供插件直接调用 shared 数据模块 约定:webhost 只依赖 desktop/shared 的真源登录模块,不复制登录逻辑。 """ from __future__ import annotations import json import os import requests from webhost.backend.shared import hr_login as _hr from webhost.backend.shared import oa_login as _oa from webhost.backend.shared import seal_data_export as _seal _LABELS = {"hr": "HR 系统", "oa": "OA 系统"} # 共享 cookies:与 desktop/shared 版本使用同一份文件,路径约定保持一致 _APP_DATA_DIR = os.path.join( os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'), '37duAutomation') _SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions') # 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入), # 未设置时沿用共享目录(兼容旧逻辑) _ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip() if _ACCOUNT: _SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT) # 各平台 cookie 文件与域名(构建 session 时按域过滤) _COOKIE_DEFS = { "hr": {"file": "hr_cookies.json", "domain": "hr.37du.co"}, "oa": {"file": "oa_cookies.json", "domain": "oa.37du.co"}, } # 登录模块(desktop/shared 真源) _LOGIN_MODS = {"hr": _hr, "oa": _oa} class PlatformAuthError(Exception): """平台不存在 / 登录态不可用等宿主层错误。""" def platforms() -> list: return [{"id": pid, "label": label} for pid, label in _LABELS.items()] def is_online(pid: str) -> bool: """真实校验平台登录态(发起轻量 API 校验,非内存假状态)。""" if pid == "hr": return _hr._is_hr_session_valid() if pid == "oa": return _oa._is_oa_session_valid() return False def login(pid: str) -> dict: """真实登录:cookies 有效则复用(不弹浏览器),失效则浏览器自动化登录。 返回 {id, label, online, message} """ if pid not in _LOGIN_MODS: raise PlatformAuthError(f"未知平台: {pid}") result = _LOGIN_MODS[pid].ensure_login(force=False) ok = bool(result and result.get("success")) return {"id": pid, "label": _LABELS[pid], "online": ok, "message": (result or {}).get("message", "")} def logout(pid: str) -> dict: """登出平台:删除共享 cookies 文件,使该平台登录态失效。 返回 {id, label, online} """ if pid not in _COOKIE_DEFS: raise PlatformAuthError(f"未知平台: {pid}") path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"]) if os.path.exists(path): os.remove(path) return {"id": pid, "label": _LABELS[pid], "online": False} def build_session(pid: str) -> "requests.Session": """从共享 cookies 构建已登录 requests.Session(供插件调用 shared 数据模块)。 若登录态缺失则抛 PlatformAuthError,提示先登录。 """ if pid not in _COOKIE_DEFS: raise PlatformAuthError(f"未知平台: {pid}") path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"]) if not os.path.exists(path): raise PlatformAuthError( f"未找到 {_LABELS[pid]} 登录态({path}),请先在页面点击登录") with open(path, encoding="utf-8") as f: cookies = json.load(f) if not cookies: raise PlatformAuthError(f"{_LABELS[pid]} 登录态为空,请重新登录") session = requests.Session() session.headers.update({ "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", }) domain = _COOKIE_DEFS[pid]["domain"] injected: set = set() for c in cookies: if c.get("domain") and domain in c["domain"]: session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/")) injected.add(c["name"]) # 兜底:domain 未命中目标域名的 cookie(如别名域名),且 name 尚未注入时, # 按目标域名补注入,避免漏掉关键 cookie 导致接口鉴权失败。 for c in cookies: name = c.get("name") if name and name not in injected: session.cookies.set(name, c.get("value", ""), domain=domain, path=c.get("path", "/")) return session def get_user_id(pid: str) -> str: """获取平台用户 ID(HR 数据接口大多需要 user_id 参数)。""" if pid == "hr": session = build_session("hr") info = _seal.fetch_cur_user_info(session) return str(info.get("userId") or "") raise PlatformAuthError(f"平台 {pid} 暂不支持取 user_id")