fix: 阻止用扫码标记冒充他人登录

This commit is contained in:
2026-11-16 02:31:02 +08:00
parent 5e5f3bd1bd
commit ddc2ef784b
2 changed files with 38 additions and 1 deletions
+9 -1
View File
@@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
import hmac
import json import json
import secrets import secrets
import threading import threading
@@ -127,9 +128,16 @@ def login_and_store(
auto_attempts: int = 3, auto_attempts: int = 3,
) -> dict: ) -> dict:
_purge_pending() _purge_pending()
if is_qr_password(password):
raise RuntimeError("请使用扫码登录")
account = db.get(Account, employee_id) account = db.get(Account, employee_id)
if account and account.password_cipher and account.credential_cipher: if account and account.password_cipher and account.credential_cipher:
if decrypt_secret(account.password_cipher) == password and _credential_still_valid(account, client_factory): stored = decrypt_secret(account.password_cipher)
same_password = (
not is_qr_password(stored)
and hmac.compare_digest(stored.encode("utf-8"), password.encode("utf-8"))
)
if same_password and _credential_still_valid(account, client_factory):
_request_course_sync(employee_id) _request_course_sync(employee_id)
return {"employee_id": employee_id} return {"employee_id": employee_id}
_drop_employee(employee_id) _drop_employee(employee_id)
+29
View File
@@ -169,6 +169,35 @@ def test_login_stores_password_and_credential_only() -> None:
assert "测试用户" not in decrypt_secret(account.password_cipher) assert "测试用户" not in decrypt_secret(account.password_cipher)
def test_qr_mark_cannot_password_login_and_unicode_password_is_safe() -> None:
import euniv.api as api_module
import euniv.service as service_module
from euniv.client import QR_PASSWORD_MARK
from euniv.crypto import encrypt_secret
api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts
)
client = TestClient(api_module.app)
with SessionLocal() as db:
db.add(
Account(
employee_id="7001",
password_cipher=encrypt_secret(QR_PASSWORD_MARK),
credential_cipher=encrypt_secret(json.dumps({"yxt_token": "yxt-1"})),
)
)
db.commit()
stolen = client.post("/api/login", json={"employee_id": "7001", "password": QR_PASSWORD_MARK})
assert stolen.status_code == 400
assert stolen.json()["detail"] == "请使用扫码登录"
first = client.post("/api/login", json={"employee_id": "7002", "password": "密码一"})
assert first.status_code == 200
second = client.post("/api/login", json={"employee_id": "7002", "password": "密码一"})
assert second.status_code == 200
def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None: def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None:
import euniv.api as api_module import euniv.api as api_module
import euniv.service as service_module import euniv.service as service_module