feat(portal): password fields on create user and a set-temporary-password dialog

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 11:19:10 +08:00
1 parent 2c0a847b68
commit c7a51b4074
13 files changed
+424 -59

No files matched your search

@@ -0,0 +1,51 @@
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/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]/password", () => {
it("returns 401 when there is no session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await POST(req({}), ctx("9"));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards only the password pair and answers 204", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: null });
const res = await POST(req({ password: "Good#Pass1", confirmPassword: "Good#Pass1", extra: 1 }), ctx("9"));
expect(res.status).toBe(204);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/users/9/password", {
method: "POST",
body: { password: "Good#Pass1", confirmPassword: "Good#Pass1" },
token: "jwt-abc",
});
});
it("passes a refusal through with its code", async () => {
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: false, status: 409, error: "The user is deactivated", code: "USER_DISABLED" });
const res = await POST(req({ password: "a", confirmPassword: "a" }), ctx("9"));
expect(res.status).toBe(409);
expect(await res.json()).toMatchObject({ error: "The user is deactivated", code: "USER_DISABLED" });
});
});
@@ -0,0 +1,24 @@
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";
type Ctx = { params: Promise<{ id: string }> };
/** Admin-typed temporary password; only the password pair is forwarded, and nothing is logged. */
export async function POST(req: NextRequest, { params }: Ctx) {
const token = await getToken();
if (!token) return unauthorized();
const { id } = await params;
const { password, confirmPassword } = (await req.json().catch(() => ({}))) as {
password?: string;
confirmPassword?: string;
};
const result = await callMobileApi<null>(`/api/admin/users/${encodeURIComponent(id)}/password`, {
method: "POST",
body: { password, confirmPassword },
token,
});
if (!result.ok) return errorResponse(result);
return new NextResponse(null, { status: 204 });
}
@@ -0,0 +1,50 @@
"use client";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { useT } from "@/app/lib/i18n/MessagesProvider";
/** Password + confirmation inputs shared by the create form and "Set temporary password". */
export function PasswordFields(props: {
password: string;
confirmPassword: string;
onPassword: (v: string) => void;
onConfirmPassword: (v: string) => void;
disabled?: boolean;
passwordError?: string;
confirmError?: string;
}) {
const t = useT();
return (
<>
<div className="space-y-1.5">
<Label htmlFor="user-password">{t("Password")}</Label>
<Input
id="user-password"
type="password"
autoComplete="new-password"
value={props.password}
onChange={(e) => props.onPassword(e.target.value)}
disabled={props.disabled}
aria-invalid={!!props.passwordError}
aria-describedby="user-password-hint"
/>
<p id="user-password-hint" className="text-sm text-muted-foreground">{t("AdminPasswordHint")}</p>
{props.passwordError && <p role="alert" className="text-sm text-destructive">{props.passwordError}</p>}
</div>
<div className="space-y-1.5">
<Label htmlFor="user-confirm-password">{t("UsrConfirmPassword")}</Label>
<Input
id="user-confirm-password"
type="password"
autoComplete="new-password"
value={props.confirmPassword}
onChange={(e) => props.onConfirmPassword(e.target.value)}
disabled={props.disabled}
aria-invalid={!!props.confirmError}
/>
{props.confirmError && <p role="alert" className="text-sm text-destructive">{props.confirmError}</p>}
</div>
</>
);
}
@@ -0,0 +1,74 @@
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";
const mocks = vi.hoisted(() => ({ setAdminUserPassword: vi.fn() }));
vi.mock("@/app/lib/services/adminUsers", () => ({ setAdminUserPassword: mocks.setAdminUserPassword }));
import { SetPasswordButton } from "./SetPasswordButton";
beforeEach(() => {
mocks.setAdminUserPassword.mockReset();
});
async function open() {
await userEvent.click(screen.getByRole("button", { name: "Set temporary password" }));
}
describe("SetPasswordButton", () => {
it("sends both fields, closes, and reports success", async () => {
mocks.setAdminUserPassword.mockResolvedValue(undefined);
const onDone = vi.fn();
render(<SetPasswordButton userId={9} onDone={onDone} />);
await open();
await userEvent.type(screen.getByLabelText("Password"), "Good#Pass1");
await userEvent.type(screen.getByLabelText("Confirm password"), "Good#Pass1");
await userEvent.click(screen.getByRole("button", { name: "Set password" }));
await waitFor(() => expect(onDone).toHaveBeenCalledTimes(1));
expect(mocks.setAdminUserPassword).toHaveBeenCalledWith(9, "Good#Pass1", "Good#Pass1");
expect(screen.queryByLabelText("Password")).not.toBeInTheDocument();
});
it("opens with empty fields again after a success", async () => {
mocks.setAdminUserPassword.mockResolvedValue(undefined);
render(<SetPasswordButton userId={9} onDone={vi.fn()} />);
await open();
await userEvent.type(screen.getByLabelText("Password"), "Good#Pass1");
await userEvent.type(screen.getByLabelText("Confirm password"), "Good#Pass1");
await userEvent.click(screen.getByRole("button", { name: "Set password" }));
await waitFor(() => expect(screen.queryByLabelText("Password")).not.toBeInTheDocument());
await open();
expect(screen.getByLabelText("Password")).toHaveValue("");
expect(screen.getByLabelText("Confirm password")).toHaveValue("");
});
it("catches a mismatch before calling the server", async () => {
render(<SetPasswordButton userId={9} onDone={vi.fn()} />);
await open();
await userEvent.type(screen.getByLabelText("Password"), "Good#Pass1");
await userEvent.type(screen.getByLabelText("Confirm password"), "Other#Pass1");
await userEvent.click(screen.getByRole("button", { name: "Set password" }));
expect(await screen.findByText("The passwords do not match.")).toBeInTheDocument();
expect(mocks.setAdminUserPassword).not.toHaveBeenCalled();
});
it.each([
["USER_DISABLED", "The user is deactivated"],
["PASSWORD_POLICY", "Password does not meet the password policy"],
["SUPER_ADMIN_REQUIRED", "Only a super admin can manage a super admin"],
])("shows the %s refusal and keeps the dialog open", async (code, message) => {
mocks.setAdminUserPassword.mockImplementation(async () => {
throw new ApiError(message, 400, { code });
});
const onDone = vi.fn();
render(<SetPasswordButton userId={9} onDone={onDone} />);
await open();
await userEvent.type(screen.getByLabelText("Password"), "Good#Pass1");
await userEvent.type(screen.getByLabelText("Confirm password"), "Good#Pass1");
await userEvent.click(screen.getByRole("button", { name: "Set password" }));
expect(await screen.findByText(message)).toBeInTheDocument();
expect(onDone).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,83 @@
"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 { setAdminUserPassword } from "@/app/lib/services/adminUsers";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { PasswordFields } from "./PasswordFields";
/** "Set temporary password" on the user edit page: the admin types it; the user must change it at next sign-in. */
export function SetPasswordButton({ userId, onDone }: { userId: number; onDone: () => void }) {
const t = useT();
const [open, setOpen] = useState(false);
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
function close() {
// The password lives only in this state; clear it whenever the dialog closes.
setOpen(false);
setPassword("");
setConfirmPassword("");
setError(null);
}
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!password) return setError("UsrPasswordRequired");
if (password !== confirmPassword) return setError("UsrPasswordMismatch");
setSaving(true);
setError(null);
try {
await setAdminUserPassword(userId, password, confirmPassword);
close();
onDone();
} catch (err) {
setError(err instanceof Error ? err.message : "UsrSetPasswordFailed");
} finally {
setSaving(false);
}
}
return (
<>
<Button type="button" variant="outline" onClick={() => setOpen(true)}>
{t("UsrSetTempPassword")}
</Button>
{open && (
<Dialog open onOpenChange={(o) => !o && close()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("UsrSetTempPassword")}</DialogTitle>
</DialogHeader>
<form onSubmit={submit} className="space-y-4" noValidate>
<p className="text-sm text-muted-foreground">{t("UsrSetTempPasswordBody")}</p>
<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={close}>
{t("Cancel")}
</Button>
<Button type="submit" disabled={saving}>
{t("UsrSetPasswordSubmit")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)}
</>
);
}
@@ -15,6 +15,7 @@ import { listAdminRoles } from "@/app/lib/services/adminRoles";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import type { AdminUser } from "@/app/lib/types";
import { PasswordFields } from "./PasswordFields";
// Shared create/edit form for /users/new and /users/[id] (plan: "Build the admin
// add/edit-user form"). The Roles picker is populated from the admin roles list
@@ -29,13 +30,18 @@ interface RoleOption {
name: string;
}
/** On create the payload also carries the admin-typed first password and its confirmation. */
export type UserFormPayload = AdminUser & { password?: string; confirmPassword?: string };
export interface UserFormProps {
initial?: AdminUser;
onSubmit: (payload: AdminUser) => Promise<void>;
onSubmit: (payload: UserFormPayload) => Promise<void>;
submitLabel?: string;
/** Create only: ask for the first password (the user must change it at first sign-in). */
withPassword?: boolean;
}
export function UserForm({ initial, onSubmit, submitLabel }: UserFormProps) {
export function UserForm({ initial, onSubmit, submitLabel, withPassword }: UserFormProps) {
const t = useT();
const { id: myId } = useAdminAuth();
// The server refuses SELF_DEACTIVATION; this keeps the switch from offering it.
@@ -45,6 +51,8 @@ export function UserForm({ initial, onSubmit, submitLabel }: UserFormProps) {
const [username, setUsername] = useState(initial?.username ?? "");
const [email, setEmail] = useState(initial?.email ?? "");
const [enabled, setEnabled] = useState(initial?.enabled ?? true);
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [selectedRoleIds, setSelectedRoleIds] = useState<Set<number>>(
() => new Set((initial?.roles ?? []).map((r) => r.id).filter((id): id is number => id != null)),
);
@@ -106,6 +114,8 @@ export function UserForm({ initial, onSubmit, submitLabel }: UserFormProps) {
if (!username.trim()) errors.username = t("UsrUsernameRequired");
if (!email.trim()) errors.email = t("UsrEmailRequired");
else if (!EMAIL_RE.test(email.trim())) errors.email = t("UsrEmailInvalid");
if (withPassword && !password) errors.password = t("UsrPasswordRequired");
else if (withPassword && password !== confirmPassword) errors.confirmPassword = t("UsrPasswordMismatch");
setFieldErrors(errors);
if (Object.keys(errors).length > 0) return;
@@ -122,6 +132,7 @@ export function UserForm({ initial, onSubmit, submitLabel }: UserFormProps) {
// Only `enabled` gates admin sign-in; status is derived to stay consistent.
status: enabled ? "Y" : "N",
roles: selectedRoles.map((r) => ({ id: r.id, name: r.name })),
...(withPassword ? { password, confirmPassword } : {}),
});
} catch (err) {
setFormError(err instanceof Error ? err.message : "UsrSaveFailed");
@@ -198,6 +209,18 @@ export function UserForm({ initial, onSubmit, submitLabel }: UserFormProps) {
)}
</div>
{withPassword && (
<PasswordFields
password={password}
confirmPassword={confirmPassword}
onPassword={setPassword}
onConfirmPassword={setConfirmPassword}
disabled={saving}
passwordError={fieldErrors.password}
confirmError={fieldErrors.confirmPassword}
/>
)}
<fieldset className="space-y-1.5">
<legend className="text-sm font-medium">{t("BO_ROLES")}</legend>
{selectedRoles.length > 0 && (
@@ -125,9 +125,15 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
UsrDisabledHint: "Disabled users cannot sign in.",
UsrOwnAccountHint: "You can't deactivate your own account",
UsrNameRequired: "Name is required.",
UsrCreatedBanner: "User created. A temporary password has been emailed to them; they will be asked to set their own at first sign-in.",
UsrCreatedNoEmail: "User created, but the temporary password email could not be sent. Open the user from the users list and use Send password reset to try again.",
UsrBackToUsers: "Back to users",
UsrCreatedBanner: "User created. Give them the password you set; they will be asked to choose their own at first sign-in.",
UsrConfirmPassword: "Confirm password",
UsrPasswordRequired: "Password is required.",
UsrPasswordMismatch: "The passwords do not match.",
UsrSetTempPassword: "Set temporary password",
UsrSetTempPasswordBody: "Type a temporary password and give it to the user. Their old password stops working, and they must choose a new one at next sign-in.",
UsrSetPasswordSubmit: "Set password",
UsrSetPasswordFailed: "Failed to set the password.",
UsrTempPasswordSet: "Temporary password set. The user must change it at next sign-in.",
AdminPasswordHint: "At least 8 characters, with at least one capital letter and one small letter.",
UiDatePlaceholder: "DD/MM/YYYY",
UiOpenCalendarFor: "Open calendar for {label}",
@@ -8,6 +8,7 @@ import {
getAdminUser,
saveAdminUser,
sendAdminUserPasswordReset,
setAdminUserPassword,
USER_STATUS_FILTER_OPTIONS,
} from "./adminUsers";
import { DEFAULT_MESSAGES } from "@/app/lib/i18n/defaultMessages";
@@ -56,6 +57,14 @@ describe("sendAdminUserPasswordReset", () => {
});
});
describe("setAdminUserPassword", () => {
it("POSTs the password pair to /api/users/{id}/password", async () => {
mocks.apiPost.mockResolvedValue(undefined);
await setAdminUserPassword(9, "Good#Pass1", "Good#Pass1");
expect(mocks.apiPost).toHaveBeenCalledWith("/api/users/9/password", { password: "Good#Pass1", confirmPassword: "Good#Pass1" });
});
});
describe("normalizeAdminUserPage identity refs", () => {
it("resolves bare role ids to the first full role object in the response and drops unresolvable ones", async () => {
const { normalizeAdminUserPage } = await import("./adminUsers");
@@ -63,6 +63,11 @@ export async function saveAdminUser(payload: AdminUser): Promise<AdminUser> {
: apiPost<AdminUser>("/api/users", payload);
}
/** 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 });
}
export async function sendAdminUserPasswordReset(id: number): Promise<{ updated: number }> {
return apiPost<{ updated: number }>(`/api/users/${id}/reset-password`, undefined);
}
@@ -7,6 +7,7 @@ const mocks = vi.hoisted(() => ({
getAdminUser: vi.fn(),
saveAdminUser: vi.fn(),
sendAdminUserPasswordReset: vi.fn(),
setAdminUserPassword: vi.fn(),
useAdminAuth: vi.fn(),
listAdminRoles: vi.fn(),
searchParamsGet: vi.fn(),
@@ -15,6 +16,7 @@ vi.mock("@/app/lib/services/adminUsers", () => ({
getAdminUser: mocks.getAdminUser,
saveAdminUser: mocks.saveAdminUser,
sendAdminUserPasswordReset: mocks.sendAdminUserPasswordReset,
setAdminUserPassword: mocks.setAdminUserPassword,
}));
vi.mock("@/app/lib/services/adminRoles", () => ({ listAdminRoles: mocks.listAdminRoles }));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
@@ -126,7 +128,7 @@ describe("EditUserPage", () => {
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
expect(
screen.getByText(
"User created. A temporary password has been emailed to them; they will be asked to set their own at first sign-in.",
"User created. Give them the password you set; they will be asked to choose their own at first sign-in.",
),
).toBeInTheDocument();
});
@@ -158,4 +160,39 @@ describe("EditUserPage", () => {
render(<EditUserPage />);
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
});
describe("set temporary password", () => {
it("is offered on another user's page and shows the banner once set", async () => {
mocks.useAdminAuth.mockReturnValue({ id: 1, loading: false, hasModule: () => true });
mocks.getAdminUser.mockResolvedValue(USER);
mocks.setAdminUserPassword.mockResolvedValue(undefined);
render(<EditUserPage />);
await userEvent.click(await screen.findByRole("button", { name: "Set temporary password" }));
await userEvent.type(screen.getByLabelText("Password"), "Good#Pass1");
await userEvent.type(screen.getByLabelText("Confirm password"), "Good#Pass1");
await userEvent.click(screen.getByRole("button", { name: "Set password" }));
expect(await screen.findByText("Temporary password set. The user must change it at next sign-in.")).toBeInTheDocument();
expect(mocks.setAdminUserPassword).toHaveBeenCalledWith(9, "Good#Pass1", "Good#Pass1");
});
it("is not offered on the admin's own account", async () => {
mocks.useAdminAuth.mockReturnValue({ id: 9, loading: false, hasModule: () => true });
mocks.getAdminUser.mockResolvedValue(USER);
render(<EditUserPage />);
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
expect(screen.queryByRole("button", { name: "Set temporary password" })).not.toBeInTheDocument();
});
it("is not offered while the signed-in admin is still unknown", async () => {
mocks.useAdminAuth.mockReturnValue({ id: null, loading: false, hasModule: () => true });
mocks.getAdminUser.mockResolvedValue(USER);
render(<EditUserPage />);
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("Jane"));
expect(screen.queryByRole("button", { name: "Set temporary password" })).not.toBeInTheDocument();
});
});
});
@@ -10,6 +10,8 @@ import { Skeleton } from "@/app/components/ui/skeleton";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { RequireModule } from "@/app/lib/RequireModule";
import { UserForm } from "@/app/components/users/UserForm";
import { SetPasswordButton } from "@/app/components/users/SetPasswordButton";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { ApiError } from "@/app/lib/clientApi";
import { getAdminUser, saveAdminUser, sendAdminUserPasswordReset } from "@/app/lib/services/adminUsers";
import type { AdminUser } from "@/app/lib/types";
@@ -21,6 +23,7 @@ function EditUserPageContent() {
const { id } = useParams<{ id: string }>();
const searchParams = useSearchParams();
const userId = Number(id);
const { id: myId } = useAdminAuth();
const [user, setUser] = useState<AdminUser | null>(null);
const [loading, setLoading] = useState(true);
@@ -125,6 +128,10 @@ function EditUserPageContent() {
title={t("UsrEditNamed", { username: user.username })}
actions={
<>
{/* Own account: the server refuses SELF_NOT_ALLOWED; also hidden until the signed-in admin is known. */}
{myId != null && user.id !== myId && (
<SetPasswordButton userId={userId} onDone={() => setSuccessMessage({ code: "UsrTempPasswordSet" })} />
)}
<Button
type="button"
variant="outline"
@@ -38,7 +38,8 @@ describe("NewUserPage", () => {
await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue(""));
expect(screen.getByLabelText("Username")).toHaveValue("");
expect(screen.getByLabelText("Email")).toHaveValue("");
expect(screen.queryByLabelText(/password/i)).not.toBeInTheDocument();
expect(screen.getByLabelText("Password")).toHaveValue("");
expect(screen.getByLabelText("Confirm password")).toHaveValue("");
});
it("calls saveAdminUser without an id and redirects to the returned user's id", async () => {
@@ -49,22 +50,34 @@ describe("NewUserPage", () => {
await userEvent.type(screen.getByLabelText("Name"), "Jane");
await userEvent.type(screen.getByLabelText("Username"), "jane.doe");
await userEvent.type(screen.getByLabelText("Email"), "jane@example.com");
await userEvent.type(screen.getByLabelText("Password"), "Good#Pass1");
await userEvent.type(screen.getByLabelText("Confirm password"), "Good#Pass1");
await userEvent.click(screen.getByRole("button", { name: /create user/i }));
await waitFor(() => expect(mocks.saveAdminUser).toHaveBeenCalledTimes(1));
const payload = mocks.saveAdminUser.mock.calls[0][0];
expect(payload.id).toBeUndefined();
expect(payload.username).toBe("jane.doe");
expect(payload.password).toBe("Good#Pass1");
expect(payload.confirmPassword).toBe("Good#Pass1");
await waitFor(() => expect(mocks.push).toHaveBeenCalledWith("/users/42?created=1"));
});
it("when the temp-password email fails, says so with a link to the users list instead of redirecting", async () => {
const { ApiError } = await vi.importActual<typeof import("@/app/lib/clientApi")>("@/app/lib/clientApi");
mocks.saveAdminUser.mockRejectedValue(
new ApiError("User created but the temporary password email was not sent; retry the password reset", 400, {
code: "TEMP_PASSWORD_NOT_SENT",
}),
);
it("catches a mismatched confirmation before submitting", async () => {
render(<NewUserPage />);
await waitFor(() => expect(screen.getByLabelText("Name")).toBeInTheDocument());
await userEvent.type(screen.getByLabelText("Name"), "Jane");
await userEvent.type(screen.getByLabelText("Username"), "jane.doe");
await userEvent.type(screen.getByLabelText("Email"), "jane@example.com");
await userEvent.type(screen.getByLabelText("Password"), "Good#Pass1");
await userEvent.type(screen.getByLabelText("Confirm password"), "Other#Pass1");
await userEvent.click(screen.getByRole("button", { name: /create user/i }));
expect(await screen.findByText("The passwords do not match.")).toBeInTheDocument();
expect(mocks.saveAdminUser).not.toHaveBeenCalled();
});
it("requires a password", async () => {
render(<NewUserPage />);
await waitFor(() => expect(screen.getByLabelText("Name")).toBeInTheDocument());
await userEvent.type(screen.getByLabelText("Name"), "Jane");
@@ -72,14 +85,26 @@ describe("NewUserPage", () => {
await userEvent.type(screen.getByLabelText("Email"), "jane@example.com");
await userEvent.click(screen.getByRole("button", { name: /create user/i }));
expect(
await screen.findByText(
"User created, but the temporary password email could not be sent. Open the user from the users list and use Send password reset to try again.",
),
).toBeInTheDocument();
expect(screen.getByRole("link", { name: "Back to users" })).toHaveAttribute("href", "/users");
expect(await screen.findByText("Password is required.")).toBeInTheDocument();
expect(mocks.saveAdminUser).not.toHaveBeenCalled();
});
it("shows the server's policy message and stays on the form", async () => {
const { ApiError } = await vi.importActual<typeof import("@/app/lib/clientApi")>("@/app/lib/clientApi");
mocks.saveAdminUser.mockRejectedValue(
new ApiError("Password does not meet the password policy", 400, { code: "PASSWORD_POLICY" }),
);
render(<NewUserPage />);
await waitFor(() => expect(screen.getByLabelText("Name")).toBeInTheDocument());
await userEvent.type(screen.getByLabelText("Name"), "Jane");
await userEvent.type(screen.getByLabelText("Username"), "jane.doe");
await userEvent.type(screen.getByLabelText("Email"), "jane@example.com");
await userEvent.type(screen.getByLabelText("Password"), "weak");
await userEvent.type(screen.getByLabelText("Confirm password"), "weak");
await userEvent.click(screen.getByRole("button", { name: /create user/i }));
expect(await screen.findByText("Password does not meet the password policy")).toBeInTheDocument();
expect(mocks.push).not.toHaveBeenCalled();
expect(screen.queryByRole("button", { name: /create user/i })).not.toBeInTheDocument();
});
it("renders NotAuthorized when the Users module is absent from aclMenu", () => {
+9 -38
View File
@@ -1,60 +1,31 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { ApiError } from "@/app/lib/clientApi";
import { ErrorState } from "@/app/components/ui/states";
import { RequireModule } from "@/app/lib/RequireModule";
import { PageHeader } from "@/app/components/ui/page-header";
import { UserForm } from "@/app/components/users/UserForm";
import { UserForm, type UserFormPayload } from "@/app/components/users/UserForm";
import { saveAdminUser } from "@/app/lib/services/adminUsers";
import type { AdminUser } from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
// Passwordless create (plan "Build the admin add/edit-user form", Task 3):
// AdminUserService.create never accepts a client-supplied password (see
// AdminUser.java's Javadoc), so this form has no password field. Once the
// mobile-api returns the created user's id, we redirect to its edit page,
// which surfaces a banner (via the `created=1` query param). The backend emails a temporary password
// on create; if that email fails the user exists but the error body carries no id, so we stay here.
// The admin types the first password (legacy backoffice flow); the user is saved with a pending
// password change and must choose their own at first sign-in. No email is sent. Once the
// mobile-api returns the created user's id, we redirect to its edit page with a `created=1` banner.
function NewUserPageContent() {
const t = useT();
const router = useRouter();
const [emailFailed, setEmailFailed] = useState(false);
async function handleSubmit(payload: AdminUser) {
try {
const created = await saveAdminUser(payload);
if (created.id != null) {
router.push(`/users/${created.id}?created=1`);
}
} catch (err) {
if (err instanceof ApiError && (err.data as { code?: string } | undefined)?.code === "TEMP_PASSWORD_NOT_SENT") {
setEmailFailed(true);
return;
}
throw err;
async function handleSubmit(payload: UserFormPayload) {
const created = await saveAdminUser(payload);
if (created.id != null) {
router.push(`/users/${created.id}?created=1`);
}
}
if (emailFailed) {
return (
<>
<PageHeader title={t("UsrNewUser")} />
<ErrorState message={t("UsrCreatedNoEmail")} className="mb-4" />
<Link href="/users" className="text-primary underline-offset-4 hover:underline">
{t("UsrBackToUsers")}
</Link>
</>
);
}
return (
<>
<PageHeader title={t("UsrNewUser")} />
<UserForm onSubmit={handleSubmit} submitLabel={t("UsrCreateUser")} />
<UserForm onSubmit={handleSubmit} submitLabel={t("UsrCreateUser")} withPassword />
</>
);
}