施工(HEL-226): 实现登录门户与本机免密切换账号
用设备 Cookie 和授权表记住本机已验证账号,登录页按确认样图做成门户,不再把密码写进浏览器。 Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
co-authored by
Cursor
multica-agent
parent
8a5e78f022
commit
f0a1adf52f
@@ -0,0 +1,151 @@
|
||||
const { test, expect } = require("@playwright/test");
|
||||
|
||||
function loginPayload(user) {
|
||||
return {
|
||||
ok: true,
|
||||
authenticated: true,
|
||||
csrf_token: "portal-csrf",
|
||||
user,
|
||||
};
|
||||
}
|
||||
|
||||
async function mockLoginPortal(page, options = {}) {
|
||||
const accounts = options.accounts || [];
|
||||
let currentUserId = options.currentUserId ?? null;
|
||||
await page.route("**/api/**", async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const method = route.request().method();
|
||||
if (url.pathname === "/api/auth/accounts") {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({ ok: true, accounts, current_user_id: currentUserId }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (url.pathname === "/api/auth/switch" && method === "POST") {
|
||||
const body = route.request().postDataJSON() || {};
|
||||
const account = accounts.find((item) => Number(item.user_id) === Number(body.user_id));
|
||||
if (!account || options.switchFails) {
|
||||
await route.fulfill({
|
||||
status: 401,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({ error: "该账号需重新验证" }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
currentUserId = account.user_id;
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify(loginPayload(account)),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (url.pathname === "/api/auth/forget" && method === "POST") {
|
||||
const body = route.request().postDataJSON() || {};
|
||||
const index = accounts.findIndex((item) => Number(item.user_id) === Number(body.user_id));
|
||||
if (index >= 0) accounts.splice(index, 1);
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({ ok: true }),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if ((url.pathname === "/api/auth/login" || url.pathname === "/api/auth/register") && method === "POST") {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify(loginPayload({
|
||||
id: 9,
|
||||
username: "new_user",
|
||||
role: "user",
|
||||
membership: { active: false, subscribed: false, is_admin: false },
|
||||
})),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (url.pathname === "/api/auth/me") {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({
|
||||
ok: true,
|
||||
authenticated: Boolean(currentUserId),
|
||||
csrf_token: "portal-csrf",
|
||||
user: accounts.find((item) => Number(item.user_id) === Number(currentUserId)) || null,
|
||||
}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({ ok: true }),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const SAVED_ACCOUNTS = [
|
||||
{
|
||||
user_id: 1,
|
||||
username: "alpha_user",
|
||||
role: "admin",
|
||||
membership: { active: true, subscribed: true, is_admin: true },
|
||||
last_used_at: "2026-08-29T01:00:00+00:00",
|
||||
},
|
||||
{
|
||||
user_id: 2,
|
||||
username: "beta_user",
|
||||
role: "user",
|
||||
membership: { active: false, subscribed: false, is_admin: false },
|
||||
last_used_at: "2026-08-28T01:00:00+00:00",
|
||||
},
|
||||
];
|
||||
|
||||
test("first-time login portal asks for a password and hides environment copy", async ({ page }) => {
|
||||
await mockLoginPortal(page, { accounts: [] });
|
||||
await page.goto("/login/");
|
||||
await expect(page.locator(".login-card-title")).toHaveText("欢迎回来");
|
||||
await expect(page.locator("#loginUsername")).toBeVisible();
|
||||
await expect(page.locator(".login-submit")).toHaveText("登录");
|
||||
await expect(page.locator("body")).not.toContainText("内网个人版");
|
||||
await expect(page.locator("body")).not.toContainText("192.168.200.11");
|
||||
});
|
||||
|
||||
test("saved accounts can switch directly and show a re-auth message on failure", async ({ page }) => {
|
||||
await mockLoginPortal(page, { accounts: SAVED_ACCOUNTS.map((item) => ({ ...item })) });
|
||||
await page.goto("/login/");
|
||||
await expect(page.locator(".login-card-title")).toHaveText("选择账号");
|
||||
await expect(page.locator(".login-account-row")).toHaveCount(2);
|
||||
const switched = page.waitForRequest((request) => (
|
||||
request.url().includes("/api/auth/switch") && request.method() === "POST"
|
||||
));
|
||||
await page.locator('[data-switch-id="2"]').click();
|
||||
const request = await switched;
|
||||
expect(JSON.parse(request.postData() || "{}")).toEqual({ user_id: 2 });
|
||||
});
|
||||
|
||||
test("failed account switch stays on the portal with the original copy", async ({ page }) => {
|
||||
await mockLoginPortal(page, {
|
||||
accounts: SAVED_ACCOUNTS.map((item) => ({ ...item })),
|
||||
switchFails: true,
|
||||
});
|
||||
await page.goto("/login/");
|
||||
await page.locator('[data-switch-id="2"]').click();
|
||||
await expect(page.locator(".login-error")).toHaveText("该账号需重新验证");
|
||||
await expect(page).toHaveURL(/\/login\/?/);
|
||||
});
|
||||
|
||||
test("managing accounts removes a local record after inline confirmation", async ({ page }) => {
|
||||
await mockLoginPortal(page, { accounts: SAVED_ACCOUNTS.map((item) => ({ ...item })) });
|
||||
await page.goto("/login/");
|
||||
await page.locator('[data-login-action="manage"]').click();
|
||||
await expect(page.locator(".login-card-title")).toHaveText("管理账号记录");
|
||||
await page.locator('[data-confirm-id="2"]').click();
|
||||
await expect(page.locator(".login-confirm-copy")).toContainText("beta_user");
|
||||
await page.locator('[data-forget-id="2"]').click();
|
||||
await expect(page.locator(".login-account-row")).toHaveCount(1);
|
||||
await expect(page.locator(".login-account-row")).toContainText("alpha_user");
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import unittest
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from backend.features.accounts.security import SecretVault, token_hash
|
||||
from backend.features.accounts.service import AccountService
|
||||
from database import ReviewDatabase
|
||||
|
||||
|
||||
class AccountSwitchGrantTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.temp = TemporaryDirectory()
|
||||
self.database = ReviewDatabase(Path(self.temp.name) / "review.db")
|
||||
self.bound_user_id = 0
|
||||
self.service = AccountService(
|
||||
database=self.database,
|
||||
vault=SecretVault(SecretVault.generate_key()),
|
||||
current_user_supplier=lambda: self.bound_user_id,
|
||||
access_supplier=lambda: self.database.user_access(self.bound_user_id) or {},
|
||||
bind_user=self._bind,
|
||||
personal_field_builder=lambda *args, **kwargs: {},
|
||||
auth_lock=threading.Lock(),
|
||||
)
|
||||
self.device_a = token_hash("device-a-token")
|
||||
self.device_b = token_hash("device-b-token")
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.temp.cleanup()
|
||||
|
||||
def _bind(self, user_id: int) -> None:
|
||||
self.bound_user_id = int(user_id)
|
||||
|
||||
def _register(self, username: str, device_hash: str = "") -> dict:
|
||||
return self.service.register(username, "Password123", device_hash or self.device_a)
|
||||
|
||||
def test_login_records_accounts_for_the_current_device_only(self) -> None:
|
||||
first = self._register("alpha_user")
|
||||
second = self._register("beta_user")
|
||||
self.service.login("alpha_user", "Password123", self.device_b)
|
||||
|
||||
listed = self.service.list_device_accounts(self.device_a)
|
||||
names = [item["username"] for item in listed["accounts"]]
|
||||
self.assertEqual(names, ["beta_user", "alpha_user"])
|
||||
self.assertEqual(
|
||||
self.service.list_device_accounts(self.device_b)["accounts"][0]["username"],
|
||||
"alpha_user",
|
||||
)
|
||||
self.assertEqual(self.service.list_device_accounts("")["accounts"], [])
|
||||
self.assertEqual(first["user"]["username"], "alpha_user")
|
||||
self.assertEqual(second["user"]["username"], "beta_user")
|
||||
|
||||
def test_switch_uses_device_grant_and_keeps_the_original_authorization(self) -> None:
|
||||
first = self._register("alpha_user")
|
||||
self._register("beta_user")
|
||||
switched = self.service.switch_account(self.device_a, int(first["user"]["id"]))
|
||||
self.assertEqual(switched["user"]["username"], "alpha_user")
|
||||
remaining = {
|
||||
item["username"]
|
||||
for item in self.service.list_device_accounts(self.device_a)["accounts"]
|
||||
}
|
||||
self.assertEqual(remaining, {"alpha_user", "beta_user"})
|
||||
|
||||
def test_switch_without_a_valid_grant_requires_reauthentication(self) -> None:
|
||||
user = self._register("alpha_user")
|
||||
with self.assertRaisesRegex(PermissionError, "该账号需重新验证"):
|
||||
self.service.switch_account(self.device_b, int(user["user"]["id"]))
|
||||
with self.assertRaisesRegex(PermissionError, "该账号需重新验证"):
|
||||
self.service.switch_account("", int(user["user"]["id"]))
|
||||
|
||||
def test_forget_only_removes_the_current_device_grant(self) -> None:
|
||||
user = self._register("alpha_user")
|
||||
self.service.login("alpha_user", "Password123", self.device_b)
|
||||
self.service.forget_account(self.device_a, int(user["user"]["id"]))
|
||||
self.service.forget_account(self.device_a, int(user["user"]["id"]))
|
||||
self.assertEqual(self.service.list_device_accounts(self.device_a)["accounts"], [])
|
||||
self.assertEqual(
|
||||
self.service.list_device_accounts(self.device_b)["accounts"][0]["username"],
|
||||
"alpha_user",
|
||||
)
|
||||
|
||||
def test_logout_revokes_only_the_current_account_on_this_device(self) -> None:
|
||||
first = self._register("alpha_user")
|
||||
second = self._register("beta_user")
|
||||
self.service.revoke_current_device_grant(self.device_a, int(second["user"]["id"]))
|
||||
names = {
|
||||
item["username"]
|
||||
for item in self.service.list_device_accounts(self.device_a)["accounts"]
|
||||
}
|
||||
self.assertEqual(names, {"alpha_user"})
|
||||
switched = self.service.switch_account(self.device_a, int(first["user"]["id"]))
|
||||
self.assertEqual(switched["user"]["id"], first["user"]["id"])
|
||||
|
||||
def test_password_change_revokes_grants_on_every_device(self) -> None:
|
||||
user = self._register("alpha_user")
|
||||
self.service.login("alpha_user", "Password123", self.device_b)
|
||||
self._bind(int(user["user"]["id"]))
|
||||
self.service.change_password("Password123", "Password456")
|
||||
self.assertEqual(self.service.list_device_accounts(self.device_a)["accounts"], [])
|
||||
self.assertEqual(self.service.list_device_accounts(self.device_b)["accounts"], [])
|
||||
with self.assertRaisesRegex(PermissionError, "该账号需重新验证"):
|
||||
self.service.switch_account(self.device_a, int(user["user"]["id"]))
|
||||
|
||||
def test_device_keeps_at_most_five_accounts(self) -> None:
|
||||
usernames = [f"user_{index}" for index in range(6)]
|
||||
ids = [self._register(name)["user"]["id"] for name in usernames]
|
||||
listed = self.service.list_device_accounts(self.device_a)["accounts"]
|
||||
self.assertEqual(len(listed), 5)
|
||||
kept = {item["user_id"] for item in listed}
|
||||
self.assertNotIn(ids[0], kept)
|
||||
self.assertTrue(set(ids[1:]).issubset(kept))
|
||||
|
||||
def test_expired_grants_are_removed_lazily(self) -> None:
|
||||
user = self._register("alpha_user")
|
||||
past = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat(timespec="seconds")
|
||||
self.database.upsert_switch_grant(
|
||||
self.device_a,
|
||||
int(user["user"]["id"]),
|
||||
past,
|
||||
past,
|
||||
past,
|
||||
)
|
||||
self.assertEqual(self.service.list_device_accounts(self.device_a)["accounts"], [])
|
||||
with self.assertRaisesRegex(PermissionError, "该账号需重新验证"):
|
||||
self.service.switch_account(self.device_a, int(user["user"]["id"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -25,6 +25,7 @@ class DatabaseMigrationTests(unittest.TestCase):
|
||||
("0002", "create_job_runs"),
|
||||
("0003", "extend_llm_audit"),
|
||||
("0004", "add_mentor_note"),
|
||||
("0005", "create_account_switch_grants"),
|
||||
],
|
||||
)
|
||||
columns = {
|
||||
@@ -39,7 +40,7 @@ class DatabaseMigrationTests(unittest.TestCase):
|
||||
count = connection.execute(
|
||||
"SELECT COUNT(*) AS count FROM schema_migrations"
|
||||
).fetchone()["count"]
|
||||
self.assertEqual(count, 4)
|
||||
self.assertEqual(count, 5)
|
||||
|
||||
def test_database_with_recorded_0004_and_note_column_starts_without_reapply(
|
||||
self,
|
||||
@@ -60,7 +61,7 @@ class DatabaseMigrationTests(unittest.TestCase):
|
||||
count = connection.execute(
|
||||
"SELECT COUNT(*) AS count FROM schema_migrations"
|
||||
).fetchone()["count"]
|
||||
self.assertEqual(count, 4)
|
||||
self.assertEqual(count, 5)
|
||||
|
||||
def test_old_database_without_0004_upgrades_and_adds_note_column(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
@@ -87,7 +88,7 @@ class DatabaseMigrationTests(unittest.TestCase):
|
||||
"PRAGMA table_info(mentor_preferences)"
|
||||
)
|
||||
]
|
||||
self.assertEqual(versions, {"0001", "0002", "0003", "0004"})
|
||||
self.assertEqual(versions, {"0001", "0002", "0003", "0004", "0005"})
|
||||
self.assertIn("note", note_rows)
|
||||
|
||||
def test_database_with_unknown_migration_is_rejected(self) -> None:
|
||||
|
||||
@@ -65,8 +65,11 @@ class GovernanceRegistryTests(unittest.TestCase):
|
||||
public,
|
||||
{
|
||||
("GET", "/api/health"),
|
||||
("GET", "/api/auth/accounts"),
|
||||
("POST", "/api/auth/login"),
|
||||
("POST", "/api/auth/register"),
|
||||
("POST", "/api/auth/switch"),
|
||||
("POST", "/api/auth/forget"),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user