diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md index ada29a5..629ad76 100644 --- a/docs/ASSUMPTIONS.md +++ b/docs/ASSUMPTIONS.md @@ -49,3 +49,4 @@ Items marked "to be confirmed" or left flexible in the proposal are recorded her - Prohibited passwords: blocklist of common passwords (`123456`, `12345678`, `password`, `password1`, `qwerty123`, `admin123`, `welcome1`), while preserving `demo@123` for seeded testing environments. - Username containment: cannot contain the user's email username (local part before `@`) if 4 or more characters. - Password changes additionally require that the new password is not identical to the current password. +28. **Admin Reset Password Interface (Task 5)**: `frontend/src/api/users.ts` and `frontend/src/pages/MastersPage.tsx` expose an administrator password reset modal for users with role `system_admin`. The dialog features password masking toggles, client-side mismatch validation (`Passwords do not match`), universal password policy helper instructions, and displays backend 422 validation errors inline. Successful resets trigger a notification toast and close the modal without affecting the active administrator session. diff --git a/frontend/src/api/masters.ts b/frontend/src/api/masters.ts index 5ae7dd3..e589d84 100644 --- a/frontend/src/api/masters.ts +++ b/frontend/src/api/masters.ts @@ -153,6 +153,8 @@ export const usersApi = { }> ) => api.patch(`/users/${id}`, data), remove: (id: number) => api.delete(`/users/${id}`), + resetPassword: (id: number, new_password: string) => + api.post<{ message: string }>(`/users/${id}/reset-password`, { new_password }), }; export interface UserLookupItem { diff --git a/frontend/src/api/users.ts b/frontend/src/api/users.ts new file mode 100644 index 0000000..e646f81 --- /dev/null +++ b/frontend/src/api/users.ts @@ -0,0 +1,7 @@ +import { api } from "./client"; +import { usersApi } from "./masters"; + +export { usersApi }; + +export const resetPassword = (id: number, new_password: string) => + api.post<{ message: string }>(`/users/${id}/reset-password`, { new_password }); diff --git a/frontend/src/pages/MastersPage.tsx b/frontend/src/pages/MastersPage.tsx index 524212e..71d7e4c 100644 --- a/frontend/src/pages/MastersPage.tsx +++ b/frontend/src/pages/MastersPage.tsx @@ -1,16 +1,18 @@ -import { useState, useMemo } from "react"; +import { useState, useMemo, useEffect } from "react"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import type { ColumnDef } from "@tanstack/react-table"; -import { Plus, Pencil, Power, AlertCircle } from "lucide-react"; +import { Plus, Pencil, Power, AlertCircle, KeyRound, Eye, EyeOff } from "lucide-react"; import { DataTable } from "@/components/DataTable"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Modal } from "@/components/ui/dialog"; import { ApiError } from "@/api/client"; import { ROLE_LABELS, type Role } from "@/lib/permissions"; +import { useAuthStore } from "@/hooks/useAuth"; +import { toast } from "@/lib/toast"; import { departmentsApi, locationsApi, @@ -542,6 +544,113 @@ function UserModal({ ); } +export function ResetPasswordModal({ + user, + onClose, +}: { + user: MasterUser | null; + onClose: () => void; +}) { + const [newPassword, setNewPassword] = useState(""); + const [confirmPassword, setConfirmPassword] = useState(""); + const [showPassword, setShowPassword] = useState(false); + const [clientError, setClientError] = useState(null); + const [serverError, setServerError] = useState(null); + const [submitting, setSubmitting] = useState(false); + + useEffect(() => { + setNewPassword(""); + setConfirmPassword(""); + setShowPassword(false); + setClientError(null); + setServerError(null); + }, [user]); + + if (!user) return null; + + async function handleSubmit(e: React.FormEvent) { + e.preventDefault(); + if (!user) return; + setClientError(null); + setServerError(null); + + if (newPassword !== confirmPassword) { + setClientError("Passwords do not match"); + return; + } + + setSubmitting(true); + try { + await usersApi.resetPassword(user.id, newPassword); + toast.success(`Password for ${user.name} has been reset.`); + setNewPassword(""); + setConfirmPassword(""); + onClose(); + } catch (err) { + setServerError(err instanceof ApiError ? err.detail : "Failed to reset password."); + } finally { + setSubmitting(false); + } + } + + return ( + !open && onClose()} + title={`Reset Password for ${user.name}`} + > + +
+
+ +
+ setNewPassword(e.target.value)} + required + className={inputCls} + placeholder="Enter new password" + autoComplete="new-password" + /> + +
+

At least 8 characters, with a letter and a number.

