Add DB viewer access logging, account deletion, and forced password change
Logs a distinct db_viewer_accessed event (not just the earlier session_created "requested" event) when an admin's browser actually completes the hand-off into Adminer. Adds a password-confirmed account-deletion box to Settings, relying on the existing ON DELETE CASCADE foreign keys to clean up everything the account owns. Adds an admin-only "require password change" flag that get_current_user enforces server-side (403 on everything except /auth/me, /auth/change-password, /auth/logout) - meant for handing a demo account to someone with a known sample password. Co-Authored-By: Claude Sonnet 5 <[email protected]>
This commit is contained in:
@@ -15,6 +15,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
||||
const logout = useLogout();
|
||||
|
||||
const requiresLogin = systemStatus ? !isLocalConvenience(systemStatus) : false;
|
||||
const mustChangePassword = user?.must_change_password ?? false;
|
||||
|
||||
useEffect(() => {
|
||||
if (requiresLogin && !isLoading && isError) {
|
||||
@@ -22,6 +23,12 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
||||
}
|
||||
}, [requiresLogin, isLoading, isError, router]);
|
||||
|
||||
useEffect(() => {
|
||||
if (mustChangePassword) {
|
||||
router.replace("/change-password");
|
||||
}
|
||||
}, [mustChangePassword, router]);
|
||||
|
||||
if (requiresLogin && (isLoading || isError)) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center text-sm text-slate-500">
|
||||
@@ -30,6 +37,17 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
||||
);
|
||||
}
|
||||
|
||||
// Every API call except /auth/me, /auth/change-password, and /auth/logout
|
||||
// 403s server-side while this is set (app/auth/dependencies.py) - this is
|
||||
// just the matching frontend redirect, not the actual enforcement.
|
||||
if (mustChangePassword) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center text-sm text-slate-500">
|
||||
Redirecting…
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50">
|
||||
<LocalModeBanner />
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
useCreateDbViewerSession,
|
||||
useCreateIpBan,
|
||||
useCurrentUser,
|
||||
useDeleteAccount,
|
||||
useDeleteIpBan,
|
||||
useIpBans,
|
||||
useRejectUnbanRequest,
|
||||
@@ -690,13 +691,14 @@ function DatabaseViewerBox() {
|
||||
</div>
|
||||
<p className="mt-1 text-sm text-slate-500">
|
||||
Open a web-based Postgres client (Adminer) in a new tab to view and edit rows directly.
|
||||
Local developers and server admins only.
|
||||
PostgreSQL is pre-selected - just enter the database password to sign in. Local developers
|
||||
and server admins only.
|
||||
</p>
|
||||
|
||||
<div className="mt-4">
|
||||
{isLocal ? (
|
||||
<a
|
||||
href="http://localhost:8081"
|
||||
href="http://localhost:8081/?pgsql=postgres&username=ciagent"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="focus-ring inline-flex items-center gap-1.5 rounded-md bg-slate-800 px-3 py-1.5 text-xs font-semibold text-white transition-colors duration-200 hover:bg-slate-900"
|
||||
@@ -720,6 +722,64 @@ function DatabaseViewerBox() {
|
||||
);
|
||||
}
|
||||
|
||||
function DeleteAccountBox() {
|
||||
const { data: systemStatus } = useSystemStatus();
|
||||
const [password, setPassword] = useState("");
|
||||
const deleteAccount = useDeleteAccount();
|
||||
const isLocal = systemStatus ? isLocalConvenience(systemStatus) : false;
|
||||
|
||||
// The local-dev bypass account has no password_hash at all (it never
|
||||
// registers/logs in) - there's nothing to type to confirm deletion, and
|
||||
// deleting it would just get silently re-created on the next request.
|
||||
if (isLocal) return null;
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-red-200 bg-red-50 p-6">
|
||||
<div className="flex items-center gap-2 text-sm font-semibold text-red-700">
|
||||
<Trash2 className="h-4 w-4" aria-hidden /> Delete account
|
||||
</div>
|
||||
<p className="mt-1 text-sm text-red-700/80">
|
||||
Permanently deletes your account and everything in it - companies, monitoring history,
|
||||
reports, and API keys. This can't be undone.
|
||||
</p>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
deleteAccount.mutate({ password });
|
||||
}}
|
||||
className="mt-4 flex flex-wrap items-end gap-2"
|
||||
>
|
||||
<div className="min-w-[220px] flex-1">
|
||||
<label htmlFor="delete-account-password" className="block text-sm font-medium text-red-700">
|
||||
Confirm your password
|
||||
</label>
|
||||
<input
|
||||
id="delete-account-password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="focus-ring mt-1 block w-full rounded-md border border-red-300 px-3 py-2 text-sm text-slate-900 shadow-sm transition-colors duration-150"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!password || deleteAccount.isPending}
|
||||
className="focus-ring inline-flex shrink-0 items-center gap-1.5 rounded-md bg-red-600 px-3 py-2 text-sm font-semibold text-white transition-colors duration-200 hover:bg-red-700 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{deleteAccount.isPending && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
|
||||
{deleteAccount.isPending ? "Deleting…" : "Delete account"}
|
||||
</button>
|
||||
</form>
|
||||
{deleteAccount.isError && (
|
||||
<p className="mt-2 text-sm text-red-700" role="alert">
|
||||
{authErrorMessage(deleteAccount.error)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function SettingsPage() {
|
||||
const { data: user } = useCurrentUser();
|
||||
const { data: systemStatus } = useSystemStatus();
|
||||
@@ -820,6 +880,8 @@ export default function SettingsPage() {
|
||||
<LoggingBox />
|
||||
</>
|
||||
)}
|
||||
|
||||
<DeleteAccountBox />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { KeyRound, Loader2 } from "lucide-react";
|
||||
import { z } from "zod";
|
||||
import { PasswordField } from "@/components/ui/password-field";
|
||||
import { PasswordStrengthMeter } from "@/components/ui/password-strength-meter";
|
||||
import { authErrorMessage, useChangePassword } from "@/hooks/use-auth";
|
||||
|
||||
const changePasswordSchema = z.object({
|
||||
currentPassword: z.string().min(1, "Enter your current password"),
|
||||
newPassword: z
|
||||
.string()
|
||||
.min(10, "Must be at least 10 characters")
|
||||
.refine((v) => /[a-zA-Z]/.test(v) && /\d/.test(v), {
|
||||
message: "Must contain at least one letter and one digit",
|
||||
}),
|
||||
});
|
||||
|
||||
type ChangePasswordForm = z.infer<typeof changePasswordSchema>;
|
||||
|
||||
export default function ChangePasswordPage() {
|
||||
const router = useRouter();
|
||||
const changePassword = useChangePassword();
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
watch,
|
||||
formState: { errors },
|
||||
} = useForm<ChangePasswordForm>({ resolver: zodResolver(changePasswordSchema) });
|
||||
|
||||
const onSubmit = handleSubmit(async (values) => {
|
||||
try {
|
||||
await changePassword.mutateAsync({
|
||||
current_password: values.currentPassword,
|
||||
new_password: values.newPassword,
|
||||
});
|
||||
router.replace("/dashboard");
|
||||
} catch {
|
||||
// Surfaced via changePassword.isError below.
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-slate-50 px-4 py-12">
|
||||
<div className="w-full max-w-sm animate-fade-in overflow-hidden rounded-lg border border-slate-200 bg-white shadow-sm">
|
||||
<div className="h-1.5 bg-gradient-to-r from-brand-500 via-brand-600 to-brand-700" />
|
||||
<div className="p-8">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-brand-50 text-brand-600">
|
||||
<KeyRound className="h-4.5 w-4.5" aria-hidden />
|
||||
</span>
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-slate-900">Change your password</h1>
|
||||
<p className="text-sm text-slate-600">
|
||||
An admin requires a new password before you can continue.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={onSubmit} className="mt-6 space-y-4" noValidate>
|
||||
<PasswordField
|
||||
label="Current password"
|
||||
autoComplete="current-password"
|
||||
{...register("currentPassword")}
|
||||
error={errors.currentPassword?.message}
|
||||
/>
|
||||
<div>
|
||||
<PasswordField
|
||||
label="New password"
|
||||
autoComplete="new-password"
|
||||
hint="At least 10 characters, with a letter and a digit."
|
||||
{...register("newPassword")}
|
||||
error={errors.newPassword?.message}
|
||||
/>
|
||||
<PasswordStrengthMeter password={watch("newPassword") ?? ""} />
|
||||
</div>
|
||||
|
||||
{changePassword.isError && (
|
||||
<p className="animate-fade-in text-sm text-red-600" role="alert">
|
||||
{authErrorMessage(changePassword.error)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={changePassword.isPending}
|
||||
className="focus-ring inline-flex w-full items-center justify-center gap-2 rounded-md bg-brand-600 px-4 py-2 text-sm font-semibold text-white transition-colors duration-200 hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{changePassword.isPending && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
|
||||
{changePassword.isPending ? "Updating…" : "Update password"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,9 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { ApiError, api, clearTokens, getRefreshToken, setTokens } from "@/lib/api-client";
|
||||
import type {
|
||||
BanIpPayload,
|
||||
ChangePasswordPayload,
|
||||
ConfirmPasswordResetPayload,
|
||||
DeleteAccountPayload,
|
||||
LoginPayload,
|
||||
RegisterPayload,
|
||||
RequestPasswordResetPayload,
|
||||
@@ -110,6 +112,33 @@ export function useLogout() {
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteAccount() {
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (payload: DeleteAccountPayload) => api.deleteAccount(payload),
|
||||
onSuccess: () => {
|
||||
// Same reasoning as useLogout: we know for certain the account is
|
||||
// gone, so clear and navigate immediately rather than waiting on a
|
||||
// background refetch of ["me"] to fail.
|
||||
clearTokens();
|
||||
queryClient.clear();
|
||||
router.replace("/");
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useChangePassword() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (payload: ChangePasswordPayload) => api.changePassword(payload),
|
||||
onSuccess: (tokens) => {
|
||||
setTokens(tokens.access_token, tokens.refresh_token);
|
||||
return queryClient.invalidateQueries({ queryKey: ["me"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useVerifyEmail() {
|
||||
return useMutation({
|
||||
mutationFn: (payload: VerifyEmailPayload) => api.verifyEmail(payload),
|
||||
|
||||
@@ -10,8 +10,10 @@ import type {
|
||||
CompanyResponse,
|
||||
CompanyUpdatePayload,
|
||||
ConfirmPasswordResetPayload,
|
||||
ChangePasswordPayload,
|
||||
DashboardAnalytics,
|
||||
DbViewerSessionResponse,
|
||||
DeleteAccountPayload,
|
||||
DiscoverCompanyRequest,
|
||||
DiscoveredCompanyProfile,
|
||||
IpBan,
|
||||
@@ -205,6 +207,18 @@ export const api = {
|
||||
|
||||
me: () => request<MeResponse>("/api/v1/auth/me"),
|
||||
|
||||
deleteAccount: (payload: DeleteAccountPayload) =>
|
||||
request<void>("/api/v1/auth/me", {
|
||||
method: "DELETE",
|
||||
body: JSON.stringify(payload),
|
||||
}),
|
||||
|
||||
changePassword: (payload: ChangePasswordPayload) =>
|
||||
request<TokenResponse>("/api/v1/auth/change-password", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
}),
|
||||
|
||||
verifyEmail: (payload: VerifyEmailPayload) =>
|
||||
request<void>("/api/v1/auth/verify-email", {
|
||||
method: "POST",
|
||||
|
||||
@@ -33,6 +33,15 @@ export interface DbViewerSessionResponse {
|
||||
token: string;
|
||||
}
|
||||
|
||||
export interface DeleteAccountPayload {
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface ChangePasswordPayload {
|
||||
current_password: string;
|
||||
new_password: string;
|
||||
}
|
||||
|
||||
export interface SetSystemSecretPayload {
|
||||
value: string;
|
||||
}
|
||||
@@ -70,6 +79,7 @@ export interface UserResponse {
|
||||
timezone: string;
|
||||
is_active: boolean;
|
||||
is_admin: boolean;
|
||||
must_change_password: boolean;
|
||||
}
|
||||
|
||||
export interface MeResponse extends UserResponse {
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { screen, waitFor } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import DashboardLayout from "@/app/(app)/layout";
|
||||
import { renderWithQueryClient } from "./test-utils";
|
||||
|
||||
const replaceMock = vi.fn();
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({ push: vi.fn(), replace: replaceMock }),
|
||||
usePathname: () => "/dashboard",
|
||||
}));
|
||||
|
||||
function meBody(mustChangePassword: boolean) {
|
||||
return {
|
||||
id: "user-1",
|
||||
email: "[email protected]",
|
||||
display_name: "Regular User",
|
||||
timezone: "America/New_York",
|
||||
is_active: true,
|
||||
is_admin: false,
|
||||
auth_mode: "jwt",
|
||||
must_change_password: mustChangePassword,
|
||||
};
|
||||
}
|
||||
|
||||
function systemStatusBody() {
|
||||
return {
|
||||
app_env: "development",
|
||||
auth_mode: "jwt",
|
||||
llm_provider: "mock",
|
||||
search_provider: "mock",
|
||||
sms_enabled: false,
|
||||
sms_provider: "twilio",
|
||||
ninjapear_configured: false,
|
||||
ninjapear_credit_balance: null,
|
||||
ninjapear_estimated_credits_per_company: null,
|
||||
is_localhost: false,
|
||||
turnstile_site_key: null,
|
||||
components: [],
|
||||
};
|
||||
}
|
||||
|
||||
function mockFetchImplementation(mustChangePassword: boolean) {
|
||||
return vi.fn().mockImplementation((url: string) => {
|
||||
const path = url.replace("http://localhost:8000", "");
|
||||
if (path === "/api/v1/auth/me") {
|
||||
return Promise.resolve({ ok: true, status: 200, json: async () => meBody(mustChangePassword) });
|
||||
}
|
||||
if (path === "/api/v1/system/status") {
|
||||
return Promise.resolve({ ok: true, status: 200, json: async () => systemStatusBody() });
|
||||
}
|
||||
return Promise.resolve({ ok: false, status: 404, json: async () => ({ detail: "not found" }) });
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
replaceMock.mockClear();
|
||||
});
|
||||
|
||||
describe("DashboardLayout - must_change_password redirect", () => {
|
||||
it("redirects to /change-password and withholds the page content when the flag is set", async () => {
|
||||
vi.stubGlobal("fetch", mockFetchImplementation(true));
|
||||
renderWithQueryClient(
|
||||
<DashboardLayout>
|
||||
<div>Protected dashboard content</div>
|
||||
</DashboardLayout>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(replaceMock).toHaveBeenCalledWith("/change-password");
|
||||
});
|
||||
expect(screen.queryByText(/protected dashboard content/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders normally when the flag is not set", async () => {
|
||||
vi.stubGlobal("fetch", mockFetchImplementation(false));
|
||||
renderWithQueryClient(
|
||||
<DashboardLayout>
|
||||
<div>Protected dashboard content</div>
|
||||
</DashboardLayout>,
|
||||
);
|
||||
|
||||
expect(await screen.findByText(/protected dashboard content/i)).toBeInTheDocument();
|
||||
expect(replaceMock).not.toHaveBeenCalledWith("/change-password");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import ChangePasswordPage from "@/app/change-password/page";
|
||||
import { renderWithQueryClient } from "./test-utils";
|
||||
|
||||
const replaceMock = vi.fn();
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({ push: vi.fn(), replace: replaceMock }),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
replaceMock.mockClear();
|
||||
});
|
||||
|
||||
describe("ChangePasswordPage", () => {
|
||||
it("rejects a weak new password before submitting", async () => {
|
||||
const user = userEvent.setup();
|
||||
renderWithQueryClient(<ChangePasswordPage />);
|
||||
|
||||
await user.type(screen.getByLabelText(/current password/i), "correct-horse-1");
|
||||
await user.type(screen.getByLabelText(/new password/i), "allletters");
|
||||
await user.click(screen.getByRole("button", { name: /update password/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText(/must contain at least one letter and one digit/i),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("submits current + new password and redirects to the dashboard on success", async () => {
|
||||
const fetchMock = vi.fn().mockImplementation((url: string, init?: RequestInit) => {
|
||||
const path = url.replace("http://localhost:8000", "");
|
||||
if (path === "/api/v1/auth/change-password" && init?.method === "POST") {
|
||||
expect(JSON.parse(init.body as string)).toEqual({
|
||||
current_password: "correct-horse-1",
|
||||
new_password: "brand-new-horse-2",
|
||||
});
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
access_token: "new-access",
|
||||
refresh_token: "new-refresh",
|
||||
token_type: "bearer",
|
||||
expires_in_minutes: 15,
|
||||
}),
|
||||
});
|
||||
}
|
||||
return Promise.resolve({ ok: false, status: 404, json: async () => ({ detail: "not found" }) });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const user = userEvent.setup();
|
||||
renderWithQueryClient(<ChangePasswordPage />);
|
||||
|
||||
await user.type(screen.getByLabelText(/current password/i), "correct-horse-1");
|
||||
await user.type(screen.getByLabelText(/new password/i), "brand-new-horse-2");
|
||||
await user.click(screen.getByRole("button", { name: /update password/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(replaceMock).toHaveBeenCalledWith("/dashboard");
|
||||
});
|
||||
});
|
||||
|
||||
it("surfaces an error for the wrong current password", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 401,
|
||||
json: async () => ({ detail: "Incorrect current password" }),
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderWithQueryClient(<ChangePasswordPage />);
|
||||
|
||||
await user.type(screen.getByLabelText(/current password/i), "wrong-password-1");
|
||||
await user.type(screen.getByLabelText(/new password/i), "brand-new-horse-2");
|
||||
await user.click(screen.getByRole("button", { name: /update password/i }));
|
||||
|
||||
expect(await screen.findByText(/incorrect current password/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -4,6 +4,10 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import SettingsPage from "@/app/(app)/settings/page";
|
||||
import { renderWithQueryClient } from "./test-utils";
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
|
||||
}));
|
||||
|
||||
const ADMIN_USER = {
|
||||
id: "user-1",
|
||||
email: "[email protected]",
|
||||
@@ -12,6 +16,7 @@ const ADMIN_USER = {
|
||||
is_active: true,
|
||||
is_admin: true,
|
||||
auth_mode: "jwt",
|
||||
must_change_password: false,
|
||||
};
|
||||
|
||||
function systemStatusBody(isLocalhost: boolean, authMode: "local" | "jwt") {
|
||||
@@ -67,7 +72,7 @@ describe("Settings - Database viewer box", () => {
|
||||
renderWithQueryClient(<SettingsPage />);
|
||||
|
||||
const link = await screen.findByRole("link", { name: /open database viewer/i });
|
||||
expect(link).toHaveAttribute("href", "http://localhost:8081");
|
||||
expect(link).toHaveAttribute("href", "http://localhost:8081/?pgsql=postgres&username=ciagent");
|
||||
expect(link).toHaveAttribute("target", "_blank");
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import { screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import SettingsPage from "@/app/(app)/settings/page";
|
||||
import { renderWithQueryClient } from "./test-utils";
|
||||
|
||||
const replaceMock = vi.fn();
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({ push: vi.fn(), replace: replaceMock }),
|
||||
}));
|
||||
|
||||
const REGULAR_USER = {
|
||||
id: "user-1",
|
||||
email: "[email protected]",
|
||||
display_name: "Regular User",
|
||||
timezone: "America/New_York",
|
||||
is_active: true,
|
||||
is_admin: false,
|
||||
auth_mode: "jwt",
|
||||
must_change_password: false,
|
||||
};
|
||||
|
||||
const LOCAL_DEV_USER = {
|
||||
id: "00000000-0000-0000-0000-000000000001",
|
||||
email: "[email protected]",
|
||||
display_name: "Local Developer",
|
||||
timezone: "America/New_York",
|
||||
is_active: true,
|
||||
is_admin: true,
|
||||
auth_mode: "local",
|
||||
must_change_password: false,
|
||||
};
|
||||
|
||||
function systemStatusBody(isLocalhost: boolean, authMode: "local" | "jwt") {
|
||||
return {
|
||||
app_env: "development",
|
||||
auth_mode: authMode,
|
||||
llm_provider: "mock",
|
||||
search_provider: "mock",
|
||||
sms_enabled: false,
|
||||
sms_provider: "twilio",
|
||||
ninjapear_configured: false,
|
||||
ninjapear_credit_balance: null,
|
||||
ninjapear_estimated_credits_per_company: null,
|
||||
is_localhost: isLocalhost,
|
||||
turnstile_site_key: null,
|
||||
components: [],
|
||||
};
|
||||
}
|
||||
|
||||
function mockFetchImplementation(
|
||||
isLocalhost: boolean,
|
||||
authMode: "local" | "jwt",
|
||||
meUser: typeof REGULAR_USER,
|
||||
) {
|
||||
return vi.fn().mockImplementation((url: string, init?: RequestInit) => {
|
||||
const path = url.replace("http://localhost:8000", "");
|
||||
const ok = (json: unknown, status = 200) =>
|
||||
Promise.resolve({ ok: true, status, json: async () => json });
|
||||
|
||||
if (path === "/api/v1/auth/me") return ok(meUser);
|
||||
if (path === "/api/v1/system/status") return ok(systemStatusBody(isLocalhost, authMode));
|
||||
if (path === "/api/v1/notification-destinations") return ok([]);
|
||||
if (path === "/api/v1/companies") return ok([]);
|
||||
if (path === "/api/v1/system/logs") return ok([]);
|
||||
if (path === "/api/v1/user-api-keys") return ok([]);
|
||||
if (path === "/api/v1/system/secrets") return ok([]);
|
||||
if (path === "/api/v1/auth/security-events") return ok([]);
|
||||
if (path === "/api/v1/admin/ip-bans") return ok([]);
|
||||
if (path === "/api/v1/admin/unban-requests") return ok([]);
|
||||
if (path === "/api/v1/auth/me" && init?.method === "DELETE") return ok(undefined, 204);
|
||||
return Promise.resolve({ ok: false, status: 404, json: async () => ({ detail: "not found" }) });
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
replaceMock.mockClear();
|
||||
});
|
||||
|
||||
describe("Settings - Delete account box", () => {
|
||||
it("renders for a regular (non-local-dev) user, disabled until a password is typed", async () => {
|
||||
vi.stubGlobal("fetch", mockFetchImplementation(false, "jwt", REGULAR_USER));
|
||||
renderWithQueryClient(<SettingsPage />);
|
||||
|
||||
const button = await screen.findByRole("button", { name: /delete account/i });
|
||||
expect(button).toBeDisabled();
|
||||
|
||||
const user = userEvent.setup();
|
||||
await user.type(screen.getByLabelText(/confirm your password/i), "correct-horse-1");
|
||||
expect(button).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it("is hidden entirely for the local-dev bypass account", async () => {
|
||||
vi.stubGlobal("fetch", mockFetchImplementation(true, "local", LOCAL_DEV_USER));
|
||||
renderWithQueryClient(<SettingsPage />);
|
||||
|
||||
await screen.findByText(LOCAL_DEV_USER.email);
|
||||
expect(screen.queryByRole("button", { name: /delete account/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("submits the password, then clears tokens and redirects home on success", async () => {
|
||||
const fetchMock = vi.fn().mockImplementation((url: string, init?: RequestInit) => {
|
||||
const path = url.replace("http://localhost:8000", "");
|
||||
if (path === "/api/v1/auth/me" && init?.method === "DELETE") {
|
||||
expect(JSON.parse(init.body as string)).toEqual({ password: "correct-horse-1" });
|
||||
return Promise.resolve({ ok: true, status: 204, json: async () => undefined });
|
||||
}
|
||||
return mockFetchImplementation(false, "jwt", REGULAR_USER)(url, init);
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const user = userEvent.setup();
|
||||
renderWithQueryClient(<SettingsPage />);
|
||||
|
||||
const button = await screen.findByRole("button", { name: /delete account/i });
|
||||
await user.type(screen.getByLabelText(/confirm your password/i), "correct-horse-1");
|
||||
await user.click(button);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(replaceMock).toHaveBeenCalledWith("/");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows an error message when the password is wrong", async () => {
|
||||
const fetchMock = vi.fn().mockImplementation((url: string, init?: RequestInit) => {
|
||||
const path = url.replace("http://localhost:8000", "");
|
||||
if (path === "/api/v1/auth/me" && init?.method === "DELETE") {
|
||||
return Promise.resolve({
|
||||
ok: false,
|
||||
status: 401,
|
||||
json: async () => ({ detail: "Incorrect password" }),
|
||||
});
|
||||
}
|
||||
return mockFetchImplementation(false, "jwt", REGULAR_USER)(url, init);
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const user = userEvent.setup();
|
||||
renderWithQueryClient(<SettingsPage />);
|
||||
|
||||
const button = await screen.findByRole("button", { name: /delete account/i });
|
||||
await user.type(screen.getByLabelText(/confirm your password/i), "wrong-password");
|
||||
await user.click(button);
|
||||
|
||||
expect(await screen.findByText(/incorrect password/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user