fix: 会话失效时自动重新登录,管理端可改判断依据
This commit is contained in:
@@ -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,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 == ""
|
||||
|
||||
Reference in New Issue
Block a user