+
+ +
+ + setConfirmPassword(e.target.value)} + required + className={inputCls} + placeholder="Re-enter new password" + autoComplete="new-password" + /> +
+ +
+ + +
+
+
+ ); +} + // --- Main MastersPage --- export function MastersPage() { const qc = useQueryClient(); @@ -554,6 +663,8 @@ export function MastersPage() { const [editingCat, setEditingCat] = useState(null); const [editingVendor, setEditingVendor] = useState(null); const [editingUser, setEditingUser] = useState(null); + const [resetPasswordUser, setResetPasswordUser] = useState(null); + const { user: currentUser } = useAuthStore(); const deptsQuery = useQuery({ queryKey: ["departments", includeInactive], @@ -806,17 +917,30 @@ export function MastersPage() { enableSorting: false, enableColumnFilter: false, cell: ({ row }) => ( - { - setEditingUser(row.original); - setModalOpen(true); - }} - onToggleActive={() => - toggleMutation.mutate({ tab: "users", id: row.original.id, currentlyActive: row.original.is_active }) - } - /> +
e.stopPropagation()}> + { + setEditingUser(row.original); + setModalOpen(true); + }} + onToggleActive={() => + toggleMutation.mutate({ tab: "users", id: row.original.id, currentlyActive: row.original.is_active }) + } + /> + {currentUser?.role === "system_admin" && ( + + )} +
), }, ]; @@ -947,6 +1071,12 @@ export function MastersPage() { departments={activeDepartments} /> )} + {resetPasswordUser && ( + setResetPasswordUser(null)} + /> + )} ); } diff --git a/frontend/src/test/admin-reset-password.test.tsx b/frontend/src/test/admin-reset-password.test.tsx new file mode 100644 index 0000000..746fa7d --- /dev/null +++ b/frontend/src/test/admin-reset-password.test.tsx @@ -0,0 +1,109 @@ +import { describe, it, expect, beforeEach, vi } from "vitest"; +import { render, screen, fireEvent, waitFor } from "@testing-library/react"; +import { ResetPasswordModal } from "@/pages/MastersPage"; +import { usersApi, type MasterUser } from "@/api/masters"; +import { toast } from "@/lib/toast"; +import { ApiError } from "@/api/client"; + +const mockUser: MasterUser = { + id: 42, + name: "Dr. Jane Doe", + email: "jane@poona.demo", + role: "department_user", + department_id: 2, + department_name: "Cardiology", + is_active: true, +}; + +describe("Admin ResetPasswordModal", () => { + beforeEach(() => { + vi.restoreAllMocks(); + }); + + it("renders the dialog with user details, helper text, and show/hide password toggle", () => { + render(); + + expect(screen.getByText("Reset Password for Dr. Jane Doe")).toBeInTheDocument(); + expect(screen.getByPlaceholderText("Enter new password")).toBeInTheDocument(); + expect(screen.getByPlaceholderText("Re-enter new password")).toBeInTheDocument(); + expect( + screen.getByText("At least 8 characters, with a letter and a number.") + ).toBeInTheDocument(); + + const input = screen.getByPlaceholderText("Enter new password"); + expect(input).toHaveAttribute("type", "password"); + + const toggleBtn = screen.getByLabelText("Show password"); + fireEvent.click(toggleBtn); + expect(input).toHaveAttribute("type", "text"); + expect(screen.getByLabelText("Hide password")).toBeInTheDocument(); + }); + + it("validates password mismatch before calling API", async () => { + const resetSpy = vi.spyOn(usersApi, "resetPassword").mockResolvedValue({ message: "OK" }); + + render(); + + fireEvent.change(screen.getByPlaceholderText("Enter new password"), { + target: { value: "SecurePass1" }, + }); + fireEvent.change(screen.getByPlaceholderText("Re-enter new password"), { + target: { value: "DifferentPass2" }, + }); + + fireEvent.click(screen.getByRole("button", { name: "Reset Password" })); + + await waitFor(() => { + expect(screen.getByText(/passwords do not match/i)).toBeInTheDocument(); + }); + expect(resetSpy).not.toHaveBeenCalled(); + }); + + it("calls API on match, shows success toast, and closes dialog", async () => { + const onClose = vi.fn(); + const resetSpy = vi + .spyOn(usersApi, "resetPassword") + .mockResolvedValue({ message: "Password reset successfully." }); + const toastSpy = vi.spyOn(toast, "success"); + + render(); + + fireEvent.change(screen.getByPlaceholderText("Enter new password"), { + target: { value: "NewSecure99" }, + }); + fireEvent.change(screen.getByPlaceholderText("Re-enter new password"), { + target: { value: "NewSecure99" }, + }); + + fireEvent.click(screen.getByRole("button", { name: "Reset Password" })); + + await waitFor(() => { + expect(resetSpy).toHaveBeenCalledWith(42, "NewSecure99"); + expect(toastSpy).toHaveBeenCalledWith("Password for Dr. Jane Doe has been reset."); + expect(onClose).toHaveBeenCalled(); + }); + }); + + it("displays server error message when API returns 422 error", async () => { + vi.spyOn(usersApi, "resetPassword").mockRejectedValue( + new ApiError(422, "Password must not start or end with a space.") + ); + + render(); + + fireEvent.change(screen.getByPlaceholderText("Enter new password"), { + target: { value: " SpacePass1 " }, + }); + fireEvent.change(screen.getByPlaceholderText("Re-enter new password"), { + target: { value: " SpacePass1 " }, + }); + + fireEvent.click(screen.getByRole("button", { name: "Reset Password" })); + + await waitFor(() => { + expect( + screen.getByText("Password must not start or end with a space.") + ).toBeInTheDocument(); + }); + }); +});