diff --git a/openspec/changes/add-admin-auth-users-roles/tasks.md b/openspec/changes/add-admin-auth-users-roles/tasks.md index 0697f4b..9894537 100644 --- a/openspec/changes/add-admin-auth-users-roles/tasks.md +++ b/openspec/changes/add-admin-auth-users-roles/tasks.md @@ -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 diff --git a/solvway-admin-portal/app/api/auth/forgot-password/route.test.ts b/solvway-admin-portal/app/api/auth/forgot-password/route.test.ts new file mode 100644 index 0000000..ae09bdd --- /dev/null +++ b/solvway-admin-portal/app/api/auth/forgot-password/route.test.ts @@ -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[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(); + }); +}); diff --git a/solvway-admin-portal/app/api/auth/forgot-password/route.ts b/solvway-admin-portal/app/api/auth/forgot-password/route.ts new file mode 100644 index 0000000..9964eaa --- /dev/null +++ b/solvway-admin-portal/app/api/auth/forgot-password/route.ts @@ -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 }); +} diff --git a/solvway-admin-portal/app/api/auth/session/route.test.ts b/solvway-admin-portal/app/api/auth/session/route.test.ts index 7ea0337..ab23c8f 100644 --- a/solvway-admin-portal/app/api/auth/session/route.test.ts +++ b/solvway-admin-portal/app/api/auth/session/route.test.ts @@ -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"); + }); }); diff --git a/solvway-admin-portal/app/api/auth/session/route.ts b/solvway-admin-portal/app/api/auth/session/route.ts index a0cbd4e..dc1c70f 100644 --- a/solvway-admin-portal/app/api/auth/session/route.ts +++ b/solvway-admin-portal/app/api/auth/session/route.ts @@ -25,6 +25,6 @@ export async function GET(req: NextRequest) { const result = await callMobileApi("/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 }); } diff --git a/solvway-admin-portal/app/components/users/UserForm.test.tsx b/solvway-admin-portal/app/components/users/UserForm.test.tsx index 3e96d48..0ffaba1 100644 --- a/solvway-admin-portal/app/components/users/UserForm.test.tsx +++ b/solvway-admin-portal/app/components/users/UserForm.test.tsx @@ -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( + , + ); + 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(); + 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(); + 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(); + await waitForPickers(); + + expect(screen.getByLabelText("Enabled")).not.toBeDisabled(); + }); + }); }); diff --git a/solvway-admin-portal/app/components/users/UserForm.tsx b/solvway-admin-portal/app/components/users/UserForm.tsx index 0ca1fe7..09b57b9 100644 --- a/solvway-admin-portal/app/components/users/UserForm.tsx +++ b/solvway-admin-portal/app/components/users/UserForm.tsx @@ -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) {
- +
-

{t("UsrDisabledHint")}

+

{t(isOwnAccount ? "UsrOwnAccountHint" : "UsrDisabledHint")}

+ + + )} + + {t("ForgotBack")} + + + +
+ +
+ + ); +} diff --git a/solvway-admin-portal/app/lib/AdminAuthContext.test.tsx b/solvway-admin-portal/app/lib/AdminAuthContext.test.tsx index 174aa12..1947b92 100644 --- a/solvway-admin-portal/app/lib/AdminAuthContext.test.tsx +++ b/solvway-admin-portal/app/lib/AdminAuthContext.test.tsx @@ -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
loading
; return (
{name ?? "none"}
+
{`${id ?? "none"}:${username ?? "none"}`}
{branch ? `${branch.code}:${branch.name}` : "none"}
{String(hasRole("ROLE_ADMIN"))}
{String(hasRole("ROLE_NOBODY"))}
@@ -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( + + + , + ); + 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 }), diff --git a/solvway-admin-portal/app/lib/AdminAuthContext.tsx b/solvway-admin-portal/app/lib/AdminAuthContext.tsx index f0bc499..22adf70 100644 --- a/solvway-admin-portal/app/lib/AdminAuthContext.tsx +++ b/solvway-admin-portal/app/lib/AdminAuthContext.tsx @@ -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({ + 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(null); + const [username, setUsername] = useState(null); const [name, setName] = useState(null); const [roles, setRoles] = useState([]); const [aclMenu, setAclMenu] = useState(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 ( {children} diff --git a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts index 0ad5758..f035fe5 100644 --- a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts +++ b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts @@ -19,6 +19,13 @@ export const DEFAULT_MESSAGES: Record = { 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 = { 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", diff --git a/solvway-admin-portal/app/lib/routeGuard.test.ts b/solvway-admin-portal/app/lib/routeGuard.test.ts index cbfc365..53178e6 100644 --- a/solvway-admin-portal/app/lib/routeGuard.test.ts +++ b/solvway-admin-portal/app/lib/routeGuard.test.ts @@ -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(); }); }); diff --git a/solvway-admin-portal/app/lib/routeGuard.ts b/solvway-admin-portal/app/lib/routeGuard.ts index 2d12052..23ad882 100644 --- a/solvway-admin-portal/app/lib/routeGuard.ts +++ b/solvway-admin-portal/app/lib/routeGuard.ts @@ -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(["/login", "/reset-password"]); +export const PUBLIC_PATHS = new Set(["/login", "/reset-password", "/forgot-password"]); export function isPublicPath(pathname: string): boolean { return PUBLIC_PATHS.has(pathname); diff --git a/solvway-admin-portal/app/lib/types.ts b/solvway-admin-portal/app/lib/types.ts index 5cd329e..413ea52 100644 --- a/solvway-admin-portal/app/lib/types.ts +++ b/solvway-admin-portal/app/lib/types.ts @@ -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; diff --git a/solvway-admin-portal/app/login/page.test.tsx b/solvway-admin-portal/app/login/page.test.tsx index 03f65b9..a071552 100644 --- a/solvway-admin-portal/app/login/page.test.tsx +++ b/solvway-admin-portal/app/login/page.test.tsx @@ -115,6 +115,13 @@ describe("LoginPage", () => { }); }); +describe("Forgot password link", () => { + it("points to /forgot-password", () => { + render(); + 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(); diff --git a/solvway-admin-portal/app/login/page.tsx b/solvway-admin-portal/app/login/page.tsx index 625c948..e6127f8 100644 --- a/solvway-admin-portal/app/login/page.tsx +++ b/solvway-admin-portal/app/login/page.tsx @@ -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() {
+ + {t("ForgotLink")} + +