feat(account): GDPR-compliant account deletion

Users could register but had no way to leave — a real GDPR Article 17
gap and a trust issue. Now end-to-end:

- DELETE /api/account: requires session + double confirmation (current
  password + literal "DELETE" string in the body). OAuth accounts skip
  the password check (no local password to verify). Single db.delete()
  cascades through every users.id FK that already had ON DELETE CASCADE
  — pets, health metrics, vaccinations, medications, records, bookings,
  reviews, orders, products listed, adoption listings/applications,
  signal history, email queue. (loggedBy on healthMetrics has no
  cascade rule but is unreachable in single-actor flows; noted as a
  latent issue if multi-user logging ships later.)
- Settings page: red-bordered "Danger zone" card with explicit copy
  about what gets deleted. Delete button opens a confirmation modal
  requiring both the password and typing DELETE; submit button stays
  disabled until both are filled. On success, signOut redirects to
  /en home (account is gone — can't bounce them to dashboard).
- 6 tests: auth gate, missing/wrong confirm string, missing password
  for credentials accounts, wrong password, OAuth bypass of password
  check, success path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
g-butandClaude Opus 4.7 committed 2026-04-26 09:56:33 +02:00
1 parent 6a3d806ffd
commit 0ce5192b77
3 files changed
+257 -3

No files matched your search

+133 -2
View File
@@ -1,9 +1,9 @@
"use client";
import { useState, useTransition, useEffect } from "react";
import { useSession } from "next-auth/react";
import { useSession, signOut } from "next-auth/react";
import { useRouter } from "next/navigation";
import { User, Lock, CheckCircle, Mail } from "lucide-react";
import { User, Lock, CheckCircle, Mail, AlertTriangle, X } from "lucide-react";
import { PASSWORD_MIN_LENGTH } from "@/lib/config/auth";
import { PasswordInput } from "@/components/portal/PasswordInput";
import { userRoleLabel } from "@/lib/config/users";
@@ -104,6 +104,39 @@ export default function SettingsPage() {
}
}
/* ── Account deletion section ────────────────────────────────────────── */
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [deletePw, setDeletePw] = useState("");
const [deleteConfirm, setDeleteConfirm] = useState("");
const [deleting, setDeleting] = useState(false);
const [deleteErr, setDeleteErr] = useState("");
function openDeleteModal() {
setDeletePw("");
setDeleteConfirm("");
setDeleteErr("");
setShowDeleteModal(true);
}
async function deleteAccount(e: React.FormEvent) {
e.preventDefault();
setDeleteErr("");
setDeleting(true);
const res = await fetch("/api/account", {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ currentPassword: deletePw, confirm: deleteConfirm }),
});
const data = await res.json();
if (!data.success) {
setDeleting(false);
setDeleteErr(data.error ?? "Deletion failed.");
return;
}
// Account is gone — sign out and land on the marketing home in default locale.
await signOut({ callbackUrl: "/en" });
}
if (!session) return null;
return (
@@ -277,6 +310,104 @@ export default function SettingsPage() {
</button>
</form>
</div>
{/* ── Danger zone ─────────────────────────────────────────────── */}
<div className="card p-6 border-[var(--danger)]">
<div className="flex items-center gap-2 mb-3">
<div className="w-8 h-8 rounded-lg bg-[var(--danger-bg)] flex items-center justify-center">
<AlertTriangle className="w-4 h-4 text-[var(--danger-text)]" />
</div>
<h2 className="font-semibold text-[var(--danger-text)]">Danger zone</h2>
</div>
<p className="text-sm text-[var(--muted)] mb-4">
Deleting your account permanently removes your profile and all related
data — pets, health logs, vaccinations, records, bookings, orders,
listings, and adoption applications. This cannot be undone.
</p>
<button
type="button"
onClick={openDeleteModal}
className="text-sm font-medium px-4 py-2 rounded-lg border border-[var(--danger)] text-[var(--danger-text)] hover:bg-[var(--danger-bg)] transition-colors"
>
Delete my account
</button>
</div>
{/* ── Delete confirmation modal ───────────────────────────────── */}
{showDeleteModal && (
<div
className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4"
onClick={(e) => e.target === e.currentTarget && setShowDeleteModal(false)}
>
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold text-[var(--danger-text)] flex items-center gap-2">
<AlertTriangle className="w-5 h-5" /> Delete account?
</h3>
<button
onClick={() => setShowDeleteModal(false)}
className="p-1.5 rounded-lg hover:bg-[var(--off)] transition-colors"
aria-label="Close"
>
<X className="w-4 h-4" />
</button>
</div>
<p className="text-sm text-[var(--ink2)] mb-4 leading-relaxed">
This permanently deletes your account, all your pets, health
records, orders, listings, and applications. <strong>This cannot
be undone.</strong>
</p>
<form onSubmit={deleteAccount} className="space-y-4">
<div>
<label className="block text-sm font-medium text-[var(--ink2)] mb-1.5">
Current password
</label>
<PasswordInput
value={deletePw}
onChange={setDeletePw}
autoComplete="current-password"
required
placeholder="Confirm your password"
/>
</div>
<div>
<label className="block text-sm font-medium text-[var(--ink2)] mb-1.5">
Type <span className="font-mono text-[var(--danger-text)]">DELETE</span> to confirm
</label>
<input
className="form-input"
value={deleteConfirm}
onChange={(e) => setDeleteConfirm(e.target.value)}
placeholder="DELETE"
required
/>
</div>
{deleteErr && <p className="alert-error">{deleteErr}</p>}
<div className="flex justify-end gap-3 pt-2">
<button
type="button"
onClick={() => setShowDeleteModal(false)}
className="btn-outline"
disabled={deleting}
>
Cancel
</button>
<button
type="submit"
disabled={deleting || deleteConfirm !== "DELETE" || !deletePw}
className="text-sm font-medium px-4 py-2 rounded-lg bg-[var(--danger)] text-white hover:bg-red-700 disabled:opacity-60 transition-colors"
>
{deleting ? "Deleting…" : "Delete forever"}
</button>
</div>
</form>
</div>
</div>
)}
</div>
);
}
+72 -1
View File
@@ -18,7 +18,7 @@ vi.mock("bcryptjs", () => ({
/* ─── Imports after mocks ──────────────────────────────────────────────────── */
import { POST, PATCH } from "./route";
import { POST, PATCH, DELETE } from "./route";
import { requireSession } from "@/lib/auth/guards";
import { getInstance } from "@/lib/db";
import bcrypt from "bcryptjs";
@@ -56,6 +56,14 @@ function makePatchRequest(body: unknown) {
});
}
function makeDeleteRequest(body: unknown) {
return new NextRequest("http://localhost/api/account", {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
}
const VALID_REGISTER = { email: "new@example.com", password: "securepass123" };
/* ─── POST (registration) tests ────────────────────────────────────────────── */
@@ -210,3 +218,66 @@ describe("PATCH /api/account", () => {
expect(body.success).toBe(true);
});
});
describe("DELETE /api/account", () => {
let db: ReturnType<typeof makeMockDb>;
beforeEach(() => {
vi.clearAllMocks();
db = makeMockDb();
vi.mocked(getInstance).mockReturnValue(db as any);
vi.mocked(requireSession).mockResolvedValue({ session: OWNER_SESSION as any, error: null });
});
it("returns 401 when not authenticated", async () => {
vi.mocked(requireSession).mockResolvedValueOnce({
session: null as any,
error: NextResponse.json({ success: false, error: "Unauthorized" }, { status: 401 }),
});
const res = await DELETE(makeDeleteRequest({ confirm: "DELETE", currentPassword: "x" }));
expect(res.status).toBe(401);
});
it("returns 400 when confirm field is missing or wrong", async () => {
const res1 = await DELETE(makeDeleteRequest({ currentPassword: "x" }));
expect(res1.status).toBe(400);
const res2 = await DELETE(makeDeleteRequest({ confirm: "delete", currentPassword: "x" })); // wrong case
expect(res2.status).toBe(400);
});
it("returns 400 when password is missing for credentials account", async () => {
db._queryFindFirst.mockResolvedValueOnce(MOCK_USER_WITH_PASSWORD);
const res = await DELETE(makeDeleteRequest({ confirm: "DELETE" }));
expect(res.status).toBe(400);
const body = await res.json();
expect(body.error).toMatch(/password is required/i);
});
it("returns 400 when current password is wrong", async () => {
vi.mocked(bcrypt.compare).mockResolvedValueOnce(false as never);
db._queryFindFirst.mockResolvedValueOnce(MOCK_USER_WITH_PASSWORD);
const res = await DELETE(makeDeleteRequest({ confirm: "DELETE", currentPassword: "wrong" }));
expect(res.status).toBe(400);
const body = await res.json();
expect(body.error).toMatch(/incorrect/i);
});
it("skips password check for OAuth accounts (no local password)", async () => {
db._queryFindFirst.mockResolvedValueOnce(MOCK_USER_OAUTH);
const res = await DELETE(makeDeleteRequest({ confirm: "DELETE" }));
expect(res.status).toBe(200);
expect(db.delete).toHaveBeenCalled();
expect(bcrypt.compare).not.toHaveBeenCalled();
});
it("deletes the user when password is correct and confirm matches", async () => {
vi.mocked(bcrypt.compare).mockResolvedValueOnce(true as never);
db._queryFindFirst.mockResolvedValueOnce(MOCK_USER_WITH_PASSWORD);
const res = await DELETE(makeDeleteRequest({ confirm: "DELETE", currentPassword: "securepass123" }));
expect(res.status).toBe(200);
const body = await res.json();
expect(body.success).toBe(true);
expect(db.delete).toHaveBeenCalled();
});
});
+52
View File
@@ -158,3 +158,55 @@ export async function PATCH(req: NextRequest) {
return NextResponse.json({ success: false, error: "Update failed" }, { status: 500 });
}
}
const deleteAccountSchema = z.object({
/** For credentials accounts: re-confirm the password before deletion. */
currentPassword: z.string().optional(),
/** Require typing the literal string "DELETE" to guard against accidental clicks. */
confirm: z.literal("DELETE"),
});
/** DELETE /api/account — permanently delete the user and all related data.
* GDPR right-to-erasure. Cascade FKs handle pets, health metrics, vaccinations,
* medications, records, bookings, reviews, orders, products listed by them,
* adoption listings/applications, signal history, and the email queue. */
export async function DELETE(req: NextRequest) {
const { session, error } = await requireSession();
if (error) return error;
const body = await req.json().catch(() => null);
const parsed = deleteAccountSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ success: false, error: "Type DELETE in the confirmation field" },
{ status: 400 },
);
}
const db = getInstance();
const user = await db.query.users.findFirst({ where: eq(users.id, session.user.id) });
if (!user) {
return NextResponse.json({ success: false, error: "Account not found" }, { status: 404 });
}
// For credentials accounts, require the current password as a re-auth check.
// OAuth accounts skip this since they have no local password.
if (user.password) {
if (!parsed.data.currentPassword) {
return NextResponse.json(
{ success: false, error: "Current password is required" },
{ status: 400 },
);
}
const valid = await bcrypt.compare(parsed.data.currentPassword, user.password);
if (!valid) {
return NextResponse.json(
{ success: false, error: "Current password is incorrect" },
{ status: 400 },
);
}
}
await db.delete(users).where(eq(users.id, session.user.id));
return NextResponse.json({ success: true });
}