fix(task5): add admin reset-password dialog in masters page

This commit is contained in:
Atharv1705
2026-11-17 18:07:50 +05:30
parent 5f649e3e4c
commit cb47017eac
5 changed files with 262 additions and 13 deletions
+1
View File
@@ -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. - 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. - 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. - 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.
+2
View File
@@ -153,6 +153,8 @@ export const usersApi = {
}> }>
) => api.patch<MasterUser>(`/users/${id}`, data), ) => api.patch<MasterUser>(`/users/${id}`, data),
remove: (id: number) => api.delete<void>(`/users/${id}`), remove: (id: number) => api.delete<void>(`/users/${id}`),
resetPassword: (id: number, new_password: string) =>
api.post<{ message: string }>(`/users/${id}/reset-password`, { new_password }),
}; };
export interface UserLookupItem { export interface UserLookupItem {
+7
View File
@@ -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 });
+132 -2
View File
@@ -1,16 +1,18 @@
import { useState, useMemo } from "react"; import { useState, useMemo, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod"; import { z } from "zod";
import type { ColumnDef } from "@tanstack/react-table"; 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 { DataTable } from "@/components/DataTable";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Modal } from "@/components/ui/dialog"; import { Modal } from "@/components/ui/dialog";
import { ApiError } from "@/api/client"; import { ApiError } from "@/api/client";
import { ROLE_LABELS, type Role } from "@/lib/permissions"; import { ROLE_LABELS, type Role } from "@/lib/permissions";
import { useAuthStore } from "@/hooks/useAuth";
import { toast } from "@/lib/toast";
import { import {
departmentsApi, departmentsApi,
locationsApi, 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<string | null>(null);
const [serverError, setServerError] = useState<string | null>(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 (
<Modal
open={Boolean(user)}
onOpenChange={(open) => !open && onClose()}
title={`Reset Password for ${user.name}`}
>
<FormErrorBanner message={clientError || serverError} />
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className={labelCls}>New Password *</label>
<div className="relative">
<input
type={showPassword ? "text" : "password"}
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
required
className={inputCls}
placeholder="Enter new password"
autoComplete="new-password"
/>
<button
type="button"
onClick={() => setShowPassword((s) => !s)}
className="absolute right-2.5 top-2.5 text-gray-400 hover:text-gray-600"
aria-label={showPassword ? "Hide password" : "Show password"}
>
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</button>
</div>
<p className="text-xs text-gray-500 mt-1">At least 8 characters, with a letter and a number.</p>
</div>
<div>
<label className={labelCls}>Confirm Password *</label>
<input
type={showPassword ? "text" : "password"}
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
className={inputCls}
placeholder="Re-enter new password"
autoComplete="new-password"
/>
</div>
<div className="flex justify-end gap-2 pt-2 border-t border-gray-100">
<Button type="button" variant="outline" onClick={onClose} disabled={submitting}>
Cancel
</Button>
<Button type="submit" loading={submitting}>
Reset Password
</Button>
</div>
</form>
</Modal>
);
}
// --- Main MastersPage --- // --- Main MastersPage ---
export function MastersPage() { export function MastersPage() {
const qc = useQueryClient(); const qc = useQueryClient();
@@ -554,6 +663,8 @@ export function MastersPage() {
const [editingCat, setEditingCat] = useState<Category | null>(null); const [editingCat, setEditingCat] = useState<Category | null>(null);
const [editingVendor, setEditingVendor] = useState<Vendor | null>(null); const [editingVendor, setEditingVendor] = useState<Vendor | null>(null);
const [editingUser, setEditingUser] = useState<MasterUser | null>(null); const [editingUser, setEditingUser] = useState<MasterUser | null>(null);
const [resetPasswordUser, setResetPasswordUser] = useState<MasterUser | null>(null);
const { user: currentUser } = useAuthStore();
const deptsQuery = useQuery({ const deptsQuery = useQuery({
queryKey: ["departments", includeInactive], queryKey: ["departments", includeInactive],
@@ -806,6 +917,7 @@ export function MastersPage() {
enableSorting: false, enableSorting: false,
enableColumnFilter: false, enableColumnFilter: false,
cell: ({ row }) => ( cell: ({ row }) => (
<div className="flex items-center gap-1.5" onClick={(e) => e.stopPropagation()}>
<RowActions <RowActions
active={row.original.is_active} active={row.original.is_active}
busy={toggleMutation.isPending} busy={toggleMutation.isPending}
@@ -817,6 +929,18 @@ export function MastersPage() {
toggleMutation.mutate({ tab: "users", id: row.original.id, currentlyActive: row.original.is_active }) toggleMutation.mutate({ tab: "users", id: row.original.id, currentlyActive: row.original.is_active })
} }
/> />
{currentUser?.role === "system_admin" && (
<Button
variant="outline"
size="sm"
onClick={() => setResetPasswordUser(row.original)}
className="text-blue-600 hover:text-blue-800"
>
<KeyRound className="h-3.5 w-3.5 mr-1" />
Reset password
</Button>
)}
</div>
), ),
}, },
]; ];
@@ -947,6 +1071,12 @@ export function MastersPage() {
departments={activeDepartments} departments={activeDepartments}
/> />
)} )}
{resetPasswordUser && (
<ResetPasswordModal
user={resetPasswordUser}
onClose={() => setResetPasswordUser(null)}
/>
)}
</div> </div>
); );
} }
@@ -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(<ResetPasswordModal user={mockUser} onClose={vi.fn()} />);
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(<ResetPasswordModal user={mockUser} onClose={vi.fn()} />);
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(<ResetPasswordModal user={mockUser} onClose={onClose} />);
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(<ResetPasswordModal user={mockUser} onClose={vi.fn()} />);
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();
});
});
});