feat: locked sign-in message and Change password dialog in the portal

mobile-api now records the browser user agent the portal forwards as
X-Client-User-Agent instead of the portal server's own.

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:16:11 +08:00
1 parent 5ce684168a
commit 6598b58cb8
14 files changed
+364 -12

No files matched your search

@@ -56,7 +56,7 @@ Design: `design.md`. All tasks run serially: each builds on the one before.
- a success records `LOGIN_SUCCESS`;
- a record failure does not change the answer;
- logout records `LOGOUT`;
- the IP and user agent are taken from `X-Client-IP` and `User-Agent`.
- the IP and user agent are taken from `X-Client-Ip` and `X-Client-User-Agent`.
- Scope: `solvway-mobile-api/src/**` (`AdminAuthController`, a new login-audit client, constants, tests)
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
@@ -87,8 +87,8 @@ Design: `design.md`. All tasks run serially: each builds on the one before.
## 4. Portal
- [ ] 4.1 Sign-in pieces (design decisions 6 and 9).
- The login and logout routes forward `X-Client-IP` and `User-Agent`.
- [x] 4.1 Sign-in pieces (design decisions 6 and 9).
- The login and logout routes forward `X-Client-Ip` and `X-Client-User-Agent`.
- The login page shows the locked message on `ACCOUNT_LOCKED`.
- Header "Change password" item opens `ChangePasswordDialog`, using the `/api/auth/change-password` route.
- **Tests first:**
@@ -0,0 +1,48 @@
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 { POST } from "./route";
function req(body: unknown) {
return new Request("http://localhost/api/auth/change-password", {
method: "POST",
body: JSON.stringify(body),
}) as unknown as Parameters<typeof POST>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
});
describe("POST /api/auth/change-password", () => {
it("returns 401 when there is no session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await POST(req({}));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards only the three password fields and answers 204", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: null });
const res = await POST(req({ currentPassword: "Old#1", newPassword: "New#1", confirmPassword: "New#1", extra: 1 }));
expect(res.status).toBe(204);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/auth/change-password", {
method: "POST",
body: { currentPassword: "Old#1", newPassword: "New#1", confirmPassword: "New#1" },
token: "jwt-abc",
});
});
it("passes a refusal through with its code", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 400, error: "Current password is wrong", code: "CURRENT_PASSWORD_WRONG" });
const res = await POST(req({}));
expect(res.status).toBe(400);
expect(await res.json()).toMatchObject({ error: "Current password is wrong", code: "CURRENT_PASSWORD_WRONG" });
});
});
@@ -0,0 +1,22 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
/** The signed-in admin changes their own password; only the three fields are forwarded, and nothing is logged. */
export async function POST(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
const { currentPassword, newPassword, confirmPassword } = (await req.json().catch(() => ({}))) as {
currentPassword?: string;
newPassword?: string;
confirmPassword?: string;
};
const result = await callMobileApi<null>("/api/admin/auth/change-password", {
method: "POST",
body: { currentPassword, newPassword, confirmPassword },
token,
});
if (!result.ok) return errorResponse(result);
return new NextResponse(null, { status: 204 });
}
@@ -0,0 +1,34 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), setSession: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
vi.mock("@/app/lib/server/session", () => ({ setSession: mocks.setSession }));
import { POST } from "./route";
function req() {
return new Request("http://localhost/api/auth/login", {
method: "POST",
body: JSON.stringify({ username: "sales1", password: "x" }),
}) as unknown as Parameters<typeof POST>[0];
}
beforeEach(() => {
mocks.callMobileApi.mockReset();
});
describe("POST /api/auth/login: locked account", () => {
it("keeps the ACCOUNT_LOCKED code on the 401", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 401, error: "Too many failed sign-ins.", code: "ACCOUNT_LOCKED" });
const res = await POST(req());
expect(res.status).toBe(401);
expect(await res.json()).toMatchObject({ error: "Too many failed sign-ins.", code: "ACCOUNT_LOCKED" });
});
it("leaves other 401s without a code", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 401, error: "Invalid username or password" });
const res = await POST(req());
expect(res.status).toBe(401);
expect((await res.json()).code).toBeUndefined();
});
});
@@ -31,9 +31,9 @@ export async function POST(req: NextRequest) {
if (!result.ok) {
// The mobile-api answers bad credentials with HTTP 401 directly (not the
// expired-token signal), so surface it as 401 rather than the generic 400.
// A confirmed-locked account comes back as 423 with its own message, which
// errorResponse forwards as-is (4xx passthrough).
if (result.status === 401) return unauthorized(result.error);
// A locked account is also a 401, but carries code ACCOUNT_LOCKED, which the
// login page needs to show its own message; errorResponse keeps the code.
if (result.status === 401 && result.code !== "ACCOUNT_LOCKED") return unauthorized(result.error);
return errorResponse(result);
}
@@ -0,0 +1,79 @@
"use client";
import { useState, type FormEvent } from "react";
import { Button } from "@/app/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { PasswordFields } from "@/app/components/users/PasswordFields";
import { changeOwnPassword } from "@/app/lib/services/adminUsers";
import { useT } from "@/app/lib/i18n/MessagesProvider";
/** The signed-in admin's own password change; mounted only while open, so every field starts empty. */
export default function ChangePasswordDialog({ onClose, onDone }: { onClose: () => void; onDone: () => void }) {
const t = useT();
const [current, setCurrent] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!current || !password || !confirmPassword) return setError("PwdChangeRequired");
if (password !== confirmPassword) return setError("UsrPasswordMismatch");
setSaving(true);
setError(null);
try {
await changeOwnPassword(current, password, confirmPassword);
onClose();
onDone();
} catch (err) {
setError(err instanceof Error ? err.message : "PwdChangeRequired");
setSaving(false);
}
}
return (
<Dialog open onOpenChange={(o) => !o && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("PwdChangeMenu")}</DialogTitle>
</DialogHeader>
<form onSubmit={submit} className="space-y-4" noValidate>
<div className="space-y-1.5">
<Label htmlFor="current-password">{t("PwdCurrent")}</Label>
<Input
id="current-password"
type="password"
autoComplete="current-password"
value={current}
onChange={(e) => setCurrent(e.target.value)}
disabled={saving}
/>
</div>
<PasswordFields
password={password}
confirmPassword={confirmPassword}
onPassword={setPassword}
onConfirmPassword={setConfirmPassword}
disabled={saving}
/>
{error && (
<div role="alert" className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">
{t(error)}
</div>
)}
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose}>
{t("Cancel")}
</Button>
<Button type="submit" disabled={saving}>
{t("PwdChangeMenu")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,85 @@
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { ApiError } from "@/app/lib/clientApi";
vi.mock("next/navigation", () => ({
useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }),
usePathname: () => "/",
}));
vi.mock("@/app/lib/useAclSidebar", () => ({ useAclSidebar: () => [] }));
vi.mock("@/app/lib/AdminAuthContext", () => ({
useAdminAuth: () => ({ name: "Admin User", hasModule: () => false }),
}));
vi.mock("@/app/lib/theme", () => ({ useTheme: () => ({ theme: "light", toggleTheme: vi.fn() }) }));
const mocks = vi.hoisted(() => ({ changeOwnPassword: vi.fn() }));
vi.mock("@/app/lib/services/adminUsers", () => ({ changeOwnPassword: mocks.changeOwnPassword }));
import Header from "./Header";
beforeEach(() => {
mocks.changeOwnPassword.mockReset();
});
async function openDialog() {
await userEvent.click(screen.getByRole("button", { name: /admin user/i }));
await userEvent.click(await screen.findByText("Change password"));
}
describe("Header: change password", () => {
it("lists Change password above Sign out", async () => {
render(<Header />);
await userEvent.click(screen.getByRole("button", { name: /admin user/i }));
const items = (await screen.findAllByRole("menuitem")).map((i) => i.textContent);
expect(items).toEqual(["Change password", "Logout"]);
});
it("blocks empty fields and mismatched passwords without calling the server", async () => {
render(<Header />);
await openDialog();
await userEvent.click(screen.getByRole("button", { name: "Change password" }));
expect(await screen.findByRole("alert")).toHaveTextContent("Fill in all the password fields.");
await userEvent.type(screen.getByLabelText("Current password"), "Old#1");
await userEvent.type(screen.getByLabelText("Password"), "New#1");
await userEvent.type(screen.getByLabelText("Confirm password"), "Other#1");
await userEvent.click(screen.getByRole("button", { name: "Change password" }));
expect(await screen.findByRole("alert")).toHaveTextContent("The passwords do not match.");
expect(mocks.changeOwnPassword).not.toHaveBeenCalled();
});
it("submits, closes, confirms, and starts empty next time", async () => {
mocks.changeOwnPassword.mockResolvedValue(undefined);
render(<Header />);
await openDialog();
expect(screen.getByLabelText("Current password")).toHaveAttribute("autocomplete", "current-password");
await userEvent.type(screen.getByLabelText("Current password"), "Old#1");
await userEvent.type(screen.getByLabelText("Password"), "New#1");
await userEvent.type(screen.getByLabelText("Confirm password"), "New#1");
await userEvent.click(screen.getByRole("button", { name: "Change password" }));
await waitFor(() => expect(mocks.changeOwnPassword).toHaveBeenCalledWith("Old#1", "New#1", "New#1"));
await waitFor(() => expect(screen.queryByLabelText("Current password")).not.toBeInTheDocument());
expect(screen.getByText("Your password has been changed.")).toBeInTheDocument();
await openDialog();
expect(screen.getByLabelText("Current password")).toHaveValue("");
expect(screen.getByLabelText("Password")).toHaveValue("");
});
it("shows the server message on failure and clears the fields on cancel", async () => {
mocks.changeOwnPassword.mockRejectedValue(new ApiError("Current password is incorrect.", 400, { code: "CURRENT_PASSWORD_WRONG" }));
render(<Header />);
await openDialog();
await userEvent.type(screen.getByLabelText("Current password"), "bad");
await userEvent.type(screen.getByLabelText("Password"), "New#1");
await userEvent.type(screen.getByLabelText("Confirm password"), "New#1");
await userEvent.click(screen.getByRole("button", { name: "Change password" }));
expect(await screen.findByRole("alert")).toHaveTextContent("Current password is incorrect.");
await userEvent.click(screen.getByRole("button", { name: "Cancel" }));
await openDialog();
expect(screen.getByLabelText("Current password")).toHaveValue("");
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
});
@@ -1,7 +1,7 @@
"use client";
import { useState } from "react";
import { LogOut, Menu, Moon, Sun } from "lucide-react";
import { KeyRound, LogOut, Menu, Moon, Sun } from "lucide-react";
import { useRouter } from "next/navigation";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { useTheme } from "@/app/lib/theme";
@@ -20,6 +20,7 @@ import { Sheet, SheetContent, SheetTitle } from "@/app/components/ui/sheet";
import Breadcrumbs from "./Breadcrumbs";
import { BrandLink, SidebarNav } from "./Sidebar";
import LocaleSwitcher from "./LocaleSwitcher";
import ChangePasswordDialog from "./ChangePasswordDialog";
// The authenticated shell's header: user menu reads the signed-in name from
// AdminAuthContext (session hydration, Task 5), and logout calls the
@@ -31,6 +32,8 @@ export default function Header() {
const t = useT();
const router = useRouter();
const [menuOpen, setMenuOpen] = useState(false);
const [changingPassword, setChangingPassword] = useState(false);
const [changed, setChanged] = useState(false);
async function handleLogout() {
// Best-effort: /api/auth/logout clears the httpOnly cookie regardless of
@@ -100,6 +103,10 @@ export default function Header() {
<span className="block text-sm font-medium">{name}</span>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => setChangingPassword(true)}>
<KeyRound aria-hidden="true" className="size-4" />
{t("PwdChangeMenu")}
</DropdownMenuItem>
<DropdownMenuItem onClick={handleLogout}>
<LogOut aria-hidden="true" className="size-4" />
{t("Logout")}
@@ -107,6 +114,20 @@ export default function Header() {
</DropdownMenuContent>
</DropdownMenu>
</div>
{changingPassword && (
<ChangePasswordDialog
onClose={() => setChangingPassword(false)}
onDone={() => {
setChanged(true);
setTimeout(() => setChanged(false), 5000);
}}
/>
)}
{changed && (
<div role="status" className="fixed right-4 bottom-4 z-50 rounded-md border bg-card px-4 py-3 text-sm shadow-md">
{t("PwdChanged")}
</div>
)}
</header>
);
}
@@ -77,6 +77,11 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
NotFoundBody: "That route does not exist in the back office.",
LayoutMetaDescription: "Co-Lite admin back office",
LoginInvalidCredentials: "Invalid username or password",
LoginAccountLocked: "Too many failed sign-ins. Try again later or ask an administrator to unlock your account.",
PwdChangeMenu: "Change password",
PwdCurrent: "Current password",
PwdChangeRequired: "Fill in all the password fields.",
PwdChanged: "Your password has been changed.",
LoginHidePassword: "Hide password",
LoginShowPassword: "Show password",
ResetAllRequired: "All fields are required.",
@@ -63,6 +63,11 @@ export async function saveAdminUser(payload: AdminUser): Promise<AdminUser> {
: apiPost<AdminUser>("/api/users", payload);
}
/** The signed-in admin changes their own password. */
export async function changeOwnPassword(currentPassword: string, newPassword: string, confirmPassword: string): Promise<void> {
await apiPost<void>("/api/auth/change-password", { currentPassword, newPassword, confirmPassword });
}
/** Admin-typed temporary password; the user must change it at next sign-in. */
export async function setAdminUserPassword(id: number, password: string, confirmPassword: string): Promise<void> {
await apiPost<void>(`/api/users/${id}/password`, { password, confirmPassword });
@@ -0,0 +1,51 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ apiPost: vi.fn() }));
vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }));
vi.mock("@/app/lib/clientApi", async () => {
class ApiError extends Error {
status: number;
data?: unknown;
constructor(message: string, status: number, data?: unknown) {
super(message);
this.status = status;
this.data = data;
}
}
return { apiPost: mocks.apiPost, ApiError };
});
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: () => ({ refresh: vi.fn() }) }));
import LoginPage from "./page";
import { ApiError } from "@/app/lib/clientApi";
import { DEFAULT_MESSAGES } from "@/app/lib/i18n/defaultMessages";
beforeEach(() => {
mocks.apiPost.mockReset();
});
async function submit() {
render(<LoginPage />);
await userEvent.type(screen.getByLabelText("Username"), "sales1");
await userEvent.type(screen.getByLabelText("Password"), "x");
await userEvent.click(screen.getByRole("button", { name: "Log in" }));
}
describe("LoginPage: locked account", () => {
it("shows the locked message when the body code is ACCOUNT_LOCKED", async () => {
mocks.apiPost.mockRejectedValue(new ApiError("server text", 401, { error: "server text", code: "ACCOUNT_LOCKED" }));
await submit();
expect(await screen.findByText(DEFAULT_MESSAGES.LoginAccountLocked)).toBeInTheDocument();
expect(DEFAULT_MESSAGES.LoginAccountLocked).toBe(
"Too many failed sign-ins. Try again later or ask an administrator to unlock your account.",
);
});
it("shows the server message for other failures", async () => {
mocks.apiPost.mockRejectedValue(new ApiError("Invalid username or password", 401, { error: "Invalid username or password" }));
await submit();
expect(await screen.findByText("Invalid username or password")).toBeInTheDocument();
});
});
+3 -2
View File
@@ -8,7 +8,7 @@ import { Button } from "@/app/components/ui/button";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { ErrorState } from "@/app/components/ui/states";
import { apiPost } from "@/app/lib/clientApi";
import { ApiError, apiPost } from "@/app/lib/clientApi";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import PoweredBy from "@/app/components/app/PoweredBy";
@@ -64,7 +64,8 @@ export default function LoginPage() {
// replace keeps the root layout, whose locale list was loaded without a token; re-run it.
router.refresh();
} catch (err) {
setError(err instanceof Error ? err.message : "LoginInvalidCredentials");
const locked = err instanceof ApiError && (err.data as { code?: unknown } | undefined)?.code === "ACCOUNT_LOCKED";
setError(locked ? "LoginAccountLocked" : err instanceof Error ? err.message : "LoginInvalidCredentials");
} finally {
setSubmitting(false);
}
@@ -94,7 +94,7 @@ public class AdminAuthenticationService {
}
}
/** Best-effort login history entry with the caller's X-Client-IP and User-Agent; never throws. */
/** Best-effort login history entry with the caller's X-Client-IP and X-Client-User-Agent; never throws. */
public void record(String username, String event, String message) {
try {
HttpServletRequest req = RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes a
@@ -103,7 +103,7 @@ public class AdminAuthenticationService {
body.put("username", username);
body.put("event", event);
body.put("ip", req == null ? null : req.getHeader("X-Client-IP"));
body.put("userAgent", req == null ? null : req.getHeader("User-Agent"));
body.put("userAgent", req == null ? null : req.getHeader("X-Client-User-Agent"));
body.put("message", message);
restTemplateUtil.postForEntity(
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_RECORD),
@@ -76,7 +76,8 @@ class AdminAuthenticationServiceLoginSecurityTest {
void record_sendsClientIpAndUserAgentFromRequest() {
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("X-Client-IP", "203.0.113.7");
req.addHeader("User-Agent", "JUnit");
req.addHeader("X-Client-User-Agent", "JUnit");
req.addHeader("User-Agent", "node");
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(req));
when(rest.postForEntity(any(String.class), eq(String.class), any())).thenReturn(ResponseEntity.ok(""));