From 091503a820e56e7332b866e290826bcf0b0ffe06 Mon Sep 17 00:00:00 2001 From: ngqile Date: Mon, 30 Nov 2026 14:33:53 +0800 Subject: [PATCH] feat: Login security screen with history, locked accounts and settings Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../changes/add-admin-login-security/tasks.md | 2 +- .../login-security/[[...path]]/route.test.ts | 74 ++++ .../api/login-security/[[...path]]/route.ts | 30 ++ .../app/components/ui/tabs.tsx | 89 +++++ .../app/lib/i18n/defaultMessages.ts | 63 +++ .../app/lib/routeModules.test.ts | 2 +- solvway-admin-portal/app/lib/routeModules.ts | 1 + .../app/lib/services/loginSecurity.test.ts | 53 +++ .../app/lib/services/loginSecurity.ts | 80 ++++ .../app/login-security/page.test.tsx | 156 ++++++++ .../app/login-security/page.tsx | 377 ++++++++++++++++++ 11 files changed, 925 insertions(+), 2 deletions(-) create mode 100644 solvway-admin-portal/app/api/login-security/[[...path]]/route.test.ts create mode 100644 solvway-admin-portal/app/api/login-security/[[...path]]/route.ts create mode 100644 solvway-admin-portal/app/components/ui/tabs.tsx create mode 100644 solvway-admin-portal/app/lib/services/loginSecurity.test.ts create mode 100644 solvway-admin-portal/app/lib/services/loginSecurity.ts create mode 100644 solvway-admin-portal/app/login-security/page.test.tsx create mode 100644 solvway-admin-portal/app/login-security/page.tsx diff --git a/openspec/changes/add-admin-login-security/tasks.md b/openspec/changes/add-admin-login-security/tasks.md index c8d2bce..b3a7743 100644 --- a/openspec/changes/add-admin-login-security/tasks.md +++ b/openspec/changes/add-admin-login-security/tasks.md @@ -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; diff --git a/solvway-admin-portal/app/api/login-security/[[...path]]/route.test.ts b/solvway-admin-portal/app/api/login-security/[[...path]]/route.test.ts new file mode 100644 index 0000000..39f03f3 --- /dev/null +++ b/solvway-admin-portal/app/api/login-security/[[...path]]/route.test.ts @@ -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[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[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" }); + }); +}); diff --git a/solvway-admin-portal/app/api/login-security/[[...path]]/route.ts b/solvway-admin-portal/app/api/login-security/[[...path]]/route.ts new file mode 100644 index 0000000..0d121fa --- /dev/null +++ b/solvway-admin-portal/app/api/login-security/[[...path]]/route.ts @@ -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(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); diff --git a/solvway-admin-portal/app/components/ui/tabs.tsx b/solvway-admin-portal/app/components/ui/tabs.tsx new file mode 100644 index 0000000..8766f2a --- /dev/null +++ b/solvway-admin-portal/app/components/ui/tabs.tsx @@ -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) { + return ( + + ) +} + +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 & + VariantProps) { + return ( + + ) +} + +function TabsTrigger({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function TabsContent({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants } diff --git a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts index a23f7eb..beda955 100644 --- a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts +++ b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts @@ -323,4 +323,67 @@ export const DEFAULT_MESSAGES: Record = { 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", }; diff --git a/solvway-admin-portal/app/lib/routeModules.test.ts b/solvway-admin-portal/app/lib/routeModules.test.ts index 334cc9e..3450412 100644 --- a/solvway-admin-portal/app/lib/routeModules.test.ts +++ b/solvway-admin-portal/app/lib/routeModules.test.ts @@ -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"); }); diff --git a/solvway-admin-portal/app/lib/routeModules.ts b/solvway-admin-portal/app/lib/routeModules.ts index f87c33f..e6c7ba6 100644 --- a/solvway-admin-portal/app/lib/routeModules.ts +++ b/solvway-admin-portal/app/lib/routeModules.ts @@ -10,6 +10,7 @@ export const ROUTE_MODULES: Record = { "/event-leads": "BO_EVENT_LEADS", "/leads": "BO_LEADS", "/emails": "BO_EMAILS", + "/login-security": "BO_LOGIN_SECURITY", }; export function requiredModuleFor(pathname: string): string | undefined { diff --git a/solvway-admin-portal/app/lib/services/loginSecurity.test.ts b/solvway-admin-portal/app/lib/services/loginSecurity.test.ts new file mode 100644 index 0000000..443370a --- /dev/null +++ b/solvway-admin-portal/app/lib/services/loginSecurity.test.ts @@ -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); + }); +}); diff --git a/solvway-admin-portal/app/lib/services/loginSecurity.ts b/solvway-admin-portal/app/lib/services/loginSecurity.ts new file mode 100644 index 0000000..f2dda3c --- /dev/null +++ b/solvway-admin-portal/app/lib/services/loginSecurity.ts @@ -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; + +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(`${BASE}/locked`); +export const unlock = (username: string) => apiPost(`${BASE}/locked/${encodeURIComponent(username)}/unlock`); +export const getConfig = () => apiGet(`${BASE}/config`); +export const saveConfig = (cfg: LockoutConfig) => apiPut(`${BASE}/config`, cfg); +export const getPasswordRules = () => apiGet(`${BASE}/password-rules`); +export const savePasswordRules = (rules: PasswordRuleUpdate[]) => apiPut(`${BASE}/password-rules`, rules); + +export const LOGIN_EVENT_KEYS: Record = { + 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"]; diff --git a/solvway-admin-portal/app/login-security/page.test.tsx b/solvway-admin-portal/app/login-security/page.test.tsx new file mode 100644 index 0000000..07ce764 --- /dev/null +++ b/solvway-admin-portal/app/login-security/page.test.tsx @@ -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()), + 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(); + 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(); + 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(); + 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(); + expect(await screen.findByText("No sign-in history found")).toBeInTheDocument(); + unmount(); + mocks.listAudit.mockRejectedValue(new Error("LsHistoryLoadFailed")); + render(); + expect(await screen.findByRole("alert")).toHaveTextContent("Failed to load the sign-in history"); + }); + + async function openTab(name: string) { + render(); + 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); + }); +}); diff --git a/solvway-admin-portal/app/login-security/page.tsx b/solvway-admin-portal/app/login-security/page.tsx new file mode 100644 index 0000000..b2516ac --- /dev/null +++ b/solvway-admin-portal/app/login-security/page.tsx @@ -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[]>( + () => [ + { 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 }) => {row.original.userAgent}, + }, + { accessorKey: "message", header: t("LsNote"), enableSorting: false }, + ], + [t], + ); + + return ( + <> + {failed && } + + + set({ username })} /> + + + set({ event })} /> + + + set({ from })} max={filters.to || undefined} /> + + + set({ to })} min={filters.from || undefined} /> + + + String(r.id)} + empty={ 0 ? t("LsNoMatch") : t("LsNoHistory")} />} + /> + + ); +} + +function LockedTab() { + const t = useT(); + const [rows, setRows] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [reloadKey, setReloadKey] = useState(0); + const [target, setTarget] = useState(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[]>( + () => [ + { 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 }) => ( + + ), + }, + ], + [t], + ); + + return ( + <> + {error && } + {/* ponytail: the locked list is small (only accounts currently locked), so it is shown unpaged. */} + {}} + isLoading={loading} + rowKey={(r) => r.username} + empty={} + /> + !open && setTarget(null)}> + + + {t("LsUnlockTitle")} + {t("LsUnlockConfirm", { username: target ?? "" })} + + + + + + + + + ); +} + +type Notice = { kind: "ok" | "error"; text: string } | null; + +function NoticeLine({ notice }: { notice: Notice }) { + if (!notice) return null; + return notice.kind === "error" + ?

{notice.text}

+ :

{notice.text}

; +} + +function LockoutForm() { + const t = useT(); + const [cfg, setCfg] = useState(null); + const [saving, setSaving] = useState(false); + const [notice, setNotice] = useState(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 ; + + 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 ( +
+

{t("LsLockoutTitle")}

+
+ setCfg({ ...cfg, enabled })} /> + +
+
+
+ + setCfg({ ...cfg, maxAttempts: num(e.target.value) })} /> +
+
+ + setCfg({ ...cfg, period: num(e.target.value) })} /> +
+
+ + +
+
+
+ + +
+
+ ); +} + +type RuleEdit = { status: "Y" | "N"; value: string | null }; + +function PasswordRulesForm() { + const t = useT(); + const [rules, setRules] = useState(null); + const [edits, setEdits] = useState>({}); + const [saving, setSaving] = useState(false); + const [notice, setNotice] = useState(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 ; + + 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) => setEdits((e) => ({ ...e, [id]: { ...e[id], ...patch } })); + + return ( +
+

{t("LsRulesTitle")}

+ + + + {t("LsRuleName")} + {t("LsRuleOn")} + {t("LsRuleValue")} + + + + {rules.map((r) => { + const label = t(`PwdRule_${r.param}`); + const e = edits[r.id]; + return ( + + {label} + + edit(r.id, { status: on ? "Y" : "N" })} /> + + + {!FLAG_RULE_PARAMS.includes(r.param) && ( + edit(r.id, { value: ev.target.value })} /> + )} + + + ); + })} + +
+
+ + +
+
+ ); +} + +function LoginSecurityContent() { + const t = useT(); + return ( + <> + + + + {t("LsTabHistory")} + {t("LsTabLocked")} + {t("LsTabSettings")} + + + + + + + ); +} + +export default function LoginSecurityPage() { + return ( + + + + ); +}