fix: 会话失效时自动重新登录,管理端可改判断依据

This commit is contained in:
Nixevol
2026-11-21 14:39:56 +08:00
parent 4d4fe224bc
commit a6306e8339
7 changed files with 204 additions and 19 deletions
+2
View File
@@ -78,6 +78,7 @@ class AdminStudySettingsBody(BaseModel):
port: int | None = None
username: str = ""
password: str | None = None
hours_source: str | None = None
def require_admin(request: Request, db: Session = Depends(get_db)) -> str:
@@ -208,6 +209,7 @@ def put_users_study_settings(
port=body.port,
username=body.username,
password=body.password,
hours_source=body.hours_source,
)
+13
View File
@@ -102,6 +102,8 @@ def list_users(db: Session) -> list[dict]:
"hours_month": account.hours_month or "",
"study_active": work_running(account.employee_id),
"state": str(live.get("state") or ""),
"message": str(live.get("message") or ""),
"hours_met": control["hours_met"],
}
)
return rows
@@ -364,7 +366,10 @@ def set_study_action(db: Session, employee_ids: list[str], action: str) -> dict:
db.commit()
if kind == "start":
from euniv.autostudy import clear_study_hold
for account in accounts:
clear_study_hold(account.employee_id)
sync_work(account.employee_id)
else:
for account in accounts:
@@ -387,8 +392,14 @@ def set_study_settings(
port: object = None,
username: str = "",
password: str | None = None,
hours_source: str | None = None,
) -> dict:
accounts = _accounts_by_ids(db, employee_ids)
chosen_source = None
if hours_source is not None:
chosen_source = str(hours_source).strip().lower()
if chosen_source not in {"api", "history"}:
raise HTTPException(status_code=400, detail="学时判断须为官方统计或历史统计")
if monthly_target is not None:
if not isinstance(monthly_target, int) or isinstance(monthly_target, bool) or not 0 <= monthly_target <= 9999:
raise HTTPException(status_code=400, detail="每月学时目标须为 0 到 9999 的整数")
@@ -403,6 +414,8 @@ def set_study_settings(
account.study_schedule_enabled = bool(schedule_enabled)
if workers is not None:
apply_workers(account, workers)
if chosen_source is not None:
account.hours_source = chosen_source
if scheme is not None:
apply(account, scheme, host, port, username, password)
except (StudyWindowError, CourseWorkersError, ProxyError) as exc:
+48 -17
View File
@@ -1828,23 +1828,51 @@ def _stored_credential(employee_id: str) -> dict:
return data if isinstance(data, dict) else {}
def _login_direct_client(client: EunivClient, employee_id: str, password: str
) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None, str]:
from euniv.client import LoginRejected, ManualJigsaw
_login_notes: dict[str, str] = {}
def _remember_login_note(employee_id: str, message: str) -> None:
text = " ".join(str(message or "").split())
if len(text) > 80:
text = text[:80]
_login_notes[employee_id] = text or "自动重新登录没有成功"
def _take_login_note(employee_id: str) -> str:
return _login_notes.pop(employee_id, "")
def _relogin(client: EunivClient, employee_id: str, password: str, proxy: str | None
) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None, str]:
"""保存的会话打不开学习页时,用账号密码再登一次。"""
from euniv.client import LoginRejected, ManualJigsaw, is_qr_password
from euniv.db import SessionLocal
from euniv.service import _persist
if not password:
return "", "", "", [], None, "expired"
if not password or is_qr_password(password):
_remember_login_note(employee_id, "扫码登录已失效,请重新扫码登录")
return "", "", "", [], proxy, "expired"
try:
profile = client.login(manual=False)
with SessionLocal() as db:
_persist(db, employee_id, password, client, profile)
log.info("用户 %s 直连复查确认凭据已失效,已用本机网络重新登录", employee_id)
return _session_export(client, None)
_take_login_note(employee_id)
log.info("用户 %s 登录已失效,已自动重新登录", employee_id)
return _session_export(client, proxy)
except (SessionExpired, LoginRejected, ManualJigsaw, RuntimeError) as exc:
log.warning("用户 %s 直连重新登录失败: %s", employee_id, exc)
return "", "", "", [], None, "expired"
log.warning("用户 %s 自动重新登录失败: %s", employee_id, exc)
if isinstance(exc, LoginRejected):
_remember_login_note(employee_id, "账号或密码错误")
elif isinstance(exc, ManualJigsaw):
_remember_login_note(employee_id, "自动登录没有通过验证码")
else:
_remember_login_note(employee_id, str(exc) or "自动重新登录没有成功")
return "", "", "", [], proxy, "expired"
def _login_direct_client(client: EunivClient, employee_id: str, password: str
) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None, str]:
return _relogin(client, employee_id, password, None)
def _continue_direct(employee_id: str, password: str
@@ -1864,9 +1892,13 @@ def _continue_direct(employee_id: str, password: str
log.warning("用户 %s 直连复查凭据失败: %s", employee_id, exc)
return "", "", "", [], None, "network"
if alive:
client._ensure_site()
log.info("用户 %s 凭据经直连复查仍然有效,改为直连继续,不重新登录", employee_id)
return _session_export(client, None)
try:
client._ensure_site()
except SessionExpired:
alive = False
else:
log.info("用户 %s 凭据经直连复查仍然有效,改为直连继续,不重新登录", employee_id)
return _session_export(client, None)
return _login_direct_client(client, employee_id, password)
finally:
client.close()
@@ -1886,15 +1918,13 @@ def _prepare_session(employee_id: str, password: str,
try:
client.restore(credential)
if not client.credential_alive():
if use_pool and current:
return _continue_direct(employee_id, password)
return "", "", "", [], current, "expired"
raise SessionExpired("学习平台登录已失效")
client._ensure_site()
return _session_export(client, current)
except SessionExpired:
if use_pool and current:
return _continue_direct(employee_id, password)
return "", "", "", [], current, "expired"
return _relogin(client, employee_id, password, current)
except Exception as exc:
log.warning("用户 %s 准备会话失败: %s", employee_id, exc)
if use_pool and current and is_proxy_failure(exc):
@@ -2171,9 +2201,10 @@ class AutoStudyWorker:
return
if not token:
if reason == "expired":
_set_user_status(employee_id, state="会话失效", message="请重新登录")
_set_user_status(employee_id, state="会话失效", message=_take_login_note(employee_id) or "请重新登录")
log.info("用户 %s 需要重新登录", employee_id)
else:
_take_login_note(employee_id)
_set_user_status(employee_id, state="学习失败", message="无法连接学习平台")
log.info("用户 %s 无法连接学习平台", employee_id)
return
+25
View File
@@ -527,6 +527,8 @@ def test_check_skips_empty_credential_and_updates_saved_one(monkeypatch) -> None
"hours_month",
"study_active",
"state",
"message",
"hours_met",
}
assert saved["has_credential"] is True
assert saved["refresh_paused"] is False
@@ -985,6 +987,29 @@ def test_admin_can_save_study_settings_in_one_request() -> None:
assert one["proxy"] == "HTTP 9.9.9.9:8080"
def test_admin_can_set_account_hours_source() -> None:
_add_account("source-user")
_add_account("other-user")
api = _app()
client = TestClient(api.app)
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
saved = client.put(
"/api/admin/users/study-settings",
json={"employee_ids": ["source-user"], "hours_source": "history"},
)
assert saved.status_code == 200
listed = client.get("/api/admin/users").json()
one = next(item for item in listed if item["employee_id"] == "source-user")
other = next(item for item in listed if item["employee_id"] == "other-user")
assert one["hours_source"] == "history"
assert other["hours_source"] == "api"
bad = client.put(
"/api/admin/users/study-settings",
json={"employee_ids": ["source-user"], "hours_source": "other"},
)
assert bad.status_code == 400
def test_admin_can_switch_hours_source() -> None:
api = _app()
client = TestClient(api.app)
+55
View File
@@ -1505,3 +1505,58 @@ def test_progress_updates_do_not_call_into_the_page_connections(monkeypatch) ->
halt_work("u-quiet")
assert seen == [("u-quiet", True)]
_clear_user_status("u-quiet")
def test_dead_saved_session_logs_in_again(monkeypatch) -> None:
from euniv.autostudy import _prepare_session
from euniv.client import SessionExpired
logins: list[bool] = []
class _Jar:
def __iter__(self):
return iter(())
class _Client:
def __init__(self, *_args, **_kwargs) -> None:
self.client = type("HTTP", (), {"cookies": type("Cookies", (), {"jar": _Jar()})()})()
self._profile = {"userId": "u", "accountId": "a"}
def restore(self, _credential: dict) -> None:
return None
def credential_alive(self) -> bool:
return False
def _ensure_site(self) -> str:
raise AssertionError("失效会话不应再打开学习页")
def login(self, manual: bool = False) -> dict:
logins.append(manual)
return {"token": "new"}
def session_token(self) -> str:
return "yxt-new"
def close(self) -> None:
return None
monkeypatch.setattr("euniv.autostudy.EunivClient", _Client)
monkeypatch.setattr("euniv.service._persist", lambda *_args, **_kwargs: None)
token, _user, _org, _cookies, _proxy, reason = _prepare_session("u1", "secret", {"yxt_token": "old"}, None, False)
assert logins == [False]
assert token == "yxt-new"
assert reason == ""
class _SiteDead(_Client):
def credential_alive(self) -> bool:
return True
def _ensure_site(self) -> str:
raise SessionExpired("授权失败")
monkeypatch.setattr("euniv.autostudy.EunivClient", _SiteDead)
token, _user, _org, _cookies, _proxy, reason = _prepare_session("u1", "secret", {"yxt_token": "old"}, None, False)
assert logins == [False, False]
assert token == "yxt-new"
assert reason == ""
+47 -2
View File
@@ -36,6 +36,8 @@ interface UserRow {
hours_month: string;
study_active: boolean | null;
study_state: string;
study_message: string;
hours_met: boolean;
}
interface SecretField {
@@ -68,6 +70,7 @@ const startHour = ref<number | null>(0);
const startMinute = ref<number | null>(0);
const startSecond = ref<number | null>(0);
const scheduleChoice = ref<"keep" | "on" | "off">("keep");
const hoursChoice = ref<"keep" | "api" | "history">("keep");
const workersValue = ref<number | null>(1);
const proxyScheme = ref("keep");
const settingsReady = ref(false);
@@ -116,6 +119,7 @@ interface SettingsBaseline {
startMinute: number | null;
startSecond: number | null;
scheduleChoice: "keep" | "on" | "off";
hoursChoice: "keep" | "api" | "history";
workers: number | null;
scheme: string;
host: string;
@@ -196,6 +200,8 @@ function asUser(value: unknown): UserRow | null {
hours_month: textOf(value.hours_month),
study_active: typeof value.study_active === "boolean" ? value.study_active : null,
study_state: textOf(value.state) || textOf(value.study_state),
study_message: textOf(value.message) || textOf(value.study_message),
hours_met: value.hours_met === true,
};
}
@@ -214,10 +220,21 @@ function taskText(row: UserRow) {
const state = row.study_state;
if (row.study_active === true || state === "运行中" || state === "学习中" || state === "准备") return "运行中";
if (state === "排队中") return "排队中";
if (state === "会话失效") return "会话失效";
if (state === "学习失败") return "学习失败";
if (state === "已达标" || row.hours_met) return "已达标";
if (state === "已学完") return "已学完";
if (row.study_paused || state === "已停止") return "已停止";
return "未开始";
}
function taskClass(row: UserRow) {
const text = taskText(row);
if (text === "运行中" || text === "排队中") return "ok";
if (text === "会话失效" || text === "学习失败") return "late";
return "quiet";
}
function taskCanStop(row: UserRow) {
const text = taskText(row);
return text === "运行中" || text === "排队中";
@@ -500,6 +517,7 @@ function resetSettingsForm() {
startMinute.value = null;
startSecond.value = null;
scheduleChoice.value = "keep";
hoursChoice.value = "keep";
workersValue.value = null;
proxyScheme.value = "keep";
proxyHost.value = "";
@@ -518,6 +536,7 @@ function captureSettings(): SettingsBaseline {
startMinute: startMinute.value,
startSecond: startSecond.value,
scheduleChoice: scheduleChoice.value,
hoursChoice: hoursChoice.value,
workers: workersValue.value,
scheme: proxyScheme.value,
host: proxyHost.value,
@@ -533,6 +552,7 @@ function applyRowSettings(row: UserRow) {
startMinute.value = row.study_start_minute;
startSecond.value = row.study_start_second;
scheduleChoice.value = row.study_schedule_enabled === false ? "off" : "on";
hoursChoice.value = row.hours_source === "history" ? "history" : "api";
workersValue.value = row.course_workers;
}
@@ -616,6 +636,7 @@ function applySavedRow(row: UserRow, sent: {
monthlyTarget: number | null;
scheduleEnabled: boolean | null;
workers: number | null;
hoursSource: "api" | "history" | null;
day: number | null;
hour: number | null;
minute: number | null;
@@ -628,6 +649,7 @@ function applySavedRow(row: UserRow, sent: {
if (sent.monthlyTarget != null) next.monthly_target = sent.monthlyTarget;
if (sent.scheduleEnabled != null) next.study_schedule_enabled = sent.scheduleEnabled;
if (sent.workers != null) next.course_workers = sent.workers;
if (sent.hoursSource) next.hours_source = sent.hoursSource;
if (sent.day != null && sent.hour != null && sent.minute != null && sent.second != null) {
next.study_start_day = sent.day;
next.study_start_hour = sent.hour;
@@ -653,6 +675,7 @@ async function saveSettings() {
|| startSecond.value !== baseline.startSecond;
const scheduleChanged = scheduleChoice.value !== baseline.scheduleChoice && scheduleValue() !== null;
const workersChanged = workersValue.value !== baseline.workers;
const hoursChanged = hoursChoice.value !== baseline.hoursChoice && hoursChoice.value !== "keep";
const proxyTouched = proxyScheme.value !== baseline.scheme
|| proxyHost.value.trim() !== baseline.host
|| proxyPort.value !== baseline.port
@@ -691,12 +714,13 @@ async function saveSettings() {
const sentTarget = targetChanged ? monthlyTarget.value : null;
const sentSchedule = scheduleChanged ? scheduleValue() : null;
const sentWorkers = workersChanged ? workersValue.value : null;
const sentHours = hoursChanged ? hoursChoice.value : null;
const sentDay = scheduleTouched ? startDay.value : null;
const sentHour = scheduleTouched ? startHour.value : null;
const sentMinute = scheduleTouched ? startMinute.value : null;
const sentSecond = scheduleTouched ? startSecond.value : null;
const sentScheme = proxyTouched && proxyScheme.value !== "keep" ? proxyScheme.value : null;
if (sentTarget == null && sentSchedule == null && sentWorkers == null && sentDay == null && sentScheme == null) {
if (sentTarget == null && sentSchedule == null && sentWorkers == null && sentDay == null && sentScheme == null && sentHours == null) {
settingsOpen.value = false;
return;
}
@@ -714,6 +738,7 @@ async function saveSettings() {
second: sentSecond,
schedule_enabled: sentSchedule,
workers: sentWorkers,
hours_source: sentHours,
scheme: sentScheme,
host: sentScheme && proxyManual.value ? proxyHost.value.trim() : "",
port: sentScheme && proxyManual.value ? proxyPort.value : null,
@@ -730,6 +755,7 @@ async function saveSettings() {
monthlyTarget: sentTarget,
scheduleEnabled: sentSchedule,
workers: sentWorkers,
hoursSource: sentHours === "history" || sentHours === "api" ? sentHours : null,
day: sentDay,
hour: sentHour,
minute: sentMinute,
@@ -932,7 +958,15 @@ onMounted(() => {
:official="row.official_month_hours"
/>
</td>
<td :class="taskText(row) === '运行中' ? 'ok' : 'quiet'">{{ taskText(row) }}</td>
<td :class="taskClass(row)">
<n-tooltip v-if="row.study_message" placement="top">
<template #trigger>
<span>{{ taskText(row) }}</span>
</template>
{{ row.study_message }}
</n-tooltip>
<template v-else>{{ taskText(row) }}</template>
</td>
<td class="when">{{ formatRefreshTime(row.study_opened_at) || "—" }}</td>
<td class="when">{{ row.proxy || "—" }}</td>
<td class="when">{{ formatRefreshTime(row.last_refresh_at) }}</td>
@@ -1006,6 +1040,17 @@ onMounted(() => {
<n-time-picker v-model:formatted-value="startTime" value-format="HH:mm:ss" :actions="null" placeholder="保持不变" :disabled="scheduleTimeDisabled" />
</div>
</n-form-item>
<n-form-item label="判断依据">
<div class="hours-source-field">
<n-radio-group v-model:value="hoursChoice" size="small">
<n-radio-button v-if="settingsIds.length !== 1" value="keep">保持不变</n-radio-button>
<n-radio-button value="api">官方统计数据</n-radio-button>
<n-radio-button value="history">历史统计数据</n-radio-button>
</n-radio-group>
<p v-if="hoursChoice === 'api'" class="field-hint">根据官方接口返回进行判断(官方统计可能会延后,导致学时可能会多刷)</p>
<p v-else-if="hoursChoice === 'history'" class="field-hint">根据学习历史统计本月学时</p>
</div>
</n-form-item>
<n-form-item label="同时学习课程数">
<div class="target-control">
<n-select class="worker-select" v-model:value="workersValue" :options="workerOptions" placeholder="保持不变" />
+14
View File
@@ -1687,6 +1687,20 @@ a.history-title:hover {
margin: 0 0 12px;
}
.hours-source-field {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.field-hint {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.secret-field {
padding: 8px 0;
border-bottom: 1px solid var(--line);