feat: admin login security (history, lockout, unlock) and own password change #19
No files matched your search
@@ -0,0 +1,29 @@
|
||||
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";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset();
|
||||
});
|
||||
|
||||
describe("POST /api/auth/change-password: client context", () => {
|
||||
it("forwards the browser IP and user agent for the login history", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: null });
|
||||
const req = new Request("http://localhost/api/auth/change-password", {
|
||||
method: "POST",
|
||||
headers: { "x-forwarded-for": "198.51.100.7", "user-agent": "Browser/1.0" },
|
||||
body: JSON.stringify({ currentPassword: "a", newPassword: "b", confirmPassword: "b" }),
|
||||
}) as unknown as Parameters<typeof POST>[0];
|
||||
await POST(req);
|
||||
expect(mocks.callMobileApi.mock.calls[0][1].headers).toEqual({
|
||||
"X-Client-Ip": "198.51.100.7",
|
||||
"X-Client-User-Agent": "Browser/1.0",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -35,6 +35,7 @@ describe("POST /api/auth/change-password", () => {
|
||||
method: "POST",
|
||||
body: { currentPassword: "Old#1", newPassword: "New#1", confirmPassword: "New#1" },
|
||||
token: "jwt-abc",
|
||||
headers: {},
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ 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";
|
||||
import { clientContextHeaders } from "@/app/lib/server/clientContext";
|
||||
|
||||
/** The signed-in admin changes their own password; only the three fields are forwarded, and nothing is logged. */
|
||||
export async function POST(req: NextRequest) {
|
||||
@@ -16,6 +17,8 @@ export async function POST(req: NextRequest) {
|
||||
method: "POST",
|
||||
body: { currentPassword, newPassword, confirmPassword },
|
||||
token,
|
||||
// The browser IP and user agent go into the login history rows this call writes.
|
||||
headers: clientContextHeaders(req),
|
||||
});
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
|
||||
vi.mock("@/app/lib/i18n/MessagesProvider", () => ({ useT: () => (k: string) => k }));
|
||||
vi.mock("@/app/lib/services/adminUsers", () => ({ changeOwnPassword: vi.fn() }));
|
||||
|
||||
import ChangePasswordDialog from "./ChangePasswordDialog";
|
||||
|
||||
describe("ChangePasswordDialog labels", () => {
|
||||
it("labels the new password field as the new password", () => {
|
||||
render(<ChangePasswordDialog onClose={() => {}} onDone={() => {}} />);
|
||||
expect(screen.getByLabelText("PwdNew")).toHaveAttribute("autocomplete", "new-password");
|
||||
expect(screen.getByLabelText("PwdCurrent")).toHaveAttribute("autocomplete", "current-password");
|
||||
});
|
||||
});
|
||||
@@ -53,6 +53,7 @@ export default function ChangePasswordDialog({ onClose, onDone }: { onClose: ()
|
||||
/>
|
||||
</div>
|
||||
<PasswordFields
|
||||
passwordLabel="PwdNew"
|
||||
password={password}
|
||||
confirmPassword={confirmPassword}
|
||||
onPassword={setPassword}
|
||||
|
||||
@@ -41,7 +41,7 @@ describe("Header: 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("New 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.");
|
||||
@@ -54,7 +54,7 @@ describe("Header: change password", () => {
|
||||
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("New password"), "New#1");
|
||||
await userEvent.type(screen.getByLabelText("Confirm password"), "New#1");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Change password" }));
|
||||
|
||||
@@ -64,7 +64,7 @@ describe("Header: change password", () => {
|
||||
|
||||
await openDialog();
|
||||
expect(screen.getByLabelText("Current password")).toHaveValue("");
|
||||
expect(screen.getByLabelText("Password")).toHaveValue("");
|
||||
expect(screen.getByLabelText("New password")).toHaveValue("");
|
||||
});
|
||||
|
||||
it("shows the server message on failure and clears the fields on cancel", async () => {
|
||||
@@ -72,7 +72,7 @@ describe("Header: change password", () => {
|
||||
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("New 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.");
|
||||
|
||||
@@ -13,12 +13,14 @@ export function PasswordFields(props: {
|
||||
disabled?: boolean;
|
||||
passwordError?: string;
|
||||
confirmError?: string;
|
||||
/** i18n key for the first field's label; "Password" by default. */
|
||||
passwordLabel?: string;
|
||||
}) {
|
||||
const t = useT();
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="user-password">{t("Password")}</Label>
|
||||
<Label htmlFor="user-password">{t(props.passwordLabel ?? "Password")}</Label>
|
||||
<Input
|
||||
id="user-password"
|
||||
type="password"
|
||||
|
||||
@@ -80,6 +80,7 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
LoginAccountLocked: "Too many failed sign-ins. Try again later or ask an administrator to unlock your account.",
|
||||
PwdChangeMenu: "Change password",
|
||||
PwdCurrent: "Current password",
|
||||
PwdNew: "New password",
|
||||
PwdChangeRequired: "Fill in all the password fields.",
|
||||
PwdChanged: "Your password has been changed.",
|
||||
LoginHidePassword: "Hide password",
|
||||
|
||||
+5
-5
@@ -118,9 +118,9 @@ public class LoginSecurityService {
|
||||
@Transactional
|
||||
public Config saveConfig(Config c) {
|
||||
if (c == null) throw new IllegalArgumentException("body is required");
|
||||
if (c.maxAttempts() < 1) throw new IllegalArgumentException("maxAttempts must be at least 1");
|
||||
if (c.period() < 1) throw new IllegalArgumentException("period must be at least 1");
|
||||
if (c.chronoUnit() == null) throw new IllegalArgumentException("unit must be S, M, H or D");
|
||||
if (c.maxAttempts() < 1) throw new IllegalArgumentException("Max attempts must be at least 1");
|
||||
if (c.period() < 1) throw new IllegalArgumentException("Period must be at least 1");
|
||||
if (c.chronoUnit() == null) throw new IllegalArgumentException("Unit must be seconds, minutes, hours or days");
|
||||
put(BLOCK, PERIOD_PARAM, c.enabled() ? "Y" : "N", String.valueOf(c.period()));
|
||||
put(BLOCK, MAX_PARAM, null, String.valueOf(c.maxAttempts()));
|
||||
put(UNIT, "ADMIN_LOGIN_BLOCK_TIME_UNIT", null, c.unit());
|
||||
@@ -138,13 +138,13 @@ public class LoginSecurityService {
|
||||
List<PasswordRuleProperty> rows = new ArrayList<>();
|
||||
for (Rule in : input) { // validate everything before saving anything
|
||||
if (in == null) throw new IllegalArgumentException("rule is required");
|
||||
if (!"Y".equals(in.status()) && !"N".equals(in.status())) throw new IllegalArgumentException("status must be Y or N");
|
||||
if (!"Y".equals(in.status()) && !"N".equals(in.status())) throw new IllegalArgumentException("Each rule must be on or off");
|
||||
if (in.id() == null) throw new IllegalArgumentException("id is required");
|
||||
PasswordRuleProperty row = properties.findById(in.id()).filter(r -> PWD.equals(r.getType()))
|
||||
.orElseThrow(() -> new IllegalArgumentException("unknown password rule " + in.id()));
|
||||
String p = row.getParam();
|
||||
if (in.value() != null && p != null && (p.endsWith("_MIN") || p.endsWith("_MAX")) && !in.value().matches("\\d{1,9}"))
|
||||
throw new IllegalArgumentException(p + " must be a non-negative integer");
|
||||
throw new IllegalArgumentException("Rule values must be whole numbers");
|
||||
rows.add(row);
|
||||
}
|
||||
for (int i = 0; i < rows.size(); i++) {
|
||||
|
||||
+7
@@ -333,6 +333,13 @@ class LoginSecurityServiceTest {
|
||||
verify(properties, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void settingsErrorsReadAsPlainText() {
|
||||
assertThatThrownBy(() -> service.saveConfig(new Config(true, 0, 15, "M"))).hasMessage("Max attempts must be at least 1");
|
||||
assertThatThrownBy(() -> service.saveConfig(new Config(true, 5, 0, "M"))).hasMessage("Period must be at least 1");
|
||||
assertThatThrownBy(() -> service.saveConfig(new Config(true, 5, 15, "X"))).hasMessage("Unit must be seconds, minutes, hours or days");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validConfigUpdatesThreeRowsAndEnabledSetsPeriodStatus() {
|
||||
settings("Y", "15", "4", "H");
|
||||
|
||||
Reference in new issue
Block a user