feat: 新增HR纯接口登录OA接口探针及试用期变更流程增强
新增3个核心文件: 1. workflows/share/oa_login_api.py:OA纯接口登录模块,与浏览器版输出兼容 2. workflows/share/hr_login_api.py:HR纯接口登录模块,支持滑块验证,与浏览器版输出兼容 3. workflows/share/_probe_we_process_todo.py:HR WeProcess待办探针,验证替代OA待办+SSO链路 同时增强试用期变更流程: - 新增流程交叉验证逻辑,处理已被他人操作的情况 - 新增离职电子签详情链接获取逻辑 - 新增AI表格自动回填逻辑,处理无需处理的情况 - 新增流程待办查询接口,支持反查流程实例
This commit is contained in:
@@ -0,0 +1,314 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""探针(只读):验证「HR WeProcess.mc?method=getProcessAndData」能否替代 OA 待办接口 + SSO 解析。
|
||||
背景:XQ0003 请假 / XQ0004 加班 / XQ0020 改签离职电子签流程 三个审核流程目前链路为
|
||||
OA 待办(sysNotifyMainIndex.do, fdType=13) -> 详情链接 SSO 跳转解析(taskId/businessKey)
|
||||
-> WfActivity 取 formId -> WorkformEngine 取表单(SSO 后落地均在 hr.37du.co)。
|
||||
本探针验证:
|
||||
1) 仅用 hr_cookies.json 调 WeProcess 按标题关键字拉待办(不依赖 OA 登录态);
|
||||
2) 与 OA 待办接口同关键字结果做数量/标题一致性比对(验证 OA 与 HR 数据一致);
|
||||
3) 免 SSO 链路:WeProcess 返回的 taskId -> WfActivity 取 formId -> WorkformEngine
|
||||
getBusinessDate 取表单数据(全程纯 HR 接口),证明无需浏览器 SSO 解析。
|
||||
注意事项(实测结论):
|
||||
- WeProcess 响应结构为 {state, meg, total, isRecord, result, jsonList},数据在 jsonList;
|
||||
- 会话过期时 state=Nosession、meg=会话过期,需先运行 hr_login_api.py 刷新登录态。
|
||||
只读探针:不发审批、不写任何业务文件,仅控制台输出。
|
||||
运行:.venv\\Scripts\\python.exe workflows/share/_probe_we_process_todo.py
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
from datetime import datetime
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import requests
|
||||
|
||||
_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')
|
||||
HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
OA_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
OA_BASE_URL = "https://oa.37du.co"
|
||||
WE_PROCESS_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
|
||||
OA_TODO_URL = f"{OA_BASE_URL}/sys/notify/sys_notify_todo/sysNotifyMainIndex.do"
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
|
||||
# 三个审核流程的待办主题关键字(与各自 main() 中 run_flow(subject=...) 完全一致)
|
||||
SUBJECTS = ["请假", "加班", "改签离职电子签流程"]
|
||||
|
||||
PAGE_SIZE = 100
|
||||
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
|
||||
def _mtime(path):
|
||||
try:
|
||||
return datetime.fromtimestamp(os.path.getmtime(path)).strftime("%Y-%m-%d %H:%M:%S")
|
||||
except OSError:
|
||||
return "不存在"
|
||||
|
||||
|
||||
def load_cookies(path):
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
with open(path, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
def build_session(cookies, domain_keyword=None):
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": USER_AGENT,
|
||||
"X-Requested-With": "XMLHttpRequest"})
|
||||
for c in cookies or []:
|
||||
domain = c.get("domain") or ""
|
||||
if domain_keyword and domain_keyword not in domain:
|
||||
continue
|
||||
if domain:
|
||||
session.cookies.set(c["name"], c["value"], domain=domain, path=c.get("path", "/"))
|
||||
else:
|
||||
session.cookies.set(c["name"], c["value"])
|
||||
return session
|
||||
|
||||
|
||||
def _is_login_page(text):
|
||||
return bool(text) and ("login.jsp" in text or "j_username" in text)
|
||||
|
||||
|
||||
def _is_json(text):
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
def _row(row, *names):
|
||||
"""行字段多候选取值(兼容 jsonList 驼峰/下划线字段名)。"""
|
||||
for n in names:
|
||||
v = row.get(n)
|
||||
if v not in (None, ""):
|
||||
return v
|
||||
return ""
|
||||
|
||||
|
||||
# ==================== OA 侧:待办列表(现状链路) ====================
|
||||
def oa_todo_page(session, subject, page_no=1, page_size=PAGE_SIZE):
|
||||
params = {
|
||||
"method": "list", "dataType": "todo", "fdType": "13", "fdCateId": "",
|
||||
"q.s_raq": str(random.random()), "q.fdSubject": subject,
|
||||
"pageno": page_no, "rowsize": page_size, "pagingtype": "default",
|
||||
"orderby": "fdCreateTime", "ordertype": "down",
|
||||
}
|
||||
resp = session.get(f"{OA_TODO_URL}?{urlencode(params)}", timeout=20)
|
||||
text = resp.text or ""
|
||||
if _is_login_page(text):
|
||||
raise RuntimeError("OA 登录态失效(返回登录页)")
|
||||
if not _is_json(text):
|
||||
raise RuntimeError(f"OA 待办接口返回非 JSON(前 80 字符):{text[:80]}")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def oa_parse_rows(data):
|
||||
"""复刻 XQ0003 parse_todo_list:解析标题/发起人/时间/详情链接,跳过协作类待办。"""
|
||||
docs, skipped = [], 0
|
||||
for row in data.get("datas") or []:
|
||||
cells = {c.get("col"): (c.get("value") or "") for c in row if isinstance(c, dict)}
|
||||
title_raw = cells.get("todo.subject4View", "")
|
||||
match = re.search(r'<span class="subjecthead"[^>]*>(.*?)</span>', title_raw, re.DOTALL)
|
||||
title = match.group(1).strip() if match else re.sub(r'<[^>]+>', '', title_raw).strip()
|
||||
detail_url = cells.get("tr_href", "")
|
||||
if detail_url and not detail_url.startswith(("http://", "https://")):
|
||||
detail_url = OA_BASE_URL + detail_url
|
||||
if "kmCollaborateMain.do" in detail_url:
|
||||
skipped += 1
|
||||
continue
|
||||
docs.append({"title": title, "creator": cells.get("docCreatorName", ""),
|
||||
"time": cells.get("fdCreateTime", ""), "detail_url": detail_url})
|
||||
return docs, skipped
|
||||
|
||||
|
||||
def oa_fetch_all(session, subject):
|
||||
data = oa_todo_page(session, subject, page_no=1)
|
||||
total = int((data.get("page") or {}).get("totalSize") or 0)
|
||||
docs, skipped = oa_parse_rows(data)
|
||||
pages = (total + PAGE_SIZE - 1) // PAGE_SIZE if total else 1
|
||||
for p in range(2, min(pages, 20) + 1):
|
||||
data = oa_todo_page(session, subject, page_no=p)
|
||||
more, skip = oa_parse_rows(data)
|
||||
docs.extend(more)
|
||||
skipped += skip
|
||||
# 按详情链接去重(与现有 get_documents 口径一致)
|
||||
seen, unique = set(), []
|
||||
for d in docs:
|
||||
key = d.get("detail_url") or d.get("title")
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
unique.append(d)
|
||||
return unique, total, skipped
|
||||
|
||||
|
||||
# ==================== HR 侧:WeProcess 流程待办(候选新链路) ====================
|
||||
def hr_we_process_page(session, title, page_no=1, page_size=PAGE_SIZE):
|
||||
params = {
|
||||
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
|
||||
"struId": "", "rootId": "cq37du", "taskIds": "", "title": title,
|
||||
"state": "", "startTime": "", "endTime": "",
|
||||
"sortType": "desc", "sortName": "CREATE_TIME",
|
||||
"commonQuery": "[]", "start": "0", "pageNo": str(page_no), "pageSize": str(page_size),
|
||||
}
|
||||
resp = session.post(WE_PROCESS_URL, data=params, timeout=20)
|
||||
text = resp.text or ""
|
||||
if not _is_json(text):
|
||||
raise RuntimeError(f"WeProcess 返回非 JSON(HR 登录态可能失效,前 80 字符):{text[:80]}")
|
||||
d = resp.json()
|
||||
if str(d.get("state")) != "1":
|
||||
raise RuntimeError(f"WeProcess 返回失败 state={d.get('state')} meg={d.get('meg')}")
|
||||
return d
|
||||
|
||||
|
||||
def hr_fetch_all(session, title):
|
||||
rows, d, page_no = [], None, 1
|
||||
while page_no <= 20:
|
||||
d = hr_we_process_page(session, title, page_no=page_no)
|
||||
datas = d.get("jsonList") or d.get("datas") or []
|
||||
rows.extend(datas)
|
||||
if len(datas) < PAGE_SIZE:
|
||||
break
|
||||
page_no += 1
|
||||
total = d.get("total") if isinstance(d, dict) else None
|
||||
return rows, total
|
||||
|
||||
|
||||
# ==================== 免 SSO 链路验证:taskId -> formId -> 表单数据 ====================
|
||||
def wf_activity_form_id(session, task_id):
|
||||
resp = session.post(f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId",
|
||||
data={"taskId": task_id}, timeout=20)
|
||||
d = resp.json()
|
||||
if str(d.get("state")) != "1" and not d.get("formId"):
|
||||
raise RuntimeError(f"WfActivity 返回失败:{json.dumps(d, ensure_ascii=False)[:120]}")
|
||||
for src in [d] + [d.get(k) for k in ("data", "result") if isinstance(d.get(k), dict)]:
|
||||
for key in ("formId", "FormId", "form_id"):
|
||||
if src.get(key):
|
||||
return str(src[key])
|
||||
raise RuntimeError(f"WfActivity 未能提取 formId:{json.dumps(d, ensure_ascii=False)[:120]}")
|
||||
|
||||
|
||||
def business_data(session, business_key, form_id):
|
||||
resp = session.post(f"{WORKFORM_ENGINE_URL}?method=getBusinessDate",
|
||||
data={"businessKey": business_key, "formId": form_id}, timeout=20)
|
||||
d = resp.json()
|
||||
if str(d.get("state")) != "1" or not isinstance(d.get("result"), dict):
|
||||
raise RuntimeError(f"getBusinessDate 返回失败:{json.dumps(d, ensure_ascii=False)[:120]}")
|
||||
return d["result"]
|
||||
|
||||
|
||||
def _norm_title(s):
|
||||
return re.sub(r"\s+", "", str(s or ""))
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def main():
|
||||
print("=" * 72)
|
||||
print("探针:OA 待办 vs HR WeProcess 一致性 + 免 SSO 链路验证(只读)")
|
||||
print(f"hr_cookies.json 修改时间: {_mtime(HR_COOKIE_FILE)}")
|
||||
print(f"oa_cookies.json 修改时间: {_mtime(OA_COOKIE_FILE)}")
|
||||
|
||||
hr_cookies = load_cookies(HR_COOKIE_FILE)
|
||||
oa_cookies = load_cookies(OA_COOKIE_FILE)
|
||||
if not hr_cookies:
|
||||
print("[终止] 未找到 hr_cookies.json,请先运行「37duHR登录」")
|
||||
return 1
|
||||
hr = build_session(hr_cookies, domain_keyword="37du.co")
|
||||
oa = build_session(oa_cookies) if oa_cookies else None
|
||||
if oa is None:
|
||||
print("[提示] 未找到 oa_cookies.json,将只测 HR 侧,无法做 OA 一致性比对")
|
||||
|
||||
all_subjects_ok = True
|
||||
for idx, subject in enumerate(SUBJECTS, 1):
|
||||
print("=" * 72)
|
||||
print(f"[{idx}/{len(SUBJECTS)}] 主题关键字: {subject}")
|
||||
|
||||
# ---- OA 侧 ----
|
||||
oa_docs, oa_total, oa_skipped = [], None, 0
|
||||
if oa is not None:
|
||||
try:
|
||||
oa_docs, oa_total, oa_skipped = oa_fetch_all(oa, subject)
|
||||
print(f"OA 待办: 接口 total={oa_total},解析去重 {len(oa_docs)} 条"
|
||||
f"(跳过协作类 {oa_skipped} 条)")
|
||||
except RuntimeError as e:
|
||||
print(f"OA 待办拉取失败: {e}")
|
||||
|
||||
# ---- HR 侧 ----
|
||||
try:
|
||||
hr_rows, hr_total = hr_fetch_all(hr, subject)
|
||||
except RuntimeError as e:
|
||||
print(f"[HR失败] {e}")
|
||||
all_subjects_ok = False
|
||||
continue
|
||||
print(f"HR WeProcess: jsonList={len(hr_rows)} 条, total={hr_total}")
|
||||
|
||||
if not hr_rows:
|
||||
print(" (HR 返回空,无法比对)")
|
||||
all_subjects_ok = False
|
||||
continue
|
||||
|
||||
# 首行字段发现 + 状态类字段
|
||||
keys = sorted(hr_rows[0].keys())
|
||||
print(f"HR 行字段({len(keys)}): {','.join(keys)}")
|
||||
for k in ("state", "processState", "taskState", "currentState", "flowState"):
|
||||
vals = sorted({str(r.get(k)) for r in hr_rows if r.get(k) is not None})
|
||||
if vals:
|
||||
print(f" 字段 {k} 取值: {vals}")
|
||||
|
||||
# ---- 一致性比对 ----
|
||||
if oa_docs is not None and oa_total is not None:
|
||||
oa_map = {_norm_title(_row(d, "title")): d for d in oa_docs}
|
||||
hr_map = {}
|
||||
for r in hr_rows:
|
||||
t = _norm_title(_row(r, "title", "processTitle", "docSubject", "businessName"))
|
||||
if t:
|
||||
hr_map.setdefault(t, r)
|
||||
matched = set(oa_map) & set(hr_map)
|
||||
oa_only, hr_only = set(oa_map) - set(hr_map), set(hr_map) - set(oa_map)
|
||||
print(f"标题比对: OA {len(oa_map)} 条 vs HR {len(hr_map)} 条,"
|
||||
f"完全匹配 {len(matched)} 条;OA 独有 {len(oa_only)} 条,HR 独有 {len(hr_only)} 条")
|
||||
for t in list(oa_only)[:5]:
|
||||
print(f" [OA独有] {oa_map[t]['title']}(发起人 {oa_map[t]['creator']})")
|
||||
for t in list(hr_only)[:5]:
|
||||
r = hr_map[t]
|
||||
print(f" [HR独有] {_row(r, 'title')}(发起人 {_row(r, 'createUserName', 'createUserNameCn')})")
|
||||
if oa_only or hr_only:
|
||||
all_subjects_ok = False
|
||||
|
||||
# ---- 免 SSO 链路验证(最多 3 条)----
|
||||
chain_ok = chain_fail = 0
|
||||
for r in hr_rows[:3]:
|
||||
task_id = str(_row(r, "taskId", "task_id"))
|
||||
bk = str(_row(r, "businessKey", "business_key"))
|
||||
try:
|
||||
if not task_id:
|
||||
raise RuntimeError("行内无 taskId")
|
||||
form_id = wf_activity_form_id(hr, task_id)
|
||||
row_form = str(_row(r, "formId", "form_id"))
|
||||
result = business_data(hr, bk, form_id)
|
||||
chain_ok += 1
|
||||
agree = ("一致" if (not row_form or row_form == form_id)
|
||||
else f"与行内formId({row_form})不一致")
|
||||
print(f" [链路OK] {_row(r, 'title')} | taskId={task_id} -> formId={form_id}"
|
||||
f"({agree}) | 表单字段数={len(result)}")
|
||||
except Exception as e:
|
||||
chain_fail += 1
|
||||
print(f" [链路FAIL] {_row(r, 'title')} | taskId={task_id} businessKey={bk} | {e}")
|
||||
print(f"免SSO链路验证: 成功 {chain_ok} 条,失败 {chain_fail} 条")
|
||||
if chain_fail:
|
||||
all_subjects_ok = False
|
||||
|
||||
print("=" * 72)
|
||||
verdict = "三个主题均一致,免 SSO 链路可用" if all_subjects_ok else "存在差异/失败,见上方明细"
|
||||
print(f"探针结束。结论: {verdict}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,483 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: hr_login_api.py
|
||||
@Description: HR 纯接口登录(无浏览器版),「37duHR登录(接口版)」影刀自定义指令模块源码。
|
||||
与 workflows/share/hr_login.py(浏览器版)输出完全兼容:
|
||||
- 登录态落盘同一文件 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json;
|
||||
- cookies 结构一致(name/value/domain/path/...),各业务脚本零改动;
|
||||
- 对外入口 main(args) 与返回结构 {success, cookie_path, message, relogin} 一致。
|
||||
区别:全程 requests 接口完成登录(含滑块验证),不打开浏览器、无拖拽拟人。
|
||||
|
||||
登录链路(从登录页前端 JS 逆向 + 2025-10 实测验证):
|
||||
1. GET /RedseaPlatform/ 建立 Session 基础 cookie(routeEhr/JSESSIONID);
|
||||
2. GET /RedseaPlatform/captcha/get/verification/image.mob 取滑块图,返回
|
||||
result = {shadeImage(带缺口背景 jpg b64), originImage(原始背景 jpg b64),
|
||||
cutoutImage(55x55 拼图块 png b64), y(拼图块 top), x(恒 0)};
|
||||
前端 CSS 固定 340x171 容器、background 原尺寸绘制 => 浏览器只显示原图
|
||||
左上角 min(w,340) x min(h,171) 的窗口,坐标系 1:1,匹配前需先裁切到该窗口;
|
||||
3. 定位缺口 x:
|
||||
a) 首选 diff 法:|shadeImage - originImage| 最大连通域左边界 = 缺口 x
|
||||
(两图同源成对,diff 定位最准,且天然免疫整图变换);
|
||||
b) 兜底模板匹配法(与 hr_login.py 浏览器截图版同源算法);
|
||||
两者互验:diff 可信用 diff,diff 缺失用模板,分歧过大判定本图不可信换图重取;
|
||||
4. POST /RedseaPlatform/captcha/check/verification/result.mob?x=&y= 校验滑块(返回 true/false);
|
||||
5. POST /RedseaPlatform/j_red_security_check/PW 提交登录:
|
||||
form: MENU_TYPE=classic & sysCode=RedseaP & j_username & j_password=<AES密文> & x & y
|
||||
header: Csrf-Token: RP(前端写死常量);
|
||||
密码加密:AES-128-ECB + PKCS7,key='ps_uer_!@#BGYUJN'(前端硬编码),输出 base64;
|
||||
成功判定:state != "0";失败 state == "0" 且 meg 为错误信息;
|
||||
6. GET getCurUserInfo 校验会话有效后,cookies 落盘 hr_cookies.json。
|
||||
|
||||
配置(与 hr_login.py 一致,读共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env):
|
||||
hr_login_username=用户名
|
||||
hr_login_password=密码
|
||||
hr_validate_url=(可选)HR 会话校验接口 URL;默认使用 getCurUserInfo 接口
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install requests python-dotenv opencv-python numpy pycryptodome
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||||
python hr_login_api.py 独立运行(等价 main({"force": false}))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
import random
|
||||
import base64
|
||||
|
||||
import requests
|
||||
import cv2
|
||||
import numpy as np
|
||||
from Crypto.Cipher import AES
|
||||
from Crypto.Util.Padding import pad
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# ================== 共享路径(与 hr_login.py 统一) ==================
|
||||
_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')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
_load_shared_env()
|
||||
|
||||
# ================== 配置 ==================
|
||||
BASE_URL = 'https://hr.37du.co'
|
||||
LOGIN_URL = BASE_URL + '/RedseaPlatform/'
|
||||
CAPTCHA_GET_URL = BASE_URL + '/RedseaPlatform/captcha/get/verification/image.mob'
|
||||
CAPTCHA_CHECK_URL = BASE_URL + '/RedseaPlatform/captcha/check/verification/result.mob'
|
||||
LOGIN_POST_URL = BASE_URL + '/RedseaPlatform/j_red_security_check/PW'
|
||||
GET_CUR_USER_INFO_URL = BASE_URL + '/RedseaPlatform/PtUsers.mc?method=getCurUserInfo'
|
||||
|
||||
# 前端登录页硬编码:AES 密钥与 CSRF 常量
|
||||
AES_KEY = b'ps_uer_!@#BGYUJN'
|
||||
CSRF_TOKEN = 'RP'
|
||||
|
||||
USERNAME = os.getenv('hr_login_username', '')
|
||||
PASSWORD = os.getenv('hr_login_password', '')
|
||||
|
||||
# 浏览器可见窗口(登录页 CSS:.imgBg 340x171 固定、background 原尺寸绘制)
|
||||
VIEW_W = 340
|
||||
VIEW_H = 171
|
||||
|
||||
RETRY_MAX = 5 # 单轮滑块重试次数(与浏览器版一致)
|
||||
LOGIN_ROUND_MAX = 3 # 整轮登录最大重试(项目级重试机制)
|
||||
TIMEOUT = 15
|
||||
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化(格式与 hr_login.py 兼容) ==================
|
||||
def save_session_cookies(session):
|
||||
"""requests.Session cookies -> [{name, value, domain, path, expires}, ...],
|
||||
与 hr_login.py(DrissionPage page.cookies)落盘结构兼容,业务脚本零改动。"""
|
||||
cookies = []
|
||||
for c in session.cookies:
|
||||
cookies.append({
|
||||
"name": c.name,
|
||||
"value": c.value,
|
||||
"domain": c.domain,
|
||||
"path": c.path or "/",
|
||||
"expires": int(c.expires) if c.expires else None,
|
||||
})
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(与 hr_login.py 同款) ==================
|
||||
def _is_hr_session_valid():
|
||||
"""API 轻量校验 HR cookies:请求 hr_validate_url(默认 getCurUserInfo 接口),
|
||||
返回 JSON 视为 cookies 有效;返回登录页等非 JSON 即视为失效。"""
|
||||
validate_url = os.getenv('hr_validate_url', '').strip() or GET_CUR_USER_INFO_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": UA,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.post(validate_url, data={}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 密码加密(前端 pubAesEncrypt 等价实现) ==================
|
||||
def aes_encrypt_password(password):
|
||||
"""AES-128-ECB + PKCS7,key 前端硬编码,输出 base64(与 CryptoJS encrypted.toString() 一致)。"""
|
||||
cipher = AES.new(AES_KEY, AES.MODE_ECB)
|
||||
return base64.b64encode(cipher.encrypt(pad(password.encode('utf-8'), 16))).decode('ascii')
|
||||
|
||||
|
||||
# ================== 滑块图获取与裁切 ==================
|
||||
def new_session():
|
||||
"""建立会话:先访问登录页拿基础 cookie(routeEhr/JSESSIONID),验证码/登录绑定同一会话。"""
|
||||
s = requests.Session()
|
||||
s.headers.update({
|
||||
"User-Agent": UA,
|
||||
"Referer": LOGIN_URL,
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
})
|
||||
s.get(LOGIN_URL, timeout=TIMEOUT)
|
||||
return s
|
||||
|
||||
|
||||
def _b64_to_img(b64str, flag):
|
||||
"""base64 -> cv2 图像(失败返回 None)。"""
|
||||
if not b64str:
|
||||
return None
|
||||
try:
|
||||
buf = base64.b64decode(b64str)
|
||||
return cv2.imdecode(np.frombuffer(buf, np.uint8), flag)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _crop_view(img):
|
||||
"""裁切到浏览器可见窗口(左上角 min(w,340) x min(h,171)),坐标系与浏览器 1:1。"""
|
||||
if img is None:
|
||||
return None
|
||||
h, w = img.shape[:2]
|
||||
return img[:min(h, VIEW_H), :min(w, VIEW_W)]
|
||||
|
||||
|
||||
def get_captcha(session):
|
||||
"""取滑块图,返回 dict(shade, origin, cutout, y);y 为拼图块 top(服务端给定)。"""
|
||||
resp = session.get(CAPTCHA_GET_URL, timeout=TIMEOUT)
|
||||
data = resp.json()
|
||||
res = data.get("result") or {}
|
||||
shade = _crop_view(_b64_to_img(res.get("shadeImage"), cv2.IMREAD_COLOR))
|
||||
origin = _crop_view(_b64_to_img(res.get("originImage"), cv2.IMREAD_COLOR))
|
||||
cutout = _b64_to_img(res.get("cutoutImage"), cv2.IMREAD_UNCHANGED)
|
||||
y = int(res.get("y") or 0)
|
||||
return {"shade": shade, "origin": origin, "cutout": cutout, "y": y}
|
||||
|
||||
|
||||
# ================== 缺口定位 ==================
|
||||
def locate_by_diff(shade, origin):
|
||||
"""diff 法:shade/origin 同源成对,逐像素差异的最大连通域左边界 = 缺口 x。
|
||||
返回 (x, 可信度);不可信返回 (None, 原因)。"""
|
||||
if shade is None or origin is None or shade.shape != origin.shape:
|
||||
return None, "图片缺失或尺寸不一致"
|
||||
diff = cv2.absdiff(shade, origin).max(axis=2)
|
||||
mask = (diff > 30).astype(np.uint8) * 255
|
||||
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
|
||||
n, _, stats, _ = cv2.connectedComponentsWithStats(mask)
|
||||
if n <= 1:
|
||||
return None, "无差异区域"
|
||||
best = max(range(1, n), key=lambda i: stats[i, cv2.CC_STAT_AREA])
|
||||
area = int(stats[best, cv2.CC_STAT_AREA])
|
||||
x = int(stats[best, cv2.CC_STAT_LEFT])
|
||||
# 缺口约 55x55(面积 ~3000),过大/过小视为 jpg 噪声或异常
|
||||
if area < 300 or area > 12000:
|
||||
return None, f"差异区域面积异常({area})"
|
||||
return x, f"diff(area={area})"
|
||||
|
||||
|
||||
def match_slider_dual(bg_img, slider_color):
|
||||
"""模板匹配滑块缺口,返回物理距离 px。
|
||||
算法与 hr_login.py 浏览器截图版同源(边缘 Canny + TM_CCOEFF_NORMED + 白区加权)。"""
|
||||
if bg_img is None or slider_color is None:
|
||||
return None
|
||||
bg_h, bg_w = bg_img.shape[:2]
|
||||
x_offset = 0
|
||||
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
|
||||
alpha = slider_color[:, :, 3]
|
||||
slider_rgb = slider_color[:, :, :3]
|
||||
ys, xs = np.where(alpha > 0)
|
||||
if len(ys) > 0:
|
||||
y_min, y_max = np.min(ys), np.max(ys)
|
||||
x_min, x_max = np.min(xs), np.max(xs)
|
||||
slider_rgb = slider_rgb[y_min:y_max + 1, x_min:x_max + 1]
|
||||
x_offset, _ = x_min, np.min(ys)
|
||||
else:
|
||||
slider_rgb = slider_color[:, :, :3] if len(slider_color.shape) == 3 else slider_color
|
||||
|
||||
s_h, s_w = slider_rgb.shape[:2]
|
||||
if s_h <= 0 or s_w <= 0 or s_w >= bg_w or s_h >= bg_h:
|
||||
return None
|
||||
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
gray_slider = cv2.GaussianBlur(cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
bg_edges = cv2.Canny(gray_bg, 50, 150)
|
||||
slider_edges = cv2.Canny(gray_slider, 50, 150)
|
||||
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
|
||||
|
||||
candidates = []
|
||||
temp_result = result.copy()
|
||||
for _ in range(6):
|
||||
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
|
||||
if max_val < 0.03:
|
||||
break
|
||||
candidates.append((max_val, max_loc))
|
||||
y0 = max(0, max_loc[1] - s_h // 2); y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
|
||||
x0 = max(0, max_loc[0] - s_w // 2); x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
|
||||
temp_result[y0:y1, x0:x1] = -2.0
|
||||
if not candidates:
|
||||
return None
|
||||
|
||||
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
|
||||
|
||||
def region_whiteness(x, y, w, h):
|
||||
roi = bg_img[y:y + h, x:x + w]
|
||||
if roi.size == 0:
|
||||
return 0.0
|
||||
return float(np.all(roi > 200, axis=2).mean())
|
||||
|
||||
scored = []
|
||||
for val, loc in candidates:
|
||||
x, y = loc
|
||||
if x <= s_w or x > right_limit:
|
||||
continue
|
||||
scored.append((val + 0.5 * region_whiteness(x, y, s_w, s_h), val, loc))
|
||||
if scored:
|
||||
scored.sort(key=lambda t: t[0], reverse=True)
|
||||
best_loc = scored[0][2]
|
||||
else:
|
||||
best_loc = candidates[0][1]
|
||||
|
||||
distance = best_loc[0] - x_offset
|
||||
if distance < 0:
|
||||
distance = 0
|
||||
if distance + s_w > bg_w:
|
||||
distance = bg_w - s_w
|
||||
return distance
|
||||
|
||||
|
||||
def solve_distance(cap):
|
||||
"""定位缺口并输出应提交的 x(= 滑块从 0 到缺口的距离,即缺口左边界 - 拼图透明边)。
|
||||
返回 (x, 说明);本图不可信返回 (None, 原因)。
|
||||
|
||||
几何说明(与浏览器画面一致):
|
||||
- 原图宽 >= 340:浏览器只显示左上 340x171 裁切窗口;
|
||||
- 原图宽 < 340:.imgBg 的 background 默认 repeat 会把原图复制拼接到右侧,
|
||||
画面上缺口可能出现副本(x_g 与 x_g+原图宽),但服务端记录的是原图缺口
|
||||
坐标 x_g,提交 x_g 即可通过;
|
||||
因此匹配始终在原图(裁切后)上进行——拼接成画面等价图反而会让 diff 出双峰
|
||||
(副本也带缺口)——越界过滤上限用实际图宽。
|
||||
"""
|
||||
shade = cap["shade"]
|
||||
cutout = cap["cutout"]
|
||||
s_w = cutout.shape[1] if cutout is not None else 55
|
||||
view_w = shade.shape[1] if shade is not None else VIEW_W
|
||||
x_diff, info = locate_by_diff(cap["shade"], cap["origin"])
|
||||
x_tpl = match_slider_dual(cap["shade"], cutout)
|
||||
print(f" 缺口定位:{info} diff_x={x_diff} tpl_x={x_tpl}")
|
||||
|
||||
x, how = None, "无法定位"
|
||||
if x_diff is not None and x_tpl is not None and abs(x_diff - x_tpl) <= 12:
|
||||
x, how = x_diff, "diff+tpl 一致"
|
||||
elif x_diff is not None:
|
||||
x, how = x_diff, "仅 diff(与模板分歧)"
|
||||
elif x_tpl is not None:
|
||||
x, how = x_tpl, "仅模板"
|
||||
if x is None:
|
||||
return None, how
|
||||
# 合理性校验:缺口不会贴最左/最右(贴边缺口可能是平铺坐标映射产物,直接换图)
|
||||
if x <= s_w or x > view_w - s_w:
|
||||
return None, f"缺口位置越界({x}, 图宽{view_w})"
|
||||
return x, how
|
||||
|
||||
|
||||
# ================== 滑块校验与登录提交 ==================
|
||||
def check_slider(session, x, y):
|
||||
"""提交滑块校验,返回 True/False。"""
|
||||
resp = session.post(CAPTCHA_CHECK_URL, params={"x": int(round(x)), "y": int(y)}, timeout=TIMEOUT)
|
||||
try:
|
||||
return bool(resp.json())
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def submit_login(session, username, password, x, y):
|
||||
"""提交登录,返回 (ok, message)。"""
|
||||
form = {
|
||||
"MENU_TYPE": "classic",
|
||||
"sysCode": "RedseaP",
|
||||
"j_username": username,
|
||||
"j_password": aes_encrypt_password(password),
|
||||
"x": int(round(x)),
|
||||
"y": int(y),
|
||||
}
|
||||
headers = {"Csrf-Token": CSRF_TOKEN}
|
||||
resp = session.post(LOGIN_POST_URL, data=form, headers=headers, timeout=TIMEOUT)
|
||||
try:
|
||||
result = resp.json()
|
||||
except Exception:
|
||||
return False, f"登录响应非 JSON(HTTP {resp.status_code})"
|
||||
if result.get("state") == "0":
|
||||
return False, str(result.get("meg") or "登录失败")
|
||||
return True, "登录成功"
|
||||
|
||||
|
||||
def do_login_api(username, password):
|
||||
"""完整接口登录:滑块校验(带重试)+ 提交登录。成功返回 True。"""
|
||||
for rnd in range(LOGIN_ROUND_MAX):
|
||||
print(f"--- 第 {rnd + 1} 轮登录(接口版) ---")
|
||||
try:
|
||||
session = new_session()
|
||||
except Exception as e:
|
||||
print(f"建立会话异常:{e}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
for attempt in range(RETRY_MAX):
|
||||
print(f"--- 第 {attempt + 1} 次尝试验证 ---")
|
||||
try:
|
||||
cap = get_captcha(session)
|
||||
except Exception as e:
|
||||
print(f"取验证码图异常:{e}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
shade = cap["shade"]
|
||||
y = cap["y"]
|
||||
# y 用实际图高校验(裁切窗口高 = min(图高, 171),小图场景更严谨)
|
||||
if shade is None or not (0 <= y <= shade.shape[0] - 55):
|
||||
print(f"验证码图异常(shade={None if shade is None else shade.shape}, y={y})")
|
||||
time.sleep(0.5)
|
||||
continue
|
||||
|
||||
x, info = solve_distance(cap)
|
||||
if x is None:
|
||||
time.sleep(random.uniform(0.3, 0.8))
|
||||
continue
|
||||
|
||||
print(f" 提交滑块校验 x={x} y={y}({info})")
|
||||
if check_slider(session, x, y):
|
||||
print(" 滑块校验通过")
|
||||
ok, msg = submit_login(session, username, password, x, y)
|
||||
if ok:
|
||||
save_session_cookies(session)
|
||||
return True
|
||||
print(f"登录失败:{msg}")
|
||||
return False # 账号密码类错误,重试无意义
|
||||
else:
|
||||
print(" 滑块校验未通过,换图重试")
|
||||
time.sleep(random.uniform(0.5, 1.2))
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主入口(与 hr_login.py 同构) ==================
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 HR 登录态并缓存 cookies(纯接口,无浏览器)。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
_set_login_state(False)
|
||||
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(hr_login_username / hr_login_password 未配置)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需登录)
|
||||
if not force and _is_hr_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 HR 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok = do_login_api(USERNAME, PASSWORD)
|
||||
if ok:
|
||||
# 登录后校验一次会话有效性,确保落盘的 cookies 可用
|
||||
if _is_hr_session_valid():
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录接口返回成功但会话校验未通过", "relogin": False}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败(滑块验证未通过或接口异常)", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37duHR登录(接口版)」调用入口。
|
||||
args: dict,可选字段 force(bool) 是否强制重新登录
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main({"force": False})
|
||||
print("最终结果:", result)
|
||||
@@ -0,0 +1,319 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: oa_login_api.py
|
||||
@Description: OA 纯接口登录(无浏览器版),「37duOA登录(接口版)」影刀自定义指令模块源码。
|
||||
与 workflows/share/oa_login.py(浏览器版)输出完全兼容:
|
||||
- 登录态落盘同一文件 %LOCALAPPDATA%\\37duAutomation\\.sessions\\oa_cookies.json;
|
||||
- cookies 结构一致(name/value/domain/path/...),各业务脚本零改动;
|
||||
- 配置读取一致(共享 .env 的 oa_login_username / oa_login_password);
|
||||
- 对外入口 main(force) 与返回结构 {success, cookie_path, message, relogin} 一致。
|
||||
区别:全程 requests 接口完成登录,不打开浏览器。
|
||||
|
||||
登录链路(蓝凌 EKP security.js 逆向 + 2026-10 实测验证):
|
||||
1. GET /login.jsp 建立 Session 基础 cookie(SESSION/sl-session);
|
||||
2. GET /resource/js/session.jsp?_=时间戳 服务端按会话下发密钥串:
|
||||
window.getSessionId = function(){ return "<36位UUID>"; }
|
||||
同一会话内固定,登录 POST 必须与本次取密钥同会话;
|
||||
3. 密码加密(复刻 security.js desEncrypt 的 des 分支,浏览器默认走 sm2 分支,
|
||||
但密文前缀带算法标记、服务端按标记选算法解密,des 同样受支持):
|
||||
a) 密钥串不足 16 位补 "abcdefghijklmnopqrstuvwxyz",再 toUpperCase;
|
||||
b) key = 前 8 字符 toHexString、iv = 第 8~16 字符 toHexString
|
||||
(toHexString = 逐字符 charCode 转 16 进制拼接,ASCII 即 .encode().hex());
|
||||
c) DES-CBC + PKCS7 加密密码,输出 base64;
|
||||
d) j_password = 标记前缀 "\\u4445\\u5320\\u4d45" + base64 密文;
|
||||
4. POST /j_acegi_security_check form: j_username & j_password & j_redirectto(空)
|
||||
成功 302 跳转(实测跳 "/",浏览器端再由前端跳 /sys/portal/page.jsp);
|
||||
5. GET sysNotifyTodo.do?method=sumTodoCount 校验会话有效后,cookies 落盘 oa_cookies.json
|
||||
(返回 JSON 视为有效,被重定向回登录页返回 HTML 即失效)。
|
||||
|
||||
配置(与 oa_login.py 一致,读共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env):
|
||||
oa_login_username=用户名
|
||||
oa_login_password=密码
|
||||
oa_validate_url=(可选)OA 会话校验接口 URL;默认使用 sumTodoCount 待办统计接口
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install requests python-dotenv pycryptodome
|
||||
|
||||
入口:
|
||||
python oa_login_api.py 独立运行(等价 main(force=True))
|
||||
main(force) 影刀自定义指令调用入口,force 传 True/False,返回 JSON 安全 dict
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import json
|
||||
import time
|
||||
import base64
|
||||
|
||||
import requests
|
||||
from Crypto.Cipher import DES
|
||||
from Crypto.Util.Padding import pad
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# ================== 共享路径(与 oa_login.py 统一) ==================
|
||||
_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')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
_load_shared_env()
|
||||
|
||||
# ================== 配置 ==================
|
||||
BASE_URL = 'https://oa.37du.co'
|
||||
LOGIN_URL = BASE_URL + '/login.jsp'
|
||||
SESSION_KEY_URL = BASE_URL + '/resource/js/session.jsp'
|
||||
LOGIN_POST_URL = BASE_URL + '/j_acegi_security_check'
|
||||
|
||||
# OA 会话校验接口:cookies 有效时返回 JSON,失效时被重定向到登录页返回 HTML
|
||||
TODO_COUNT_URL = BASE_URL + "/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
|
||||
USERNAME = os.getenv('oa_login_username', '')
|
||||
PASSWORD = os.getenv('oa_login_password', '')
|
||||
|
||||
# security.js 密码加密常量(逆向自 /resource/js/security.js,Dean Edwards packer 混淆已还原)
|
||||
DES_MARKER = "\u4445\u5320\u4d45" # des 分支密文标记前缀(服务端按标记选算法)
|
||||
DES_PADDING = "abcdefghijklmnopqrstuvwxyz" # 密钥串不足 16 位时的补齐串
|
||||
SESSION_KEY_RE = re.compile(
|
||||
r'getSessionId\s*=\s*function\s*\(\s*\)\s*\{\s*return\s*"([^"]*)"')
|
||||
|
||||
LOGIN_ROUND_MAX = 3 # 整轮登录最大重试(项目级重试机制)
|
||||
TIMEOUT = 15
|
||||
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化(格式与 oa_login.py 兼容) ==================
|
||||
def save_session_cookies(session):
|
||||
"""requests.Session cookies -> [{name, value, domain, path, expires}, ...],
|
||||
与 oa_login.py(DrissionPage page.cookies)落盘结构兼容,业务脚本零改动。"""
|
||||
cookies = []
|
||||
for c in session.cookies:
|
||||
cookies.append({
|
||||
"name": c.name,
|
||||
"value": c.value,
|
||||
"domain": c.domain,
|
||||
"path": c.path or "/",
|
||||
"expires": int(c.expires) if c.expires else None,
|
||||
})
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== 会话校验(与 oa_login.py 同款逻辑) ==================
|
||||
def _is_todo_count_json(resp):
|
||||
"""sumTodoCount 响应判定:200 且返回 JSON 视为登录态有效。"""
|
||||
try:
|
||||
return (resp.status_code == 200 and bool(resp.text)
|
||||
and resp.text.lstrip().startswith(("{", "[")))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _is_oa_session_valid():
|
||||
"""API 轻量校验 OA cookies:请求 oa_validate_url(默认 sumTodoCount 待办统计接口),
|
||||
返回 JSON 视为 cookies 有效;被重定向到登录页返回 HTML 即视为失效。
|
||||
与 oa_login.py 及业务脚本使用同一套接口与校验逻辑。"""
|
||||
validate_url = os.getenv('oa_validate_url', '').strip() or TODO_COUNT_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": UA,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.get(validate_url, params={"method": "sumTodoCount"}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
return _is_todo_count_json(resp)
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
def check_session_alive(session):
|
||||
"""用当前登录会话直接校验(登录后、落盘前使用)。"""
|
||||
validate_url = os.getenv('oa_validate_url', '').strip() or TODO_COUNT_URL
|
||||
try:
|
||||
resp = session.get(validate_url, params={"method": "sumTodoCount"}, timeout=15)
|
||||
return _is_todo_count_json(resp)
|
||||
except Exception as e:
|
||||
print(f"会话校验异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 密码加密(复刻 security.js desEncrypt 的 des 分支) ==================
|
||||
def to_hex_str(text):
|
||||
"""复刻 security.js 的 toHexString:逐字符 charCode 转 16 进制(小写、无补零)拼接。"""
|
||||
return ''.join(format(ord(ch), 'x') for ch in text)
|
||||
|
||||
|
||||
def fetch_session_key(session):
|
||||
"""GET session.jsp 取服务端按会话下发的密钥串(同会话固定)。"""
|
||||
url = f"{SESSION_KEY_URL}?_={int(time.time() * 1000)}"
|
||||
resp = session.get(url, timeout=TIMEOUT)
|
||||
m = SESSION_KEY_RE.search(resp.text)
|
||||
return m.group(1) if m else ""
|
||||
|
||||
|
||||
def des_encrypt_password(session, password):
|
||||
"""返回可直接提交的 j_password:标记前缀 + DES-CBC-PKCS7 base64 密文。
|
||||
密钥派生:密钥串不足 16 位补齐 -> 大写 -> key/iv 各取 8 字符 toHexString。"""
|
||||
sid = fetch_session_key(session)
|
||||
if not sid:
|
||||
raise RuntimeError("session.jsp 未返回 getSessionId 密钥串")
|
||||
b = sid
|
||||
if len(b) < 16:
|
||||
b += DES_PADDING
|
||||
b = b.upper()
|
||||
key = bytes.fromhex(to_hex_str(b[:8]))
|
||||
iv = bytes.fromhex(to_hex_str(b[8:16]))
|
||||
cipher = DES.new(key, DES.MODE_CBC, iv)
|
||||
ct = base64.b64encode(cipher.encrypt(pad(password.encode('utf-8'), 8))).decode('ascii')
|
||||
return DES_MARKER + ct
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def new_session():
|
||||
"""建立会话:先访问登录页拿基础 cookie(SESSION/sl-session),取密钥与登录绑定同一会话。"""
|
||||
s = requests.Session()
|
||||
s.headers.update({"User-Agent": UA})
|
||||
s.get(LOGIN_URL, timeout=TIMEOUT)
|
||||
return s
|
||||
|
||||
|
||||
def do_login_api(username, password):
|
||||
"""完整接口登录:取密钥 -> DES 加密 -> 表单提交 -> 会话校验。返回 (ok, message)。"""
|
||||
for rnd in range(LOGIN_ROUND_MAX):
|
||||
print(f"--- 第 {rnd + 1} 轮登录(接口版) ---")
|
||||
try:
|
||||
session = new_session()
|
||||
except Exception as e:
|
||||
print(f"建立会话异常:{e}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
try:
|
||||
j_password = des_encrypt_password(session, password)
|
||||
except Exception as e:
|
||||
print(f"获取会话密钥/加密异常:{e}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
try:
|
||||
resp = session.post(
|
||||
LOGIN_POST_URL,
|
||||
data={"j_username": username, "j_password": j_password, "j_redirectto": ""},
|
||||
headers={"Referer": LOGIN_URL, "Origin": BASE_URL},
|
||||
timeout=TIMEOUT, allow_redirects=True)
|
||||
except Exception as e:
|
||||
print(f"提交登录异常:{e}")
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
final_url = str(resp.url)
|
||||
if "login.jsp" in final_url:
|
||||
# Acegi 拒绝(凭据错误/解密失败)会重定向回登录页,重试无意义
|
||||
return False, f"登录被拒绝(用户名或密码错误?):{final_url}"
|
||||
if check_session_alive(session):
|
||||
save_session_cookies(session)
|
||||
return True, "登录成功"
|
||||
print(f"登录后会话校验未通过,最终URL:{final_url}")
|
||||
time.sleep(1)
|
||||
return False, "登录失败(重试耗尽或接口异常)"
|
||||
|
||||
|
||||
# ================== 登录主入口(与 oa_login.py 同构) ==================
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 OA 登录态并缓存 cookies(纯接口,无浏览器)。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
_set_login_state(False)
|
||||
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(oa_login_username / oa_login_password 未配置)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需登录)
|
||||
if not force and _is_oa_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 OA 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok, msg = do_login_api(USERNAME, PASSWORD)
|
||||
if ok:
|
||||
# 登录后校验一次落盘 cookies 可用性,确保业务脚本拿到的登录态真实有效
|
||||
if _is_oa_session_valid():
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录接口返回成功但会话校验未通过", "relogin": False}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE, "message": msg, "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口(与 oa_login.py 契约一致) ==================
|
||||
def main(force=True):
|
||||
"""
|
||||
影刀自定义指令「37duOA登录(接口版)」调用入口。
|
||||
force: bool 是否强制重新登录(默认 True,便于本地独立运行直接刷新登录态)
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main(force=True)
|
||||
print("最终结果:", result)
|
||||
Reference in New Issue
Block a user