feat(admin-portal): forgot password page; own account cannot be deactivated
/forgot-password always shows the same message; the route never forwards upstream errors or a token. /api/admin/me now returns id and username so the user form can lock the Active switch on your own account. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
1071ddaa2a
commit
da813874ec
22 files changed
+379
-11
No files matched your search
@@ -33,7 +33,7 @@ Babyboo source: `~/Projects/babyboo` (read only). All tasks run serially; most t
|
||||
|
||||
- [x] 6.1 Cut the portal down to login, reset-password (first login), users, roles, roles access, not-authorised and the app shell: delete every other `app/` route, `app/api/` family, component folder, lib file and test, then remove `package.json` dependencies with no remaining import and their i18n keys. Cut `routeModules` and `FIXED_PROTECTED_MODULE_NAMES` to `BO_ROOT`, `BO_USERS`, `BO_ROLES`; default cookie `colite_admin`; replace babyboo branding text. Verify: in `solvway-admin-portal`, `npm ci && npm run lint && npm run build && npm test` all exit 0.
|
||||
- Scope: `solvway-admin-portal/**`
|
||||
- [ ] 6.2 Add the `/forgot-password` page (public, linked from login) and its route handler calling `/api/admin/auth/forgot-password`, showing the fixed message for any outcome; make the users form refuse self-deactivation and show duplicate-username and lock-out errors from the API. Tests first (vitest) for each portal-visible scenario in the specs. Verify: `npm run lint && npm run build && npm test` exit 0.
|
||||
- [x] 6.2 Add the `/forgot-password` page (public, linked from login) and its route handler calling `/api/admin/auth/forgot-password`, showing the fixed message for any outcome; make the users form refuse self-deactivation and show duplicate-username and lock-out errors from the API. Tests first (vitest) for each portal-visible scenario in the specs. Verify: `npm run lint && npm run build && npm test` exit 0.
|
||||
- Scope: `solvway-admin-portal/**`
|
||||
|
||||
## 7. Local stack and end-to-end check
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
|
||||
import { POST } from "./route";
|
||||
|
||||
function req(body: unknown) {
|
||||
return new Request("http://localhost/api/auth/forgot-password", {
|
||||
method: "POST",
|
||||
body: typeof body === "string" ? body : JSON.stringify(body),
|
||||
}) as unknown as Parameters<typeof POST>[0];
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
});
|
||||
|
||||
describe("POST /api/auth/forgot-password", () => {
|
||||
it("forwards trimmed username and email with no token and answers ok", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { result: "true" } });
|
||||
const res = await POST(req({ username: " jane ", email: " jane@example.com ", extra: "x" }));
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ ok: true });
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/auth/forgot-password", {
|
||||
method: "POST",
|
||||
body: { username: "jane", email: "jane@example.com" },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["404", { ok: false, error: "nope", status: 404 }],
|
||||
["500", { ok: false, error: "boom", status: 500 }],
|
||||
["network failure", { ok: false, error: "Unable to reach the server." }],
|
||||
])("answers 200 ok whatever upstream returns (%s)", async (_n, upstream) => {
|
||||
mocks.callMobileApi.mockResolvedValue(upstream);
|
||||
const res = await POST(req({ username: "jane", email: "jane@example.com" }));
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
it("drops non-string values and does not call upstream for missing ones", async () => {
|
||||
const res = await POST(req({ username: { a: 1 }, email: 5 }));
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ ok: true });
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("answers 200 ok on an unparseable body", async () => {
|
||||
const res = await POST(req("not json"));
|
||||
expect(res.status).toBe(200);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
|
||||
// POST → /api/admin/auth/forgot-password (public, no token). The browser always gets 200 {ok:true}:
|
||||
// the answer must not reveal whether the account exists, so upstream errors are never forwarded.
|
||||
// Same-origin and body-size checks are enforced for every /api write by middleware.
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = (await req.json().catch(() => ({}))) as { username?: unknown; email?: unknown };
|
||||
const username = typeof body.username === "string" ? body.username.trim() : "";
|
||||
const email = typeof body.email === "string" ? body.email.trim() : "";
|
||||
if (username && email) {
|
||||
await callMobileApi("/api/admin/auth/forgot-password", { method: "POST", body: { username, email } });
|
||||
}
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -109,4 +109,15 @@ describe("GET /api/auth/session", () => {
|
||||
const res = await GET(req());
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("passes id and username through from the upstream AdminMeResponse", async () => {
|
||||
mocks.getToken.mockResolvedValue("jwt-abc");
|
||||
mocks.callMobileApi.mockResolvedValue({
|
||||
ok: true,
|
||||
data: { id: 9, username: "jane", name: "Jane", roles: [], aclMenu: { name: "root", type: "R" } },
|
||||
});
|
||||
const json = await (await GET(req())).json();
|
||||
expect(json.id).toBe(9);
|
||||
expect(json.username).toBe("jane");
|
||||
});
|
||||
});
|
||||
@@ -25,6 +25,6 @@ export async function GET(req: NextRequest) {
|
||||
const result = await callMobileApi<AdminMeResponse>("/api/admin/me", { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
|
||||
const { name, roles, aclMenu, branch } = result.data;
|
||||
return NextResponse.json({ name, roles, aclMenu, branch: branch ?? null });
|
||||
const { id, username, name, roles, aclMenu, branch } = result.data;
|
||||
return NextResponse.json({ id, username, name, roles, aclMenu, branch: branch ?? null });
|
||||
}
|
||||
@@ -4,8 +4,10 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listAdminRoles: vi.fn(),
|
||||
useAdminAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminRoles", () => ({ listAdminRoles: mocks.listAdminRoles }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
|
||||
import { UserForm } from "./UserForm";
|
||||
|
||||
@@ -16,6 +18,7 @@ const ROLES = [
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.listAdminRoles.mockReset().mockResolvedValue(ROLES);
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ id: null });
|
||||
});
|
||||
|
||||
async function waitForPickers() {
|
||||
@@ -195,4 +198,51 @@ describe("UserForm", () => {
|
||||
expect(await screen.findByText(/username already taken/i)).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /save/i })).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["USERNAME_TAKEN", "Username is already taken"],
|
||||
["SELF_DEACTIVATION", "You cannot deactivate your own account"],
|
||||
["EMAIL_TAKEN", "Email is already in use"],
|
||||
])("shows the API's %s message on a failed save", async (_code, message) => {
|
||||
render(
|
||||
<UserForm
|
||||
initial={{ id: 9, name: "Jane", username: "jane", email: "jane@example.com", enabled: true, status: "Y", roles: [] }}
|
||||
onSubmit={vi.fn().mockRejectedValue(new Error(message))}
|
||||
/>,
|
||||
);
|
||||
await waitForPickers();
|
||||
await userEvent.click(screen.getByRole("button", { name: /save/i }));
|
||||
|
||||
expect(await screen.findByText(message)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe("own account", () => {
|
||||
const record = { id: 9, name: "Jane", username: "jane", email: "jane@example.com", enabled: true, status: "Y" as const, roles: [] };
|
||||
|
||||
it("disables the Active switch and shows the hint when editing the signed-in user", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ id: 9 });
|
||||
render(<UserForm initial={record} onSubmit={vi.fn()} />);
|
||||
await waitForPickers();
|
||||
|
||||
expect(screen.getByLabelText("Enabled")).toBeDisabled();
|
||||
expect(screen.getByText("You can't deactivate your own account")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps the Active switch enabled when editing another user", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ id: 1 });
|
||||
render(<UserForm initial={record} onSubmit={vi.fn()} />);
|
||||
await waitForPickers();
|
||||
|
||||
expect(screen.getByLabelText("Enabled")).not.toBeDisabled();
|
||||
expect(screen.queryByText("You can't deactivate your own account")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps the switch enabled on the create form", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ id: 9 });
|
||||
render(<UserForm onSubmit={vi.fn()} />);
|
||||
await waitForPickers();
|
||||
|
||||
expect(screen.getByLabelText("Enabled")).not.toBeDisabled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,7 @@ import { ErrorState } from "@/app/components/ui/states";
|
||||
import { roleLabel } from "@/app/lib/roleLabel";
|
||||
import { Skeleton } from "@/app/components/ui/skeleton";
|
||||
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";
|
||||
|
||||
@@ -36,6 +37,9 @@ export interface UserFormProps {
|
||||
|
||||
export function UserForm({ initial, onSubmit, submitLabel }: UserFormProps) {
|
||||
const t = useT();
|
||||
const { id: myId } = useAdminAuth();
|
||||
// The server refuses SELF_DEACTIVATION; this keeps the switch from offering it.
|
||||
const isOwnAccount = initial?.id != null && initial.id === myId;
|
||||
const [name, setName] = useState(initial?.name ?? "");
|
||||
const [surname, setSurname] = useState(initial?.surname ?? "");
|
||||
const [username, setUsername] = useState(initial?.username ?? "");
|
||||
@@ -243,10 +247,10 @@ export function UserForm({ initial, onSubmit, submitLabel }: UserFormProps) {
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch id="user-enabled" checked={enabled} onCheckedChange={setEnabled} disabled={saving} />
|
||||
<Switch id="user-enabled" checked={enabled} onCheckedChange={setEnabled} disabled={saving || isOwnAccount} />
|
||||
<Label htmlFor="user-enabled">{t("Enabled")}</Label>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">{t("UsrDisabledHint")}</p>
|
||||
<p className="text-sm text-muted-foreground">{t(isOwnAccount ? "UsrOwnAccountHint" : "UsrDisabledHint")}</p>
|
||||
</div>
|
||||
|
||||
<Button type="submit" disabled={saving}>
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { render, screen, waitFor, fireEvent } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/app/lib/clientApi", () => ({ apiPost: vi.fn() }));
|
||||
|
||||
import ForgotPasswordPage from "./page";
|
||||
import { apiPost } from "@/app/lib/clientApi";
|
||||
|
||||
const mockPost = apiPost as unknown as ReturnType<typeof vi.fn>;
|
||||
const FIXED = "If the details match an account, we have emailed a temporary password.";
|
||||
|
||||
function fill(username: string, email: string) {
|
||||
fireEvent.change(screen.getByLabelText("Username"), { target: { value: username } });
|
||||
fireEvent.change(screen.getByLabelText("Email"), { target: { value: email } });
|
||||
}
|
||||
const submit = () => fireEvent.submit(screen.getByRole("button", { name: /temporary password/i }));
|
||||
|
||||
beforeEach(() => {
|
||||
mockPost.mockReset();
|
||||
});
|
||||
|
||||
describe("ForgotPasswordPage", () => {
|
||||
it("posts username and email and shows the fixed message with a link back to login", async () => {
|
||||
mockPost.mockResolvedValue({ ok: true });
|
||||
render(<ForgotPasswordPage />);
|
||||
fill("jane", "jane@example.com");
|
||||
submit();
|
||||
|
||||
expect(await screen.findByText(FIXED)).toBeInTheDocument();
|
||||
expect(mockPost).toHaveBeenCalledWith("/api/auth/forgot-password", { username: "jane", email: "jane@example.com" });
|
||||
expect(screen.getByRole("link", { name: /back to log ?in/i })).toHaveAttribute("href", "/login");
|
||||
});
|
||||
|
||||
it("shows the same message when the request fails", async () => {
|
||||
mockPost.mockImplementation(() => Promise.reject(new Error("Network down")));
|
||||
render(<ForgotPasswordPage />);
|
||||
fill("jane", "jane@example.com");
|
||||
submit();
|
||||
|
||||
expect(await screen.findByText(FIXED)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/network down/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("requires both fields and does not call the API otherwise", async () => {
|
||||
render(<ForgotPasswordPage />);
|
||||
fill("jane", "");
|
||||
submit();
|
||||
|
||||
expect(await screen.findByRole("alert")).toBeInTheDocument();
|
||||
expect(mockPost).not.toHaveBeenCalled();
|
||||
expect(screen.queryByText(FIXED)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not show the message before submit", async () => {
|
||||
render(<ForgotPasswordPage />);
|
||||
await waitFor(() => expect(screen.getByLabelText("Username")).toBeInTheDocument());
|
||||
expect(screen.queryByText(FIXED)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/app/components/ui/card";
|
||||
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 { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import PoweredBy from "@/app/components/app/PoweredBy";
|
||||
|
||||
// Public "email me a temporary password" form. Whatever happens (match, no match, server or network
|
||||
// failure) the visitor sees the same message, so the page never reveals whether an account exists.
|
||||
export default function ForgotPasswordPage() {
|
||||
const t = useT();
|
||||
const [username, setUsername] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [required, setRequired] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [sent, setSent] = useState(false);
|
||||
|
||||
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (!username.trim() || !email.trim()) {
|
||||
setRequired(true);
|
||||
return;
|
||||
}
|
||||
setRequired(false);
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await apiPost("/api/auth/forgot-password", { username: username.trim(), email: email.trim() });
|
||||
} catch {
|
||||
// Deliberately ignored: a failure must look the same as success.
|
||||
}
|
||||
setSent(true);
|
||||
setSubmitting(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-svh flex-col items-center justify-center gap-4 bg-background p-4">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardHeader className="gap-2">
|
||||
<CardTitle className="text-lg">{t("ForgotTitle")}</CardTitle>
|
||||
<CardDescription>{t("ForgotIntro")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{sent ? (
|
||||
<p role="status" className="text-sm">{t("ForgotSent")}</p>
|
||||
) : (
|
||||
<>
|
||||
{required && <ErrorState message={t("ForgotRequired")} />}
|
||||
<form onSubmit={handleSubmit} className="space-y-4" noValidate>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="username">{t("Username")}</Label>
|
||||
<Input id="username" autoComplete="username" required value={username}
|
||||
onChange={(e) => setUsername(e.target.value)} disabled={submitting} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="email">{t("Email")}</Label>
|
||||
<Input id="email" type="email" autoComplete="email" required value={email}
|
||||
onChange={(e) => setEmail(e.target.value)} disabled={submitting} />
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={submitting}>
|
||||
{submitting && <Loader2 aria-hidden="true" className="size-4 animate-spin" />}
|
||||
{t("ForgotSubmit")}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
<Link href="/login" className="block text-sm text-muted-foreground underline-offset-4 hover:underline">
|
||||
{t("ForgotBack")}
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="text-center">
|
||||
<PoweredBy />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -49,11 +49,12 @@ describe("flattenModules", () => {
|
||||
});
|
||||
|
||||
function Probe() {
|
||||
const { name, branch, loading, hasRole, hasModule } = useAdminAuth();
|
||||
const { id, username, name, branch, loading, hasRole, hasModule } = useAdminAuth();
|
||||
if (loading) return <div>loading</div>;
|
||||
return (
|
||||
<div>
|
||||
<div data-testid="name">{name ?? "none"}</div>
|
||||
<div data-testid="identity">{`${id ?? "none"}:${username ?? "none"}`}</div>
|
||||
<div data-testid="branch">{branch ? `${branch.code}:${branch.name}` : "none"}</div>
|
||||
<div data-testid="has-admin-role">{String(hasRole("ROLE_ADMIN"))}</div>
|
||||
<div data-testid="has-other-role">{String(hasRole("ROLE_NOBODY"))}</div>
|
||||
@@ -79,6 +80,18 @@ describe("AdminAuthProvider", () => {
|
||||
expect(fetchMock).toHaveBeenCalledWith("/api/auth/session");
|
||||
});
|
||||
|
||||
it("exposes the signed-in user's id and username from the session", async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
makeRes({ id: 9, username: "jane", name: "Jane Admin", roles: [], aclMenu: NESTED_ACL }),
|
||||
);
|
||||
render(
|
||||
<AdminAuthProvider>
|
||||
<Probe />
|
||||
</AdminAuthProvider>,
|
||||
);
|
||||
await waitFor(() => expect(screen.getByTestId("identity")).toHaveTextContent("9:jane"));
|
||||
});
|
||||
|
||||
it("hasRole matches over roles[].name", async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
makeRes({ name: "Jane Admin", roles: [{ name: "ROLE_ADMIN" }], aclMenu: NESTED_ACL }),
|
||||
|
||||
@@ -11,6 +11,9 @@ import type { AdminBranchRef, AdminModule, AdminRole } from "@/app/lib/types";
|
||||
// not stored in the cookie").
|
||||
|
||||
interface AdminAuthCtx {
|
||||
/** The signed-in admin's user id and username (null until the session loads). */
|
||||
id: number | null;
|
||||
username: string | null;
|
||||
name: string | null;
|
||||
roles: AdminRole[];
|
||||
aclMenu: AdminModule | null;
|
||||
@@ -28,6 +31,8 @@ interface AdminAuthCtx {
|
||||
}
|
||||
|
||||
const AdminAuthContext = createContext<AdminAuthCtx>({
|
||||
id: null,
|
||||
username: null,
|
||||
name: null,
|
||||
roles: [],
|
||||
aclMenu: null,
|
||||
@@ -52,6 +57,8 @@ export function flattenModules(root: AdminModule | null | undefined): AdminModul
|
||||
}
|
||||
|
||||
export function AdminAuthProvider({ children }: { children: ReactNode }) {
|
||||
const [id, setId] = useState<number | null>(null);
|
||||
const [username, setUsername] = useState<string | null>(null);
|
||||
const [name, setName] = useState<string | null>(null);
|
||||
const [roles, setRoles] = useState<AdminRole[]>([]);
|
||||
const [aclMenu, setAclMenu] = useState<AdminModule | null>(null);
|
||||
@@ -65,6 +72,8 @@ export function AdminAuthProvider({ children }: { children: ReactNode }) {
|
||||
// 401 on a public page (e.g. /login) must not throw or redirect-loop.
|
||||
const res = await fetch("/api/auth/session");
|
||||
if (!res.ok) {
|
||||
setId(null);
|
||||
setUsername(null);
|
||||
setName(null);
|
||||
setRoles([]);
|
||||
setAclMenu(null);
|
||||
@@ -73,17 +82,23 @@ export function AdminAuthProvider({ children }: { children: ReactNode }) {
|
||||
return;
|
||||
}
|
||||
const data = (await res.json()) as {
|
||||
id?: number;
|
||||
username?: string;
|
||||
name: string;
|
||||
roles: AdminRole[];
|
||||
aclMenu: AdminModule;
|
||||
branch?: AdminBranchRef | null;
|
||||
};
|
||||
setId(data.id ?? null);
|
||||
setUsername(data.username ?? null);
|
||||
setName(data.name);
|
||||
setRoles(data.roles ?? []);
|
||||
setAclMenu(data.aclMenu ?? null);
|
||||
setGrantedMenu(data.aclMenu ?? null);
|
||||
setBranch(data.branch ?? null);
|
||||
} catch {
|
||||
setId(null);
|
||||
setUsername(null);
|
||||
setName(null);
|
||||
setRoles([]);
|
||||
setAclMenu(null);
|
||||
@@ -115,7 +130,7 @@ export function AdminAuthProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
return (
|
||||
<AdminAuthContext.Provider
|
||||
value={{ name, roles, aclMenu, branch, loading, refresh: load, hasRole, hasModule, hasGrantedModule }}
|
||||
value={{ id, username, name, roles, aclMenu, branch, loading, refresh: load, hasRole, hasModule, hasGrantedModule }}
|
||||
>
|
||||
{children}
|
||||
</AdminAuthContext.Provider>
|
||||
|
||||
@@ -19,6 +19,13 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
Username: "Username",
|
||||
Password: "Password",
|
||||
LogIn: "Log in",
|
||||
ForgotLink: "Forgot password?",
|
||||
ForgotTitle: "Forgot password",
|
||||
ForgotIntro: "Enter your username and email and we will send you a temporary password.",
|
||||
ForgotSubmit: "Email me a temporary password",
|
||||
ForgotRequired: "Username and email are required.",
|
||||
ForgotSent: "If the details match an account, we have emailed a temporary password.",
|
||||
ForgotBack: "Back to log in",
|
||||
Logout: "Logout",
|
||||
Code: "Code",
|
||||
Description: "Description",
|
||||
@@ -123,6 +130,7 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
UsrLoadingRoles: "Loading roles",
|
||||
UsrNoRolesAvailable: "No roles available.",
|
||||
UsrDisabledHint: "Disabled users cannot sign in.",
|
||||
UsrOwnAccountHint: "You can't deactivate your own account",
|
||||
UsrNameRequired: "Name is required.",
|
||||
UsrCreatedBanner: "User created. Set a password via Change password, or send a password reset email.",
|
||||
UsrLoadFailed: "Failed to load user",
|
||||
|
||||
@@ -10,7 +10,13 @@ describe("isPublicPath", () => {
|
||||
|
||||
it("includes a reset-password placeholder for a future forced-reset flow", () => {
|
||||
expect(isPublicPath("/reset-password")).toBe(true);
|
||||
expect([...PUBLIC_PATHS].sort()).toEqual(["/login", "/reset-password"]);
|
||||
expect([...PUBLIC_PATHS].sort()).toEqual(["/forgot-password", "/login", "/reset-password"]);
|
||||
});
|
||||
|
||||
it("lets signed-out visitors open /forgot-password and signed-in users too", () => {
|
||||
expect(isPublicPath("/forgot-password")).toBe(true);
|
||||
expect(guardDecision("/forgot-password", null)).toBeNull();
|
||||
expect(guardDecision("/forgot-password", { present: true })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
// Ported from solvway-customer-portal's app/lib/routeGuard.ts, trimmed to the
|
||||
// admin portal's session shape.
|
||||
|
||||
// /forgot-password is the signed-out "email me a temporary password" form.
|
||||
// /reset-password is the first sign-in set-password form (login answered
|
||||
// resetPasswordRequired); it is reached right after login, so it stays public.
|
||||
export const PUBLIC_PATHS = new Set<string>(["/login", "/reset-password"]);
|
||||
export const PUBLIC_PATHS = new Set<string>(["/login", "/reset-password", "/forgot-password"]);
|
||||
|
||||
export function isPublicPath(pathname: string): boolean {
|
||||
return PUBLIC_PATHS.has(pathname);
|
||||
|
||||
@@ -76,6 +76,8 @@ export interface AdminBranchRef {
|
||||
|
||||
/** Response body for GET /api/admin/me (mobile-api AdminMeResponse). */
|
||||
export interface AdminMeResponse {
|
||||
id?: number;
|
||||
username?: string;
|
||||
name: string;
|
||||
roles: AdminRole[];
|
||||
aclMenu: AdminModule;
|
||||
|
||||
@@ -115,6 +115,13 @@ describe("LoginPage", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Forgot password link", () => {
|
||||
it("points to /forgot-password", () => {
|
||||
render(<LoginPage />);
|
||||
expect(screen.getByRole("link", { name: "Forgot password?" })).toHaveAttribute("href", "/forgot-password");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Containerverse credit", () => {
|
||||
it("is shown on the login page, linked to containerverse.dev", () => {
|
||||
render(<LoginPage />);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useState, useSyncExternalStore } from "react";
|
||||
import { Eye, EyeOff, Loader2, Package, Truck, Users } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
@@ -165,6 +166,10 @@ export default function LoginPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Link href="/forgot-password" className="block text-sm text-muted-foreground underline-offset-4 hover:underline">
|
||||
{t("ForgotLink")}
|
||||
</Link>
|
||||
|
||||
<Button type="submit" className="h-11 w-full text-base shadow-md" disabled={submitting}>
|
||||
{submitting && <Loader2 aria-hidden="true" className="size-4 animate-spin" />}
|
||||
{t("LogIn")}
|
||||
|
||||
@@ -169,4 +169,18 @@ describe("RoleAccessPage", () => {
|
||||
await userEvent.click(screen.getByLabelText("BO_ADMINISTRATION"));
|
||||
expect(screen.getByLabelText("BO_ADMINISTRATION")).not.toBeChecked();
|
||||
});
|
||||
|
||||
it("shows the API's lock-out message when the save is refused", async () => {
|
||||
const message = "You cannot remove access control from a role you hold";
|
||||
mocks.getRoleGrantTree.mockResolvedValue(TREE);
|
||||
mocks.updateRoleGrantTree.mockRejectedValue(new Error(message));
|
||||
render(<RoleAccessPage />);
|
||||
await waitFor(() => expect(screen.getByLabelText("Users")).toBeInTheDocument());
|
||||
|
||||
await userEvent.click(screen.getByLabelText("Users"));
|
||||
await userEvent.click(screen.getByRole("button", { name: /save/i }));
|
||||
await userEvent.click(screen.getByRole("button", { name: /confirm/i }));
|
||||
|
||||
expect(await screen.findByText(message)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -109,4 +109,21 @@ describe("RolesPage", () => {
|
||||
expect(await screen.findByText(/could not be saved/i)).toBeInTheDocument();
|
||||
expect(screen.getByRole("dialog")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the backend ROLE_NAME_TAKEN message in the dialog on a rejected create", async () => {
|
||||
const message = "A role with this name already exists";
|
||||
mocks.listAdminRoles.mockResolvedValue([{ id: 4, name: "ROLE_HQ", parent: { id: 1 } }]);
|
||||
mocks.apiPost.mockRejectedValue(new Error(message));
|
||||
render(<RolesPage />);
|
||||
await waitFor(() => expect(screen.getByText("ROLE_HQ")).toBeInTheDocument());
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: /add role/i }));
|
||||
await userEvent.type(screen.getByLabelText(/role name/i), "ROLE_HQ");
|
||||
await userEvent.click(screen.getByLabelText(/parent/i));
|
||||
await userEvent.click(await screen.findByRole("option", { name: "HQ" }));
|
||||
await userEvent.click(screen.getByRole("button", { name: /save/i }));
|
||||
|
||||
expect(await screen.findByText(message)).toBeInTheDocument();
|
||||
expect(screen.getByRole("dialog")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -126,6 +126,6 @@ public class AdminAuthController {
|
||||
if (u == null) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(new AdminMeResponse(u.getName(), u.getRoles(), u.getAclMenu()));
|
||||
return ResponseEntity.ok(new AdminMeResponse(u.getId(), u.getUsername(), u.getName(), u.getRoles(), u.getAclMenu()));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -6,5 +6,5 @@ import com.solvway.core.model.Role;
|
||||
import java.util.List;
|
||||
|
||||
/** Body of {@code GET /api/admin/me}. No token or password fields. */
|
||||
public record AdminMeResponse(String name, List<Role> roles, Module aclMenu) {
|
||||
public record AdminMeResponse(Long id, String username, String name, List<Role> roles, Module aclMenu) {
|
||||
}
|
||||
+3
@@ -188,9 +188,12 @@ class AdminAuthControllerTest {
|
||||
void me_returnsNameRolesAndAclMenu() throws Exception {
|
||||
User u = user(true, GeneralEnum.LoginStatus.Y);
|
||||
u.setAclMenu(new com.solvway.core.model.Module());
|
||||
u.setUsername("admin.user");
|
||||
when(auth.loadUserByToken("tok")).thenReturn(u);
|
||||
|
||||
mvc.perform(get("/api/admin/me")).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id").value(9))
|
||||
.andExpect(jsonPath("$.username").value("admin.user"))
|
||||
.andExpect(jsonPath("$.name").value("Admin User"))
|
||||
.andExpect(jsonPath("$.roles[0].name").value("ROLE_ADMIN"))
|
||||
.andExpect(jsonPath("$.aclMenu").exists())
|
||||
|
||||
Reference in new issue
Block a user