feat: Login security screen with history, locked accounts and settings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-11-30 14:33:53 +08:00
1 parent 6598b58cb8
commit 091503a820
11 files changed
+925 -2

No files matched your search

@@ -99,7 +99,7 @@ Design: `design.md`. All tasks run serially: each builds on the one before.
- Scope: `solvway-admin-portal/app/api/auth/**`, `solvway-admin-portal/app/login/**`, `solvway-admin-portal/app/components/app/**`, `solvway-admin-portal/app/components/users/**`, `solvway-admin-portal/app/lib/**`
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`
- [ ] 4.2 `/login-security` page with History, Locked and Settings tabs, the proxy route, a service and i18n keys (design decision 9).
- [x] 4.2 `/login-security` page with History, Locked and Settings tabs, the proxy route, a service and i18n keys (design decision 9).
- **Tests first:**
- History rows and filters go into the query;
- Locked rows, with Unlock behind a confirm, refreshing the list;
@@ -0,0 +1,74 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET, POST, PUT } from "./route";
const req = (url: string, body?: unknown) =>
new Request(url, body === undefined ? undefined : { method: "PUT", body: JSON.stringify(body), headers: { "Content-Type": "application/json" } }) as unknown as Parameters<typeof GET>[0];
const ctx = (path?: string[]) => ({ params: Promise.resolve({ path }) });
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset().mockResolvedValue("jwt");
});
describe("/api/login-security/[[...path]]", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await GET(req("http://localhost/api/login-security/locked"), ctx(["locked"]))).status).toBe(401);
expect((await PUT(req("http://localhost/api/login-security/config", {}), ctx(["config"]))).status).toBe(401);
expect((await POST(req("http://localhost/api/login-security/locked/a/unlock", {}), ctx(["locked", "a", "unlock"]))).status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("refuses dot segments", async () => {
expect((await GET(req("http://localhost/api/login-security/.."), ctx([".."]))).status).toBe(400);
expect((await POST(req("http://localhost/api/login-security/locked/./unlock"), ctx(["locked", ".", "unlock"]))).status).toBe(400);
expect((await PUT(req("http://localhost/api/login-security/.."), ctx([".."]))).status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("GET forwards the path and query", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [] } });
const res = await GET(req("http://localhost/api/login-security/audit?username=a&page=0&size=20"), ctx(["audit"]));
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/login-security/audit?username=a&page=0&size=20", { token: "jwt" });
});
it("encodes each segment", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: null });
await POST(req("http://localhost/api/login-security/locked/a%2Fb/unlock"), ctx(["locked", "a/b", "unlock"]));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/login-security/locked/a%2Fb/unlock", { token: "jwt", method: "POST", body: undefined });
});
it("PUT forwards the JSON body", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { enabled: true } });
const body = { enabled: true, maxAttempts: 5, period: 15, unit: "M" };
const res = await PUT(req("http://localhost/api/login-security/config", body), ctx(["config"]));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/login-security/config", { token: "jwt", method: "PUT", body });
expect(await res.json()).toEqual({ enabled: true });
});
it("POST forwards the JSON body", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { x: 1 } });
const r = new Request("http://localhost/api/login-security/x", { method: "POST", body: JSON.stringify({ a: 1 }) }) as unknown as Parameters<typeof GET>[0];
await POST(r, ctx(["x"]));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/login-security/x", { token: "jwt", method: "POST", body: { a: 1 } });
});
it("passes an empty upstream body through as 204", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: null });
const res = await POST(req("http://localhost/api/login-security/locked/a/unlock"), ctx(["locked", "a", "unlock"]));
expect(res.status).toBe(204);
});
it("passes a refusal through with its code", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 400, error: "Max attempts must be at least 1", code: "INVALID_SETTING" });
const res = await PUT(req("http://localhost/api/login-security/config", { maxAttempts: 0 }), ctx(["config"]));
expect(res.status).toBe(400);
expect(await res.json()).toMatchObject({ code: "INVALID_SETTING", error: "Max attempts must be at least 1" });
});
});
@@ -0,0 +1,30 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
// Proxy for /api/admin/login-security/**; mobile-api owns the BO_LOGIN_SECURITY guard. Bodies are forwarded, never logged.
type Ctx = { params: Promise<{ path?: string[] }> };
async function forward(method: "GET" | "POST" | "PUT", req: NextRequest, { params }: Ctx) {
const token = await getToken();
if (!token) return unauthorized();
const { path = [] } = await params;
if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path.");
const target = `/api/admin/login-security${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${method === "GET" ? new URL(req.url).search : ""}`;
let body: unknown;
if (method !== "GET") {
const text = await req.text();
if (text) {
try { body = JSON.parse(text); } catch { return badRequest("Invalid request body."); }
}
}
const result = await callMobileApi<unknown>(target, method === "GET" ? { token } : { token, method, body });
if (!result.ok) return errorResponse(result);
if (result.data === null || result.data === undefined) return new NextResponse(null, { status: 204 });
return NextResponse.json(result.data);
}
export const GET = (req: NextRequest, ctx: Ctx) => forward("GET", req, ctx);
export const POST = (req: NextRequest, ctx: Ctx) => forward("POST", req, ctx);
export const PUT = (req: NextRequest, ctx: Ctx) => forward("PUT", req, ctx);
@@ -0,0 +1,89 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { Tabs as TabsPrimitive } from "radix-ui"
import { cn } from "@/app/lib/utils"
function Tabs({
className,
orientation = "horizontal",
...props
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
return (
<TabsPrimitive.Root
data-slot="tabs"
data-orientation={orientation}
orientation={orientation}
className={cn(
"group/tabs flex gap-2 data-[orientation=horizontal]:flex-col",
className
)}
{...props}
/>
)
}
const tabsListVariants = cva(
"group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-[orientation=horizontal]/tabs:h-9 group-data-[orientation=vertical]/tabs:h-fit group-data-[orientation=vertical]/tabs:flex-col data-[variant=line]:rounded-none",
{
variants: {
variant: {
default: "bg-muted",
line: "gap-1 bg-transparent",
},
},
defaultVariants: {
variant: "default",
},
}
)
function TabsList({
className,
variant = "default",
...props
}: React.ComponentProps<typeof TabsPrimitive.List> &
VariantProps<typeof tabsListVariants>) {
return (
<TabsPrimitive.List
data-slot="tabs-list"
data-variant={variant}
className={cn(tabsListVariants({ variant }), className)}
{...props}
/>
)
}
function TabsTrigger({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
return (
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
"relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 group-data-[variant=default]/tabs-list:data-[state=active]:shadow-sm group-data-[variant=line]/tabs-list:data-[state=active]:shadow-none dark:text-muted-foreground dark:hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent",
"data-[state=active]:bg-background data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 dark:data-[state=active]:text-foreground",
"after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:bottom-[-5px] group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-right-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-[state=active]:after:opacity-100",
className
)}
{...props}
/>
)
}
function TabsContent({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
return (
<TabsPrimitive.Content
data-slot="tabs-content"
className={cn("flex-1 outline-none", className)}
{...props}
/>
)
}
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }
@@ -323,4 +323,67 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
LeadsSameEmailAs: "Same email as",
LeadsSameMobileEmailAs: "Same mobile and email as",
LeadsViewLead: "View lead",
BO_LOGIN_SECURITY: "Login security",
LsTabHistory: "History",
LsTabLocked: "Locked",
LsTabSettings: "Settings",
LsTime: "Time",
LsEvent: "Event",
LsIp: "IP",
LsBrowser: "Browser",
LsNote: "Note",
LsFrom: "From date",
LsTo: "To date",
LsAllEvents: "All events",
LsEventLoginSuccess: "Login succeeded",
LsEventLoginFail: "Login failed",
LsEventLoginLocked: "Account locked",
LsEventLogout: "Logout",
LsEventUnlockReset: "Unlocked by an admin",
LsEventPasswordChanged: "Password changed",
LsNoHistory: "No sign-in history found",
LsNoMatch: "No sign-in history matches your filters",
LsHistoryLoadFailed: "Failed to load the sign-in history",
LsFailures: "Failures",
LsLastFailure: "Last failure",
LsLockedUntil: "Locked until",
LsUnlock: "Unlock",
LsUnlockTitle: "Unlock account",
LsUnlockConfirm: "Allow {username} to sign in again?",
LsNoLocked: "No locked accounts",
LsLockedLoadFailed: "Failed to load the locked accounts",
LsUnlockFailed: "Failed to unlock the account",
LsLockoutTitle: "Lockout",
LsLockoutOn: "Lockout on",
LsMaxAttempts: "Max attempts",
LsPeriod: "Period",
LsUnit: "Unit",
LsUnitS: "Seconds",
LsUnitM: "Minutes",
LsUnitH: "Hours",
LsUnitD: "Days",
LsSaveLockout: "Save lockout settings",
LsLockoutSaved: "Lockout settings saved.",
LsRulesTitle: "Password rules",
LsRuleOn: "On",
LsRuleValue: "Value",
LsRuleName: "Rule",
LsSaveRules: "Save password rules",
LsRulesSaved: "Password rules saved.",
LsSettingsLoadFailed: "Failed to load the settings",
LsSaveFailed: "Failed to save",
PwdRule_INPUT_LENGTH_MIN: "Minimum length",
PwdRule_INPUT_LENGTH_MAX: "Maximum length",
PwdRule_ALPHABET_LENGTH_MIN: "Minimum letters",
PwdRule_ALPHABET_LENGTH_MAX: "Maximum letters",
PwdRule_UPPERCASE_LENGTH_MIN: "Minimum uppercase letters",
PwdRule_UPPERCASE_LENGTH_MAX: "Maximum uppercase letters",
PwdRule_LOWERCASE_LENGTH_MIN: "Minimum lowercase letters",
PwdRule_LOWERCASE_LENGTH_MAX: "Maximum lowercase letters",
PwdRule_NUMERIC_LENGTH_MIN: "Minimum digits",
PwdRule_NUMERIC_LENGTH_MAX: "Maximum digits",
PwdRule_SYMBOLIC_LENGTH_MIN: "Minimum symbols",
PwdRule_SYMBOLIC_LENGTH_MAX: "Maximum symbols",
PwdRule_NO_OTHER_LANGUAGE: "Latin characters only",
PwdRule_SPACE_NOT_ALLOWED: "No spaces",
};
@@ -14,7 +14,7 @@ describe("routeModules", () => {
it("leaves other routes ungated", () => {
expect(requiredModuleFor("/")).toBeUndefined();
expect(requiredModulesFor("/members")).toBeUndefined();
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/emails", "/event-leads", "/events", "/interests", "/leads", "/roles", "/users"]);
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/emails", "/event-leads", "/events", "/interests", "/leads", "/login-security", "/roles", "/users"]);
expect(requiredModuleFor("/emails")).toBe("BO_EMAILS");
expect(requiredModuleFor("/leads")).toBe("BO_LEADS");
});
@@ -10,6 +10,7 @@ export const ROUTE_MODULES: Record<string, string> = {
"/event-leads": "BO_EVENT_LEADS",
"/leads": "BO_LEADS",
"/emails": "BO_EMAILS",
"/login-security": "BO_LOGIN_SECURITY",
};
export function requiredModuleFor(pathname: string): string | undefined {
@@ -0,0 +1,53 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), apiPut: vi.fn() }));
vi.mock("@/app/lib/clientApi", () => mocks);
import { getConfig, getPasswordRules, listAudit, listLocked, saveConfig, savePasswordRules, unlock } from "./loginSecurity";
beforeEach(() => {
mocks.apiGet.mockReset();
mocks.apiPost.mockReset();
mocks.apiPut.mockReset();
});
describe("loginSecurity service", () => {
it("listAudit sends only given filters with a 0-based page", async () => {
mocks.apiGet.mockResolvedValue({ content: [{ id: 1 }], totalElements: 9 });
const out = await listAudit({ username: "a", event: "LOGIN_FAIL", from: "2026-11-01", page: 2, pageSize: 10 });
expect(mocks.apiGet).toHaveBeenCalledWith("/api/login-security/audit?username=a&event=LOGIN_FAIL&from=2026-11-01&page=1&size=10");
expect(out).toEqual({ items: [{ id: 1 }], total: 9 });
});
it("listAudit tolerates an empty body", async () => {
mocks.apiGet.mockResolvedValue(null);
expect(await listAudit({ page: 1, pageSize: 10 })).toEqual({ items: [], total: 0 });
});
it("listLocked GETs the locked accounts", async () => {
mocks.apiGet.mockResolvedValue([]);
await listLocked();
expect(mocks.apiGet).toHaveBeenCalledWith("/api/login-security/locked");
});
it("unlock POSTs to the encoded username", async () => {
await unlock("a b/c");
expect(mocks.apiPost).toHaveBeenCalledWith("/api/login-security/locked/a%20b%2Fc/unlock");
});
it("getConfig / saveConfig use the config path", async () => {
await getConfig();
expect(mocks.apiGet).toHaveBeenCalledWith("/api/login-security/config");
const cfg = { enabled: true, maxAttempts: 5, period: 15, unit: "M" as const };
await saveConfig(cfg);
expect(mocks.apiPut).toHaveBeenCalledWith("/api/login-security/config", cfg);
});
it("getPasswordRules / savePasswordRules use the rules path", async () => {
await getPasswordRules();
expect(mocks.apiGet).toHaveBeenCalledWith("/api/login-security/password-rules");
const rules = [{ id: 1, status: "Y" as const, value: "8" }];
await savePasswordRules(rules);
expect(mocks.apiPut).toHaveBeenCalledWith("/api/login-security/password-rules", rules);
});
});
@@ -0,0 +1,80 @@
import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi";
export const LOGIN_EVENTS = ["LOGIN_SUCCESS", "LOGIN_FAIL", "LOGIN_LOCKED", "LOGOUT", "UNLOCK_RESET", "PASSWORD_CHANGED"] as const;
export const LOCKOUT_UNITS = ["S", "M", "H", "D"] as const;
export interface AuditRow {
id: number;
username: string;
/** Server-local "yyyy-MM-ddTHH:mm:ss". */
datetime: string;
event: string;
ipAddress: string | null;
userAgent: string | null;
message: string | null;
}
export interface AuditParams {
username?: string;
event?: string;
/** "yyyy-MM-dd". */
from?: string;
to?: string;
/** 1-based. */
page: number;
pageSize: number;
}
export interface LockedAccount {
username: string;
failures: number;
lastFailure: string | null;
lockedUntil: string | null;
}
export interface LockoutConfig {
enabled: boolean;
maxAttempts: number;
period: number;
unit: (typeof LOCKOUT_UNITS)[number];
}
export interface PasswordRule {
id: number;
param: string;
status: "Y" | "N";
value: string | null;
}
export type PasswordRuleUpdate = Pick<PasswordRule, "id" | "status" | "value">;
const BASE = "/api/login-security";
export async function listAudit(params: AuditParams): Promise<{ items: AuditRow[]; total: number }> {
const qs = new URLSearchParams();
for (const key of ["username", "event", "from", "to"] as const) if (params[key]) qs.set(key, params[key]);
qs.set("page", String(Math.max(0, params.page - 1)));
qs.set("size", String(params.pageSize));
const raw = await apiGet<{ content?: AuditRow[]; totalElements?: number } | null>(`${BASE}/audit?${qs}`);
const items = Array.isArray(raw?.content) ? raw.content : [];
return { items, total: typeof raw?.totalElements === "number" ? raw.totalElements : items.length };
}
export const listLocked = () => apiGet<LockedAccount[]>(`${BASE}/locked`);
export const unlock = (username: string) => apiPost<void>(`${BASE}/locked/${encodeURIComponent(username)}/unlock`);
export const getConfig = () => apiGet<LockoutConfig>(`${BASE}/config`);
export const saveConfig = (cfg: LockoutConfig) => apiPut<LockoutConfig>(`${BASE}/config`, cfg);
export const getPasswordRules = () => apiGet<PasswordRule[]>(`${BASE}/password-rules`);
export const savePasswordRules = (rules: PasswordRuleUpdate[]) => apiPut<PasswordRule[]>(`${BASE}/password-rules`, rules);
export const LOGIN_EVENT_KEYS: Record<string, string> = {
LOGIN_SUCCESS: "LsEventLoginSuccess",
LOGIN_FAIL: "LsEventLoginFail",
LOGIN_LOCKED: "LsEventLoginLocked",
LOGOUT: "LsEventLogout",
UNLOCK_RESET: "LsEventUnlockReset",
PASSWORD_CHANGED: "LsEventPasswordChanged",
};
/** Params with no value to edit: the rule is only on or off. */
export const FLAG_RULE_PARAMS = ["NO_OTHER_LANGUAGE", "SPACE_NOT_ALLOWED"];
@@ -0,0 +1,156 @@
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({
listAudit: vi.fn(), listLocked: vi.fn(), unlock: vi.fn(), getConfig: vi.fn(), saveConfig: vi.fn(),
getPasswordRules: vi.fn(), savePasswordRules: vi.fn(), useAdminAuth: vi.fn(),
}));
vi.mock("@/app/lib/services/loginSecurity", async (importActual) => ({
...(await importActual<typeof import("@/app/lib/services/loginSecurity")>()),
listAudit: mocks.listAudit, listLocked: mocks.listLocked, unlock: mocks.unlock, getConfig: mocks.getConfig,
saveConfig: mocks.saveConfig, getPasswordRules: mocks.getPasswordRules, savePasswordRules: mocks.savePasswordRules,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { memoryRouter } from "@/test/memoryRouter";
import LoginSecurityPage from "./page";
const AUDIT = [
{ id: 2, username: "sales1", datetime: "2026-11-30T13:58:18", event: "LOGIN_FAIL", ipAddress: "10.0.0.5", userAgent: "Mozilla/5.0 (X11)", message: "Bad password" },
{ id: 1, username: "admin", datetime: "2026-11-29T09:05:00", event: "LOGIN_SUCCESS", ipAddress: "10.0.0.6", userAgent: null, message: null },
];
const LOCKED = [{ username: "sales1", failures: 5, lastFailure: "2026-11-30T13:58:18", lockedUntil: "2026-11-30T14:13:18" }];
const CONFIG = { enabled: true, maxAttempts: 5, period: 15, unit: "M" };
const RULES = [
{ id: 1, param: "INPUT_LENGTH_MIN", status: "Y", value: "8" },
{ id: 2, param: "SPACE_NOT_ALLOWED", status: "N", value: null },
];
beforeEach(() => {
memoryRouter.reset("/login-security");
mocks.listAudit.mockReset().mockResolvedValue({ items: AUDIT, total: 2 });
mocks.listLocked.mockReset().mockResolvedValue(LOCKED);
mocks.unlock.mockReset().mockResolvedValue(undefined);
mocks.getConfig.mockReset().mockResolvedValue(CONFIG);
mocks.saveConfig.mockReset().mockImplementation(async (c) => c);
mocks.getPasswordRules.mockReset().mockResolvedValue(RULES);
mocks.savePasswordRules.mockReset().mockResolvedValue(RULES);
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
});
describe("LoginSecurityPage", () => {
it("renders NotAuthorized without BO_LOGIN_SECURITY", () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
render(<LoginSecurityPage />);
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
expect(mocks.listAudit).not.toHaveBeenCalled();
});
it("History lists rows with the event label and a titled browser", async () => {
render(<LoginSecurityPage />);
const table = await screen.findByRole("table");
expect(within(table).getAllByRole("columnheader").map((h) => h.textContent)).toEqual(["Time", "Username", "Event", "IP", "Browser", "Note"]);
const rows = within(table).getAllByRole("row").slice(1);
expect(rows[0]).toHaveTextContent("30/11/2026 13:58");
expect(rows[0]).toHaveTextContent("sales1");
expect(rows[0]).toHaveTextContent("Login failed");
expect(rows[0]).toHaveTextContent("Bad password");
expect(within(rows[0]).getByTitle("Mozilla/5.0 (X11)")).toBeInTheDocument();
expect(rows[1]).toHaveTextContent("Login succeeded");
});
it("History puts the filters in the query", async () => {
memoryRouter.reset("/login-security", "event=LOGIN_FAIL&from=2026-11-01");
render(<LoginSecurityPage />);
await screen.findByRole("table");
expect(mocks.listAudit).toHaveBeenCalledWith(expect.objectContaining({ event: "LOGIN_FAIL", from: "2026-11-01", page: 1, pageSize: 20 }));
await userEvent.type(screen.getByRole("searchbox", { name: "Username" }), "sales");
await waitFor(() => expect(mocks.listAudit).toHaveBeenLastCalledWith(expect.objectContaining({ username: "sales", event: "LOGIN_FAIL" })));
});
it("History shows an empty state and an error state", async () => {
mocks.listAudit.mockResolvedValue({ items: [], total: 0 });
const { unmount } = render(<LoginSecurityPage />);
expect(await screen.findByText("No sign-in history found")).toBeInTheDocument();
unmount();
mocks.listAudit.mockRejectedValue(new Error("LsHistoryLoadFailed"));
render(<LoginSecurityPage />);
expect(await screen.findByRole("alert")).toHaveTextContent("Failed to load the sign-in history");
});
async function openTab(name: string) {
render(<LoginSecurityPage />);
await screen.findByRole("table");
await userEvent.click(screen.getByRole("tab", { name }));
}
it("Locked lists accounts; Unlock asks to confirm, calls unlock and reloads", async () => {
await openTab("Locked");
const row = (await screen.findByText("sales1")).closest("tr")!;
expect(row).toHaveTextContent("5");
expect(row).toHaveTextContent("30/11/2026 14:13");
await userEvent.click(within(row).getByRole("button", { name: "Unlock" }));
const dialog = await screen.findByRole("dialog");
expect(dialog).toHaveTextContent("sales1");
expect(mocks.unlock).not.toHaveBeenCalled();
mocks.listLocked.mockResolvedValue([]);
await userEvent.click(within(dialog).getByRole("button", { name: "Unlock" }));
await waitFor(() => expect(mocks.unlock).toHaveBeenCalledWith("sales1"));
expect(await screen.findByText("No locked accounts")).toBeInTheDocument();
});
it("Locked shows the server message when unlock fails", async () => {
mocks.unlock.mockRejectedValue(new Error("Not allowed"));
await openTab("Locked");
await userEvent.click(await screen.findByRole("button", { name: "Unlock" }));
await userEvent.click(within(await screen.findByRole("dialog")).getByRole("button", { name: "Unlock" }));
expect(await screen.findByText("Not allowed")).toBeInTheDocument();
});
it("Settings loads the config, saves it and shows the server validation message", async () => {
await openTab("Settings");
const max = await screen.findByLabelText("Max attempts");
expect(max).toHaveValue(5);
expect(screen.getByLabelText("Period")).toHaveValue(15);
await userEvent.clear(max);
await userEvent.type(max, "3");
await userEvent.click(screen.getByRole("button", { name: "Save lockout settings" }));
await waitFor(() => expect(mocks.saveConfig).toHaveBeenCalledWith({ enabled: true, maxAttempts: 3, period: 15, unit: "M" }));
expect(await screen.findByText("Lockout settings saved.")).toBeInTheDocument();
mocks.saveConfig.mockRejectedValue(new Error("Max attempts too high"));
await userEvent.click(screen.getByRole("button", { name: "Save lockout settings" }));
expect(await screen.findByText("Max attempts too high")).toBeInTheDocument();
expect(screen.getByLabelText("Max attempts")).toHaveValue(3);
});
it("Settings rules: labels, flag rules have no value input, one save sends status and value", async () => {
await openTab("Settings");
const length = await screen.findByLabelText("Minimum length value");
expect(length).toHaveValue(8);
expect(screen.getByText("No spaces")).toBeInTheDocument();
expect(screen.queryByLabelText("No spaces value")).not.toBeInTheDocument();
await userEvent.clear(length);
await userEvent.type(length, "10");
await userEvent.click(screen.getByRole("switch", { name: "No spaces" }));
await userEvent.click(screen.getByRole("button", { name: "Save password rules" }));
await waitFor(() => expect(mocks.savePasswordRules).toHaveBeenCalledWith([
{ id: 1, status: "Y", value: "10" },
{ id: 2, status: "Y", value: null },
]));
expect(await screen.findByText("Password rules saved.")).toBeInTheDocument();
});
it("Settings rules keep the edit and show the server message on error", async () => {
mocks.savePasswordRules.mockRejectedValue(new Error("Minimum is above maximum"));
await openTab("Settings");
const length = await screen.findByLabelText("Minimum length value");
await userEvent.clear(length);
await userEvent.type(length, "99");
await userEvent.click(screen.getByRole("button", { name: "Save password rules" }));
expect(await screen.findByText("Minimum is above maximum")).toBeInTheDocument();
expect(length).toHaveValue(99);
});
});
@@ -0,0 +1,377 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import type { ColumnDef } from "@tanstack/react-table";
import { Button } from "@/app/components/ui/button";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { Switch } from "@/app/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/app/components/ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
import { FilterField, FilterPanel, FilterSearch, FilterSelect } from "@/app/components/ui/filter-panel";
import { DataTable } from "@/app/components/ui/data-table";
import { DatePicker } from "@/app/components/ui/date-picker";
import { PageHeader } from "@/app/components/ui/page-header";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { RequireModule } from "@/app/lib/RequireModule";
import { useListFilters } from "@/app/lib/hooks/useListFilters";
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
import { formatEmailDate as formatDate } from "@/app/lib/services/adminEmails";
import {
FLAG_RULE_PARAMS, LOCKOUT_UNITS, LOGIN_EVENTS, LOGIN_EVENT_KEYS,
getConfig, getPasswordRules, listAudit, listLocked, saveConfig, savePasswordRules, unlock,
type AuditRow, type LockedAccount, type LockoutConfig, type PasswordRule,
} from "@/app/lib/services/loginSecurity";
import { useT } from "@/app/lib/i18n/MessagesProvider";
const DEFAULTS = { username: "", event: "", from: "", to: "" };
const errMessage = (err: unknown, fallback: string) => (err instanceof Error ? err.message : fallback);
function HistoryTab() {
const t = useT();
const { tableRef, pageSize } = useFitPageSize();
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
const [data, setData] = useState<{ items: AuditRow[]; total: number }>({ items: [], total: 0 });
const [loading, setLoading] = useState(true);
const [failed, setFailed] = useState(false);
const [reloadKey, setReloadKey] = useState(0);
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
useEffect(() => {
if (pageSize == null) return;
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the filter/page/reloadKey-triggered fetch below, which is the actual synchronization.
setLoading(true);
setFailed(false);
listAudit({
username: filters.username || undefined,
event: filters.event || undefined,
from: filters.from || undefined,
to: filters.to || undefined,
page,
pageSize,
})
.then((result) => { if (!cancelled) setData(result); })
.catch(() => { if (!cancelled) setFailed(true); })
.finally(() => { if (!cancelled) setLoading(false); });
return () => { cancelled = true; };
}, [filters, page, reloadKey, pageSize]);
const eventOptions = useMemo(() => LOGIN_EVENTS.map((e) => ({ value: e, label: t(LOGIN_EVENT_KEYS[e]) })), [t]);
const columns = useMemo<ColumnDef<AuditRow, unknown>[]>(
() => [
{ id: "datetime", header: t("LsTime"), enableSorting: false, cell: ({ row }) => formatDate(row.original.datetime) },
{ accessorKey: "username", header: t("Username"), enableSorting: false },
{ id: "event", header: t("LsEvent"), enableSorting: false, cell: ({ row }) => t(LOGIN_EVENT_KEYS[row.original.event] ?? row.original.event) },
{ accessorKey: "ipAddress", header: t("LsIp"), enableSorting: false },
{
id: "userAgent",
header: t("LsBrowser"),
enableSorting: false,
cell: ({ row }) => <span className="block max-w-xs truncate" title={row.original.userAgent ?? undefined}>{row.original.userAgent}</span>,
},
{ accessorKey: "message", header: t("LsNote"), enableSorting: false },
],
[t],
);
return (
<>
{failed && <ErrorState message={t("LsHistoryLoadFailed")} onRetry={refetch} className="mb-4" />}
<FilterPanel activeCount={activeCount} onClear={clear}>
<FilterField label={t("Username")}>
<FilterSearch className="w-full" aria-label={t("Username")} value={filters.username} onChange={(username) => set({ username })} />
</FilterField>
<FilterField label={t("LsEvent")}>
<FilterSelect className="w-full" aria-label={t("LsEvent")} allLabel={t("LsAllEvents")} options={eventOptions} value={filters.event} onChange={(event) => set({ event })} />
</FilterField>
<FilterField label={t("LsFrom")}>
<DatePicker aria-label={t("LsFrom")} value={filters.from} onChange={(from) => set({ from })} max={filters.to || undefined} />
</FilterField>
<FilterField label={t("LsTo")}>
<DatePicker aria-label={t("LsTo")} value={filters.to} onChange={(to) => set({ to })} min={filters.from || undefined} />
</FilterField>
</FilterPanel>
<DataTable
label={t("LsTabHistory")}
columns={columns}
data={data.items}
total={data.total}
page={page}
pageSize={pageSize ?? MIN_PAGE_SIZE}
tableRef={tableRef}
onPageChange={setPage}
isLoading={loading}
rowKey={(r) => String(r.id)}
empty={<EmptyState title={activeCount > 0 ? t("LsNoMatch") : t("LsNoHistory")} />}
/>
</>
);
}
function LockedTab() {
const t = useT();
const [rows, setRows] = useState<LockedAccount[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [reloadKey, setReloadKey] = useState(0);
const [target, setTarget] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
useEffect(() => {
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading ahead of the reloadKey-triggered fetch below.
setLoading(true);
listLocked()
.then((result) => { if (!cancelled) { setRows(result); setError(null); } })
.catch((err: unknown) => { if (!cancelled) setError(errMessage(err, "LsLockedLoadFailed")); })
.finally(() => { if (!cancelled) setLoading(false); });
return () => { cancelled = true; };
}, [reloadKey]);
async function confirmUnlock() {
if (!target) return;
setBusy(true);
try {
await unlock(target);
setError(null);
refetch();
} catch (err) {
setError(errMessage(err, "LsUnlockFailed"));
} finally {
setBusy(false);
setTarget(null);
}
}
const columns = useMemo<ColumnDef<LockedAccount, unknown>[]>(
() => [
{ accessorKey: "username", header: t("Username"), enableSorting: false },
{ accessorKey: "failures", header: t("LsFailures"), enableSorting: false },
{ id: "lastFailure", header: t("LsLastFailure"), enableSorting: false, cell: ({ row }) => formatDate(row.original.lastFailure ?? "") },
{ id: "lockedUntil", header: t("LsLockedUntil"), enableSorting: false, cell: ({ row }) => formatDate(row.original.lockedUntil ?? "") },
{
id: "actions",
header: "",
enableSorting: false,
cell: ({ row }) => (
<Button variant="outline" size="sm" onClick={() => setTarget(row.original.username)}>{t("LsUnlock")}</Button>
),
},
],
[t],
);
return (
<>
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
{/* ponytail: the locked list is small (only accounts currently locked), so it is shown unpaged. */}
<DataTable
label={t("LsTabLocked")}
columns={columns}
data={rows}
total={rows.length}
page={1}
pageSize={Math.max(rows.length, MIN_PAGE_SIZE)}
onPageChange={() => {}}
isLoading={loading}
rowKey={(r) => r.username}
empty={<EmptyState title={t("LsNoLocked")} />}
/>
<Dialog open={target !== null} onOpenChange={(open) => !open && setTarget(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("LsUnlockTitle")}</DialogTitle>
<DialogDescription>{t("LsUnlockConfirm", { username: target ?? "" })}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setTarget(null)} disabled={busy}>{t("Cancel")}</Button>
<Button onClick={confirmUnlock} disabled={busy}>{t("LsUnlock")}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}
type Notice = { kind: "ok" | "error"; text: string } | null;
function NoticeLine({ notice }: { notice: Notice }) {
if (!notice) return null;
return notice.kind === "error"
? <p role="alert" className="text-sm text-destructive">{notice.text}</p>
: <p role="status" className="text-sm text-foreground">{notice.text}</p>;
}
function LockoutForm() {
const t = useT();
const [cfg, setCfg] = useState<LockoutConfig | null>(null);
const [saving, setSaving] = useState(false);
const [notice, setNotice] = useState<Notice>(null);
useEffect(() => {
let cancelled = false;
getConfig()
.then((c) => { if (!cancelled) setCfg(c); })
.catch((err: unknown) => { if (!cancelled) setNotice({ kind: "error", text: t(errMessage(err, "LsSettingsLoadFailed")) }); });
return () => { cancelled = true; };
}, [t]);
if (!cfg) return <NoticeLine notice={notice} />;
async function save() {
if (!cfg) return;
setSaving(true);
setNotice(null);
try {
setCfg(await saveConfig(cfg));
setNotice({ kind: "ok", text: t("LsLockoutSaved") });
} catch (err) {
setNotice({ kind: "error", text: t(errMessage(err, "LsSaveFailed")) });
} finally {
setSaving(false);
}
}
const num = (v: string) => (v === "" ? 0 : Number(v));
return (
<section className="space-y-4 rounded-xl border bg-card p-4">
<h2 className="text-base font-semibold">{t("LsLockoutTitle")}</h2>
<div className="flex items-center gap-2">
<Switch id="ls-enabled" checked={cfg.enabled} onCheckedChange={(enabled) => setCfg({ ...cfg, enabled })} />
<Label htmlFor="ls-enabled">{t("LsLockoutOn")}</Label>
</div>
<div className="grid gap-4 sm:grid-cols-3">
<div className="space-y-1.5">
<Label htmlFor="ls-max">{t("LsMaxAttempts")}</Label>
<Input id="ls-max" type="number" min={1} value={cfg.maxAttempts || ""} onChange={(e) => setCfg({ ...cfg, maxAttempts: num(e.target.value) })} />
</div>
<div className="space-y-1.5">
<Label htmlFor="ls-period">{t("LsPeriod")}</Label>
<Input id="ls-period" type="number" min={1} value={cfg.period || ""} onChange={(e) => setCfg({ ...cfg, period: num(e.target.value) })} />
</div>
<div className="space-y-1.5">
<Label>{t("LsUnit")}</Label>
<Select value={cfg.unit} onValueChange={(unit) => setCfg({ ...cfg, unit: unit as LockoutConfig["unit"] })}>
<SelectTrigger aria-label={t("LsUnit")} className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
{LOCKOUT_UNITS.map((u) => <SelectItem key={u} value={u}>{t(`LsUnit${u}`)}</SelectItem>)}
</SelectContent>
</Select>
</div>
</div>
<div className="flex flex-wrap items-center gap-3">
<Button onClick={save} disabled={saving}>{t("LsSaveLockout")}</Button>
<NoticeLine notice={notice} />
</div>
</section>
);
}
type RuleEdit = { status: "Y" | "N"; value: string | null };
function PasswordRulesForm() {
const t = useT();
const [rules, setRules] = useState<PasswordRule[] | null>(null);
const [edits, setEdits] = useState<Record<number, RuleEdit>>({});
const [saving, setSaving] = useState(false);
const [notice, setNotice] = useState<Notice>(null);
const load = useCallback((list: PasswordRule[]) => {
setRules(list);
setEdits(Object.fromEntries(list.map((r) => [r.id, { status: r.status, value: r.value }])));
}, []);
useEffect(() => {
let cancelled = false;
getPasswordRules()
.then((list) => { if (!cancelled) load(list); })
.catch((err: unknown) => { if (!cancelled) setNotice({ kind: "error", text: t(errMessage(err, "LsSettingsLoadFailed")) }); });
return () => { cancelled = true; };
}, [t, load]);
if (!rules) return <NoticeLine notice={notice} />;
async function save() {
if (!rules) return;
setSaving(true);
setNotice(null);
try {
load(await savePasswordRules(rules.map((r) => ({ id: r.id, ...edits[r.id] }))));
setNotice({ kind: "ok", text: t("LsRulesSaved") });
} catch (err) {
setNotice({ kind: "error", text: t(errMessage(err, "LsSaveFailed")) });
} finally {
setSaving(false);
}
}
const edit = (id: number, patch: Partial<RuleEdit>) => setEdits((e) => ({ ...e, [id]: { ...e[id], ...patch } }));
return (
<section className="space-y-4 rounded-xl border bg-card p-4">
<h2 className="text-base font-semibold">{t("LsRulesTitle")}</h2>
<Table>
<TableHeader>
<TableRow>
<TableHead>{t("LsRuleName")}</TableHead>
<TableHead>{t("LsRuleOn")}</TableHead>
<TableHead>{t("LsRuleValue")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rules.map((r) => {
const label = t(`PwdRule_${r.param}`);
const e = edits[r.id];
return (
<TableRow key={r.id}>
<TableCell>{label}</TableCell>
<TableCell>
<Switch aria-label={label} checked={e.status === "Y"} onCheckedChange={(on) => edit(r.id, { status: on ? "Y" : "N" })} />
</TableCell>
<TableCell>
{!FLAG_RULE_PARAMS.includes(r.param) && (
<Input aria-label={`${label} ${t("LsRuleValue").toLowerCase()}`} type="number" min={0} className="w-24" value={e.value ?? ""} onChange={(ev) => edit(r.id, { value: ev.target.value })} />
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
<div className="flex flex-wrap items-center gap-3">
<Button onClick={save} disabled={saving}>{t("LsSaveRules")}</Button>
<NoticeLine notice={notice} />
</div>
</section>
);
}
function LoginSecurityContent() {
const t = useT();
return (
<>
<PageHeader title={t("BO_LOGIN_SECURITY")} />
<Tabs defaultValue="history">
<TabsList>
<TabsTrigger value="history">{t("LsTabHistory")}</TabsTrigger>
<TabsTrigger value="locked">{t("LsTabLocked")}</TabsTrigger>
<TabsTrigger value="settings">{t("LsTabSettings")}</TabsTrigger>
</TabsList>
<TabsContent value="history"><HistoryTab /></TabsContent>
<TabsContent value="locked"><LockedTab /></TabsContent>
<TabsContent value="settings" className="space-y-4"><LockoutForm /><PasswordRulesForm /></TabsContent>
</Tabs>
</>
);
}
export default function LoginSecurityPage() {
return (
<RequireModule pathname="/login-security">
<LoginSecurityContent />
</RequireModule>
);
}