fix: 管理员账号先按本地密码判断

This commit is contained in:
2026-10-30 12:01:30 +08:00
parent c59dfcdcbe
commit 2e8c67f0a4
3 changed files with 93 additions and 21 deletions
+30
View File
@@ -93,6 +93,36 @@ def auth_mode(session: Session = Depends(get_session)) -> dict:
return {"mode": _setting(session).login_mode}
def _matched_local_user(session: Session, username: str) -> User | None:
user = session.scalar(select(User).where(User.username == username))
if user is None:
return None
if _setting(session).login_mode == "local" or user.role == "admin":
return user
return None
@router.post("/auth/login")
async def login(body: dict) -> dict:
username = str(body.get("username") or "").strip()
password = str(body.get("password") or "")
if not username or not password:
raise _bad("请填写账号和密码")
with session_scope() as session:
user = _matched_local_user(session, username)
if user is not None:
if not verify_password(password, user.password_hash):
raise _bad("登录失败")
return _token_for("local", str(user.id), user.role, user.username)
mode = _setting(session).login_mode
if mode != "nqi":
raise _bad("账号或密码不正确")
started = await nqi_start({"username": username, "purpose": "login"})
if started.get("status") == "captcha":
return {**started, "status": "need_captcha"}
return started
@router.post("/auth/local")
def local_login(body: dict, session: Session = Depends(get_session)) -> dict:
if _setting(session).login_mode != "local":
+32
View File
@@ -110,6 +110,38 @@ def test_local_login_task_and_admin(client: TestClient):
assert "小区" in downloaded.content.decode("utf-8-sig")
def test_admin_is_judged_locally_when_users_use_nqi(client: TestClient, monkeypatch):
from app.nqi.client import NqiError
logged = client.post("/api/auth/local", json={"username": "admin", "password": "admin-pass"})
headers = {"Authorization": f"Bearer {logged.json()['token']}"}
client.post("/api/admin/users", json={"username": "user", "password": "user-pass", "role": "user"}, headers=headers)
saved = client.put(
"/api/admin/settings",
json={"loginMode": "nqi", "credentialRefreshSeconds": 300, "workerConcurrency": 4},
headers=headers,
)
assert saved.status_code == 200
calls: list[str] = []
async def fail_open(self):
calls.append("open")
raise NqiError("不应访问平台")
monkeypatch.setattr("app.api.http.NqiClient.open_login", fail_open)
wrong = client.post("/api/auth/login", json={"username": "admin", "password": "wrong"})
assert wrong.status_code == 400
assert wrong.json()["detail"] == "登录失败"
ok = client.post("/api/auth/login", json={"username": "admin", "password": "admin-pass"})
assert ok.status_code == 200
assert ok.json()["user"]["role"] == "admin"
assert calls == []
other = client.post("/api/auth/login", json={"username": "user", "password": "user-pass"})
assert other.status_code == 400
assert other.json()["detail"] == "不应访问平台"
assert calls == ["open"]
def test_pool_add_is_allowed_when_login_is_local(client: TestClient, monkeypatch):
from app.nqi.client import NqiError