fix(admin-portal): drop the direct set-password dialog; the emailed reset stays

An admin could set a colleague's password to a value of their choosing. Only the
emailed temporary-password reset remains.

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-26 22:29:38 +08:00
1 parent 92c8ad3b25
commit 816c8bcb5e
11 files changed
+3 -314

No files matched your search

@@ -1,42 +0,0 @@
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 ctx(id: string) {
return { params: Promise.resolve({ id }) };
}
function req(body: unknown) {
return new Request("http://localhost/api/users/9/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/users/[id]/change-password", () => {
it("requires a password", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
const res = await POST(req({}), ctx("9"));
expect(res.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards to POST /api/admin/users/{id}/changePassword", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { updated: 1 } });
await POST(req({ password: "N3wPassw0rd!" }), ctx("9"));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/users/9/changePassword", {
method: "POST",
body: { password: "N3wPassw0rd!" },
token: "jwt-abc",
});
});
});
@@ -1,23 +0,0 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized, badRequest } from "@/app/lib/server/apiRoute";
type Ctx = { params: Promise<{ id: string }> };
export async function POST(req: NextRequest, { params }: Ctx) {
const token = await getToken();
if (!token) return unauthorized();
const { id } = await params;
const body = await req.json().catch(() => ({}));
const password = (body as { password?: string }).password;
if (!password) return badRequest("password is required.");
const result = await callMobileApi<{ updated: number }>(`/api/admin/users/${encodeURIComponent(id)}/changePassword`, {
method: "POST",
body: { password },
token,
});
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
@@ -1,83 +0,0 @@
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ changeAdminUserPassword: vi.fn() }));
vi.mock("@/app/lib/services/adminUsers", () => ({ changeAdminUserPassword: mocks.changeAdminUserPassword }));
import { ChangePasswordDialog } from "./ChangePasswordDialog";
beforeEach(() => {
mocks.changeAdminUserPassword.mockReset();
});
async function fillAndSubmit(password: string, confirm: string) {
await userEvent.type(screen.getByLabelText("New password"), password);
await userEvent.type(screen.getByLabelText("Confirm password"), confirm);
await userEvent.click(screen.getByRole("button", { name: "Change password" }));
}
describe("ChangePasswordDialog", () => {
it("states the password rules", () => {
render(<ChangePasswordDialog userId={9} onClose={vi.fn()} />);
expect(screen.getByText("At least 8 characters, with at least one capital letter and one small letter.")).toBeInTheDocument();
});
it("blocks submit when the fields are empty", async () => {
render(<ChangePasswordDialog userId={9} onClose={vi.fn()} />);
await userEvent.click(screen.getByRole("button", { name: "Change password" }));
expect(await screen.findByText(/enter and confirm/i)).toBeInTheDocument();
expect(mocks.changeAdminUserPassword).not.toHaveBeenCalled();
});
it("blocks submit when the password is too short", async () => {
render(<ChangePasswordDialog userId={9} onClose={vi.fn()} />);
// 7 characters: the backend admin rule needs at least 8.
await fillAndSubmit("Abcdefg", "Abcdefg");
expect(await screen.findByText(/must be at least 8 characters/i)).toBeInTheDocument();
expect(mocks.changeAdminUserPassword).not.toHaveBeenCalled();
});
it("blocks submit when the passwords do not match", async () => {
render(<ChangePasswordDialog userId={9} onClose={vi.fn()} />);
await fillAndSubmit("Passw0rd!", "Different1!");
expect(await screen.findByText(/do not match/i)).toBeInTheDocument();
expect(mocks.changeAdminUserPassword).not.toHaveBeenCalled();
});
it("submits a matching password", async () => {
mocks.changeAdminUserPassword.mockResolvedValue({ updated: 1 });
render(<ChangePasswordDialog userId={9} onClose={vi.fn()} />);
await fillAndSubmit("Passw0rd!", "Passw0rd!");
await waitFor(() => expect(mocks.changeAdminUserPassword).toHaveBeenCalledWith(9, "Passw0rd!"));
expect(await screen.findByText(/changed successfully/i)).toBeInTheDocument();
});
it("shows an error when the request fails", async () => {
mocks.changeAdminUserPassword.mockRejectedValue(new Error("Server error"));
render(<ChangePasswordDialog userId={9} onClose={vi.fn()} />);
await fillAndSubmit("Passw0rd!", "Passw0rd!");
expect(await screen.findByText("Server error")).toBeInTheDocument();
});
it("disables submit while the request is pending", async () => {
let resolve!: (v: { updated: number }) => void;
mocks.changeAdminUserPassword.mockReturnValue(
new Promise((r) => {
resolve = r;
}),
);
render(<ChangePasswordDialog userId={9} onClose={vi.fn()} />);
await userEvent.type(screen.getByLabelText("New password"), "Passw0rd!");
await userEvent.type(screen.getByLabelText("Confirm password"), "Passw0rd!");
await userEvent.click(screen.getByRole("button", { name: "Change password" }));
await waitFor(() => expect(screen.getByRole("button", { name: "Change password" })).toBeDisabled());
resolve({ updated: 1 });
});
});
@@ -1,121 +0,0 @@
"use client";
import { useState, type FormEvent } from "react";
import { Alert, AlertDescription } from "@/app/components/ui/alert";
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 { ErrorState } from "@/app/components/ui/states";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { changeAdminUserPassword } from "@/app/lib/services/adminUsers";
const MIN_LENGTH = 8; // services-system ADMIN_PWD_FORMAT minimum
export function ChangePasswordDialog({
userId,
onClose,
}: {
userId: number;
onClose: () => void;
}) {
const t = useT();
const [password, setPassword] = useState("");
const [confirm, setConfirm] = useState("");
const [fieldError, setFieldError] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
const [saving, setSaving] = useState(false);
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setError(null);
if (!password || !confirm) {
setFieldError(t("UsrPwEnterBoth"));
return;
}
if (password.length < MIN_LENGTH) {
setFieldError(t("UsrPwTooShort", { min: MIN_LENGTH }));
return;
}
if (password !== confirm) {
setFieldError(t("UsrPwMismatch"));
return;
}
setFieldError(null);
setSaving(true);
try {
await changeAdminUserPassword(userId, password);
setSuccess(true);
} catch (err) {
setError(err instanceof Error ? err.message : "UsrPwChangeFailed");
} finally {
setSaving(false);
}
}
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("UsrChangePassword")}</DialogTitle>
</DialogHeader>
{success ? (
<>
<Alert>
<AlertDescription>{t("UsrPwChanged")}</AlertDescription>
</Alert>
<DialogFooter>
<Button onClick={onClose}>{t("Close")}</Button>
</DialogFooter>
</>
) : (
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
{error && <ErrorState message={t(error)} />}
{fieldError && (
<p role="alert" className="text-sm text-destructive">
{fieldError}
</p>
)}
<div className="space-y-1.5">
<Label htmlFor="new-password">{t("ResetNewPassword")}</Label>
<Input
id="new-password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
disabled={saving}
aria-describedby="new-password-rules"
/>
<p id="new-password-rules" className="text-sm text-muted-foreground">{t("AdminPasswordHint")}</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="confirm-password">{t("UsrConfirmPassword")}</Label>
<Input
id="confirm-password"
type="password"
value={confirm}
onChange={(e) => setConfirm(e.target.value)}
disabled={saving}
/>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={onClose} disabled={saving}>
{t("Cancel")}
</Button>
<Button type="submit" disabled={saving}>
{t("UsrChangePassword")}
</Button>
</DialogFooter>
</form>
)}
</DialogContent>
</Dialog>
);
}
@@ -115,13 +115,6 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
Edit: "Edit",
Export: "Export",
UiMoreActionsFor: "More actions for {label}",
UsrPwEnterBoth: "Enter and confirm the new password.",
UsrPwTooShort: "Password must be at least {min} characters.",
UsrPwMismatch: "Passwords do not match.",
UsrPwChangeFailed: "Failed to change password.",
UsrChangePassword: "Change password",
UsrPwChanged: "Password changed successfully.",
UsrConfirmPassword: "Confirm password",
UsrUsernameRequired: "Username is required.",
UsrEmailRequired: "Email is required.",
UsrEmailInvalid: "Enter a valid email address.",
@@ -7,7 +7,6 @@ import {
listAdminUsers,
getAdminUser,
saveAdminUser,
changeAdminUserPassword,
sendAdminUserPasswordReset,
USER_STATUS_FILTER_OPTIONS,
} from "./adminUsers";
@@ -48,15 +47,6 @@ describe("saveAdminUser", () => {
});
});
describe("changeAdminUserPassword", () => {
it("POSTs the password to /api/users/{id}/change-password", async () => {
mocks.apiPost.mockResolvedValue({ updated: 1 });
const result = await changeAdminUserPassword(9, "N3wPassw0rd!");
expect(mocks.apiPost).toHaveBeenCalledWith("/api/users/9/change-password", { password: "N3wPassw0rd!" });
expect(result).toEqual({ updated: 1 });
});
});
describe("sendAdminUserPasswordReset", () => {
it("POSTs to /api/users/{id}/reset-password", async () => {
mocks.apiPost.mockResolvedValue({ updated: 1 });
@@ -63,10 +63,6 @@ export async function saveAdminUser(payload: AdminUser): Promise<AdminUser> {
: apiPost<AdminUser>("/api/users", payload);
}
export async function changeAdminUserPassword(id: number, password: string): Promise<{ updated: number }> {
return apiPost<{ updated: number }>(`/api/users/${id}/change-password`, { password });
}
export async function sendAdminUserPasswordReset(id: number): Promise<{ updated: number }> {
return apiPost<{ updated: number }>(`/api/users/${id}/reset-password`, undefined);
}
@@ -6,7 +6,6 @@ import { ApiError } from "@/app/lib/clientApi";
const mocks = vi.hoisted(() => ({
getAdminUser: vi.fn(),
saveAdminUser: vi.fn(),
changeAdminUserPassword: vi.fn(),
sendAdminUserPasswordReset: vi.fn(),
useAdminAuth: vi.fn(),
listAdminRoles: vi.fn(),
@@ -15,7 +14,6 @@ const mocks = vi.hoisted(() => ({
vi.mock("@/app/lib/services/adminUsers", () => ({
getAdminUser: mocks.getAdminUser,
saveAdminUser: mocks.saveAdminUser,
changeAdminUserPassword: mocks.changeAdminUserPassword,
sendAdminUserPasswordReset: mocks.sendAdminUserPasswordReset,
}));
vi.mock("@/app/lib/services/adminRoles", () => ({ listAdminRoles: mocks.listAdminRoles }));
@@ -41,7 +39,6 @@ const USER = {
beforeEach(() => {
mocks.getAdminUser.mockReset();
mocks.saveAdminUser.mockReset();
mocks.changeAdminUserPassword.mockReset();
mocks.sendAdminUserPasswordReset.mockReset();
mocks.listAdminRoles.mockReset().mockResolvedValue([{ id: 1, name: "ROLE_IT" }]);
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
@@ -134,18 +131,13 @@ describe("EditUserPage", () => {
).toBeInTheDocument();
});
it("opens the change password dialog and calls changeAdminUserPassword", async () => {
it("offers no direct password change, only the emailed reset", async () => {
mocks.getAdminUser.mockResolvedValue(USER);
mocks.changeAdminUserPassword.mockResolvedValue({ updated: 1 });
render(<EditUserPage />);
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
await userEvent.click(screen.getByRole("button", { name: /change password/i }));
await userEvent.type(screen.getByLabelText("New password"), "Passw0rd!");
await userEvent.type(screen.getByLabelText("Confirm password"), "Passw0rd!");
await userEvent.click(screen.getByRole("button", { name: "Change password" }));
await waitFor(() => expect(mocks.changeAdminUserPassword).toHaveBeenCalledWith(9, "Passw0rd!"));
expect(screen.queryByRole("button", { name: /change password/i })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: /send password reset/i })).toBeInTheDocument();
});
it("sends a password reset after confirming", async () => {
@@ -9,7 +9,6 @@ import { PageHeader } from "@/app/components/ui/page-header";
import { Skeleton } from "@/app/components/ui/skeleton";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { RequireModule } from "@/app/lib/RequireModule";
import { ChangePasswordDialog } from "@/app/components/users/ChangePasswordDialog";
import { UserForm } from "@/app/components/users/UserForm";
import { ApiError } from "@/app/lib/clientApi";
import { getAdminUser, saveAdminUser, sendAdminUserPasswordReset } from "@/app/lib/services/adminUsers";
@@ -33,7 +32,6 @@ function EditUserPageContent() {
? { code: "UsrCreatedBanner" }
: null,
);
const [changePasswordOpen, setChangePasswordOpen] = useState(false);
const [confirmingReset, setConfirmingReset] = useState(false);
const [resetError, setResetError] = useState<string | null>(null);
const [resetSending, setResetSending] = useState(false);
@@ -127,9 +125,6 @@ function EditUserPageContent() {
title={t("UsrEditNamed", { username: user.username })}
actions={
<>
<Button type="button" variant="outline" onClick={() => setChangePasswordOpen(true)}>
{t("UsrChangePassword")}
</Button>
<Button
type="button"
variant="outline"
@@ -152,10 +147,6 @@ function EditUserPageContent() {
<UserForm initial={user} onSubmit={handleSubmit} submitLabel={t("Save")} />
{changePasswordOpen && (
<ChangePasswordDialog userId={userId} onClose={() => setChangePasswordOpen(false)} />
)}
{confirmingReset && (
<Dialog open onOpenChange={(open) => !open && setConfirmingReset(false)}>
<DialogContent>
@@ -11,7 +11,6 @@ const mocks = vi.hoisted(() => ({
vi.mock("@/app/lib/services/adminUsers", () => ({
saveAdminUser: mocks.saveAdminUser,
getAdminUser: vi.fn(),
changeAdminUserPassword: vi.fn(),
sendAdminUserPasswordReset: vi.fn(),
}));
vi.mock("@/app/lib/services/adminRoles", () => ({ listAdminRoles: mocks.listAdminRoles }));
@@ -5,7 +5,6 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({
listAdminUsers: vi.fn(),
sendAdminUserPasswordReset: vi.fn(),
changeAdminUserPassword: vi.fn(),
useAdminAuth: vi.fn(),
}));
vi.mock("@/app/lib/services/adminUsers", async (importActual) => ({
@@ -14,7 +13,6 @@ vi.mock("@/app/lib/services/adminUsers", async (importActual) => ({
getAdminUser: vi.fn(),
saveAdminUser: vi.fn(),
sendAdminUserPasswordReset: mocks.sendAdminUserPasswordReset,
changeAdminUserPassword: mocks.changeAdminUserPassword,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
@@ -27,7 +25,6 @@ beforeEach(() => {
memoryRouter.reset("/users");
mocks.listAdminUsers.mockReset();
mocks.sendAdminUserPasswordReset.mockReset();
mocks.changeAdminUserPassword.mockReset();
mocks.useAdminAuth.mockReset();
mocks.useAdminAuth.mockReturnValue({
loading: false,