Kundenkonten löschen (Admin und selbst), Menü-Zähler mit eigenem Cookie je Bereich
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SvuGvHpbAQ4syfuLuRvutL
This commit is contained in:
parent
813f6e3cc9
commit
39eea12b47
12 changed files with 156 additions and 31 deletions
|
|
@ -1,9 +1,11 @@
|
|||
"use server";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db";
|
||||
import { subscribe, unsubscribe } from "@/lib/newsletter";
|
||||
import { getCurrentUser, hashPassword, verifyPassword } from "@/lib/auth";
|
||||
import { audit, destroySession, getCurrentUser, hashPassword, verifyPassword } from "@/lib/auth";
|
||||
import { deleteCustomerAccount, maskEmail } from "@/lib/customer-delete";
|
||||
import { COUNTRIES } from "@/lib/settings";
|
||||
|
||||
export type AccountState = { ok?: string; error?: string; errors?: Record<string, string>; values?: Record<string, string> } | null;
|
||||
|
|
@ -47,6 +49,23 @@ export async function changePassword(_prev: AccountState, fd: FormData): Promise
|
|||
return { ok: user.passwordHash ? "Dein Passwort ist geändert." : "Dein Passwort ist gesetzt. Du kannst dich jetzt auch mit E-Mail und Passwort anmelden." };
|
||||
}
|
||||
|
||||
/** Kunde löscht sein eigenes Konto. Bestätigung mit Passwort, bei reinen Google-/Apple-Konten mit der E-Mail-Adresse. */
|
||||
export async function deleteAccount(_prev: AccountState, fd: FormData): Promise<AccountState> {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) return { error: "Bitte melde dich erneut an." };
|
||||
if (user.role) return { error: "Team-Konten können hier nicht gelöscht werden." };
|
||||
const confirmation = String(fd.get("confirm") ?? "");
|
||||
if (user.passwordHash) {
|
||||
if (!(await verifyPassword(confirmation, user.passwordHash))) return { errors: { confirm: "Das Passwort stimmt nicht." } };
|
||||
} else if (confirmation.trim().toLowerCase() !== user.email.toLowerCase()) {
|
||||
return { errors: { confirm: "Bitte gib genau deine E-Mail-Adresse ein." } };
|
||||
}
|
||||
await destroySession();
|
||||
await deleteCustomerAccount(user.id);
|
||||
await audit(null, "Kunde hat sein Konto gelöscht", maskEmail(user.email));
|
||||
redirect("/konto/geloescht");
|
||||
}
|
||||
|
||||
const addressSchema = z.object({
|
||||
firstName: z.string().trim().min(1, "Bitte gib den Vornamen ein.").max(80),
|
||||
lastName: z.string().trim().min(1, "Bitte gib den Nachnamen ein.").max(80),
|
||||
|
|
|
|||
15
src/app/(shop)/konto/geloescht/page.tsx
Normal file
15
src/app/(shop)/konto/geloescht/page.tsx
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import Link from "next/link";
|
||||
|
||||
export const metadata = { title: "Konto gelöscht", robots: { index: false } };
|
||||
|
||||
export default function AccountDeleted() {
|
||||
return (
|
||||
<main className="sm-container sm-page">
|
||||
<div className="sm-auth" style={{ textAlign: "center" }}>
|
||||
<h1 className="display-lg sm-page__title">Dein Konto ist gelöscht.</h1>
|
||||
<p className="body sm-page__lead">Deine persönlichen Daten sind entfernt. Rechnungen zu früheren Bestellungen bewahren wir nur so lange auf, wie das Gesetz es verlangt.</p>
|
||||
<Link className="sm-btn sm-btn--primary" href="/shop">Zum Shop</Link>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
|
@ -2,7 +2,7 @@ import { redirect } from "next/navigation";
|
|||
import { db } from "@/lib/db";
|
||||
import { getCurrentUser } from "@/lib/auth";
|
||||
import { AccountShell } from "@/components/shop/account/AccountShell";
|
||||
import { PasswordForm, ProfileForm } from "@/components/shop/account/ProfileForms";
|
||||
import { DeleteAccountForm, PasswordForm, ProfileForm } from "@/components/shop/account/ProfileForms";
|
||||
|
||||
export const metadata = { title: "Profil & Sicherheit" };
|
||||
|
||||
|
|
@ -28,6 +28,13 @@ export default async function ProfilePage() {
|
|||
)}
|
||||
<PasswordForm hasPassword={Boolean(user.passwordHash)} />
|
||||
</section>
|
||||
{!user.role && (
|
||||
<section className="sm-box sm-account__panel">
|
||||
<h2 className="display-sm">Konto löschen</h2>
|
||||
<p className="body sm-muted">Dein Konto, dein Adressbuch und deine Newsletter-Anmeldung werden endgültig entfernt. Rechnungen zu deinen Bestellungen müssen wir gesetzlich aufbewahren, sie sind danach aber keinem Konto mehr zugeordnet.</p>
|
||||
<DeleteAccountForm hasPassword={Boolean(user.passwordHash)} email={user.email} />
|
||||
</section>
|
||||
)}
|
||||
</AccountShell>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,9 +5,9 @@ import { can, requireAdmin } from "@/lib/auth";
|
|||
import { formatPrice } from "@/lib/money";
|
||||
import { ORDER_STATUS, dateFmt } from "@/lib/status";
|
||||
import { Field } from "@/components/Field";
|
||||
import { AdminForm } from "@/components/admin/AdminForm";
|
||||
import { AdminForm, ConfirmButton } from "@/components/admin/AdminForm";
|
||||
import { Card, PageHead, Pill } from "@/components/admin/ui";
|
||||
import { saveCustomer } from "../actions";
|
||||
import { deleteCustomer, saveCustomer } from "../actions";
|
||||
|
||||
export default async function CustomerDetail({ params }: { params: Promise<{ id: string }> }) {
|
||||
const user = await requireAdmin("customers.view");
|
||||
|
|
@ -49,6 +49,18 @@ export default async function CustomerDetail({ params }: { params: Promise<{ id:
|
|||
)}
|
||||
</Card>
|
||||
</div>
|
||||
{can(user, "customers.delete") && (() => {
|
||||
const open = c.orders.filter((o) => ["PENDING", "PAID", "PROCESSING"].includes(o.status)).length;
|
||||
return (
|
||||
<Card title="Kundenkonto löschen">
|
||||
<p className="body-sm ad-muted" style={{ marginTop: 0 }}>
|
||||
Entfernt Konto, Anmeldedaten, Adressbuch und Newsletter-Anmeldung endgültig. Bestellungen und Rechnungen bleiben wegen der gesetzlichen Aufbewahrungspflicht erhalten, sind danach aber keinem Konto mehr zugeordnet.
|
||||
{open > 0 && <strong> Achtung: {open === 1 ? "1 Bestellung ist" : `${open} Bestellungen sind`} noch offen.</strong>}
|
||||
</p>
|
||||
<ConfirmButton action={deleteCustomer} hidden={{ id: c.id }} confirm="Konto endgültig löschen?" className="sm-btn sm-btn--secondary sm-btn--sm">Kundenkonto löschen</ConfirmButton>
|
||||
</Card>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
"use server";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { db } from "@/lib/db";
|
||||
import { assertPermission, audit } from "@/lib/auth";
|
||||
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
||||
import { deleteCustomerAccount, maskEmail } from "@/lib/customer-delete";
|
||||
|
||||
export async function saveCustomer(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||
const user = await assertPermission("customers.edit");
|
||||
|
|
@ -25,3 +27,11 @@ export async function saveCustomer(_prev: ActionResult, fd: FormData): Promise<A
|
|||
revalidatePath(`/admin/kunden/${id}`);
|
||||
return ok();
|
||||
}
|
||||
|
||||
export async function deleteCustomer(fd: FormData) {
|
||||
const user = await assertPermission("customers.delete");
|
||||
const done = await deleteCustomerAccount(String(fd.get("id")));
|
||||
if (done) await audit(user, "Kundenkonto gelöscht", maskEmail(done.email));
|
||||
revalidatePath("/admin/kunden");
|
||||
redirect("/admin/kunden");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import { AdminNav } from "@/components/admin/AdminNav";
|
|||
import { MobileAdminNav } from "@/components/admin/MobileAdminNav";
|
||||
import { ADMIN_NAV } from "@/components/admin/nav";
|
||||
import { AdminBadgesProvider } from "@/components/admin/AdminBadges";
|
||||
import { SEEN_COOKIE, SEEN_SECTIONS, getBadges } from "@/lib/admin-badges";
|
||||
import { SEEN_SECTIONS, getBadges, readSeen } from "@/lib/admin-badges";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const metadata = { title: "Admin", robots: { index: false } };
|
||||
|
|
@ -19,7 +19,7 @@ export default async function AdminLayout({ children }: { children: React.ReactN
|
|||
const user = await requireAdmin();
|
||||
const settings = await getSettings();
|
||||
const groups = ADMIN_NAV.map((g) => ({ ...g, items: g.items.filter((i) => can(user, i.permission)) })).filter((g) => g.items.length);
|
||||
const badges = await getBadges(user, (await cookies()).get(SEEN_COOKIE)?.value);
|
||||
const badges = await getBadges(user, readSeen(await cookies()));
|
||||
const nav = <AdminNav groups={groups} />;
|
||||
const foot = (
|
||||
<div className="ad-side__foot">
|
||||
|
|
|
|||
|
|
@ -1,12 +1,21 @@
|
|||
import { cookies } from "next/headers";
|
||||
import { getCurrentUser } from "@/lib/auth";
|
||||
import { SEEN_COOKIE, getBadges } from "@/lib/admin-badges";
|
||||
import { SEEN_SECTIONS, getBadges, readSeen, seenCookieName } from "@/lib/admin-badges";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET() {
|
||||
type Section = keyof typeof SEEN_SECTIONS;
|
||||
|
||||
/** Zähler fürs Menü. `?seen=newCustomers` merkt den Besuch eines Bereichs (mit Serverzeit) und setzt dessen Zähler zurück. */
|
||||
export async function GET(req: Request) {
|
||||
const user = await getCurrentUser();
|
||||
if (!user?.role) return Response.json({}, { status: 401 });
|
||||
const badges = await getBadges(user, (await cookies()).get(SEEN_COOKIE)?.value);
|
||||
const jar = await cookies();
|
||||
const visited = (new URL(req.url).searchParams.get("seen") ?? "").split(",").filter((k): k is Section => k in SEEN_SECTIONS);
|
||||
const now = Date.now();
|
||||
for (const k of visited) jar.set(seenCookieName(k), String(now), { path: "/admin", maxAge: 31536000, sameSite: "lax", httpOnly: true });
|
||||
const seen = readSeen(jar);
|
||||
for (const k of visited) seen[k] = now;
|
||||
const badges = await getBadges(user, seen);
|
||||
return Response.json(badges, { headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,38 +6,26 @@ type Badges = Record<string, number>;
|
|||
const Ctx = createContext<Badges>({});
|
||||
export const useBadges = () => useContext(Ctx);
|
||||
|
||||
const SEEN_COOKIE = "ad_seen";
|
||||
const REFRESH_MS = 60_000;
|
||||
|
||||
function markSeen(key: string) {
|
||||
const m = document.cookie.match(new RegExp(`(?:^|; )${SEEN_COOKIE}=([^;]*)`));
|
||||
let seen: Record<string, number> = {};
|
||||
try {
|
||||
seen = m ? JSON.parse(decodeURIComponent(m[1])) : {};
|
||||
} catch {}
|
||||
seen[key] = Date.now();
|
||||
document.cookie = `${SEEN_COOKIE}=${encodeURIComponent(JSON.stringify(seen))}; path=/admin; max-age=31536000; samesite=lax`;
|
||||
}
|
||||
|
||||
// Hält die Zähler in der Navigation aktuell: beim Seitenwechsel und jede Minute
|
||||
export function AdminBadgesProvider({ initial, seenSections, children }: { initial: Badges; seenSections: Record<string, string>; children: React.ReactNode }) {
|
||||
const [badges, setBadges] = useState(initial);
|
||||
const pathname = usePathname();
|
||||
const refresh = useCallback(async () => {
|
||||
const refresh = useCallback(async (seen: string[] = []) => {
|
||||
try {
|
||||
const res = await fetch("/admin/badges", { cache: "no-store" });
|
||||
const res = await fetch(`/admin/badges${seen.length ? `?seen=${seen.join(",")}` : ""}`, { cache: "no-store" });
|
||||
if (res.ok) setBadges(await res.json());
|
||||
} catch {}
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
for (const [key, href] of Object.entries(seenSections)) {
|
||||
if (pathname === href || pathname.startsWith(href + "/")) markSeen(key);
|
||||
}
|
||||
void refresh();
|
||||
// Besuchten Bereich beim Server als gelesen melden; der setzt dafür ein eigenes Cookie
|
||||
const seen = Object.entries(seenSections).filter(([, href]) => pathname === href || pathname.startsWith(href + "/")).map(([key]) => key);
|
||||
void refresh(seen);
|
||||
}, [pathname, refresh, seenSections]);
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => document.visibilityState === "visible" && refresh(), REFRESH_MS);
|
||||
const onVis = () => document.visibilityState === "visible" && refresh();
|
||||
const onVis = () => document.visibilityState === "visible" && void refresh();
|
||||
document.addEventListener("visibilitychange", onVis);
|
||||
return () => {
|
||||
clearInterval(id);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
"use client";
|
||||
import { useActionState } from "react";
|
||||
import { changePassword, updateProfile } from "@/app/(shop)/konto/actions";
|
||||
import { useActionState, useState } from "react";
|
||||
import { changePassword, deleteAccount, updateProfile } from "@/app/(shop)/konto/actions";
|
||||
import { Field } from "../../Field";
|
||||
import { Alert } from "../Blocks";
|
||||
|
||||
|
|
@ -47,3 +47,29 @@ export function PasswordForm({ hasPassword }: { hasPassword: boolean }) {
|
|||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export function DeleteAccountForm({ hasPassword, email }: { hasPassword: boolean; email: string }) {
|
||||
const [state, action, pending] = useActionState(deleteAccount, null);
|
||||
const [open, setOpen] = useState(false);
|
||||
if (!open) {
|
||||
return (
|
||||
<div className="sm-account__actions" style={{ justifyContent: "flex-start" }}>
|
||||
<button className="sm-btn sm-btn--secondary" type="button" onClick={() => setOpen(true)}>Konto löschen …</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<form action={action} noValidate>
|
||||
{state?.error && <div className="sm-account__alert"><Alert kind="danger" title={state.error} /></div>}
|
||||
{hasPassword ? (
|
||||
<Field label="Zur Bestätigung dein Passwort" name="confirm" type="password" autoComplete="current-password" error={state?.errors?.confirm} required />
|
||||
) : (
|
||||
<Field label={`Zur Bestätigung deine E-Mail-Adresse (${email})`} name="confirm" type="email" autoComplete="off" error={state?.errors?.confirm} required />
|
||||
)}
|
||||
<div className="sm-account__actions">
|
||||
<button className="sm-btn sm-btn--secondary" type="button" onClick={() => setOpen(false)}>Abbrechen</button>
|
||||
<button className="sm-btn sm-btn--primary" type="submit" disabled={pending} style={{ background: "var(--danger)", borderColor: "var(--danger)" }}>{pending ? "Löscht …" : "Konto endgültig löschen"}</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,9 @@ import type { BadgeKey } from "@/components/admin/nav";
|
|||
export type { BadgeKey };
|
||||
export type Badges = Partial<Record<BadgeKey, number>>;
|
||||
|
||||
// Früher ein gemeinsames JSON-Cookie; jetzt ein Cookie je Bereich, gesetzt vom Server mit Serverzeit
|
||||
export const SEEN_COOKIE = "ad_seen";
|
||||
export const seenCookieName = (k: keyof typeof SEEN_SECTIONS) => `ad_seen_${k}`;
|
||||
// Bereiche, deren Zähler nach dem Besuch zurückgesetzt wird
|
||||
export const SEEN_SECTIONS = { newCustomers: "/admin/kunden", newSubscribers: "/admin/newsletter" } as const;
|
||||
|
||||
|
|
@ -24,8 +26,20 @@ export function parseSeen(raw: string | undefined): Partial<Record<keyof typeof
|
|||
}
|
||||
}
|
||||
|
||||
export async function getBadges(user: CurrentUser, seenRaw: string | undefined): Promise<Badges> {
|
||||
const seen = parseSeen(seenRaw);
|
||||
type CookieJar = { get(name: string): { value: string } | undefined };
|
||||
|
||||
/** Zeitpunkte des letzten Besuchs je Bereich. Ein Cookie je Bereich, damit sich die Bereiche nie gegenseitig überschreiben. */
|
||||
export function readSeen(jar: CookieJar) {
|
||||
const legacy = parseSeen(jar.get(SEEN_COOKIE)?.value);
|
||||
const seen: Partial<Record<keyof typeof SEEN_SECTIONS, number>> = {};
|
||||
for (const k of Object.keys(SEEN_SECTIONS) as (keyof typeof SEEN_SECTIONS)[]) {
|
||||
const v = Number(jar.get(seenCookieName(k))?.value);
|
||||
seen[k] = Number.isFinite(v) && v > 0 ? v : legacy[k];
|
||||
}
|
||||
return seen;
|
||||
}
|
||||
|
||||
export async function getBadges(user: CurrentUser, seen: Partial<Record<keyof typeof SEEN_SECTIONS, number>>): Promise<Badges> {
|
||||
// Ohne Besuch zählen die letzten 7 Tage als neu
|
||||
const since = (k: keyof typeof SEEN_SECTIONS) => new Date(seen[k] ?? Date.now() - 7 * 86400000);
|
||||
const [openOrders, newCustomers, newSubscribers, lowStock] = await Promise.all([
|
||||
|
|
|
|||
24
src/lib/customer-delete.ts
Normal file
24
src/lib/customer-delete.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import "server-only";
|
||||
import { db } from "./db";
|
||||
import { unsubscribe } from "./newsletter";
|
||||
|
||||
/** "anna.muster@web.de" → "an***@web.de", damit im Protokoll keine vollständige Adresse bleibt. */
|
||||
export function maskEmail(email: string) {
|
||||
const [name, domain = ""] = email.split("@");
|
||||
return `${name.slice(0, 2)}***@${domain}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Löscht ein Kundenkonto mit allen persönlichen Daten (Anmeldungen, Adressbuch, Newsletter, Mail-Protokoll).
|
||||
* Bestellungen und Rechnungen bleiben wegen der Aufbewahrungspflicht erhalten, nur ohne Verknüpfung zum Konto.
|
||||
*/
|
||||
export async function deleteCustomerAccount(id: string) {
|
||||
const user = await db.user.findUnique({ where: { id } });
|
||||
if (!user || user.roleId) return null;
|
||||
await unsubscribe(user.email);
|
||||
// Mails ohne Bestellbezug (z. B. Passwort vergessen) sind nicht aufbewahrungspflichtig
|
||||
await db.emailLog.deleteMany({ where: { to: user.email, orderId: null } });
|
||||
// Sitzungen, Social-Logins, Reset-Links und Adressen hängen per Cascade am Konto
|
||||
await db.user.delete({ where: { id } });
|
||||
return { email: user.email };
|
||||
}
|
||||
|
|
@ -27,6 +27,7 @@ export const PERMISSION_GROUPS = [
|
|||
permissions: [
|
||||
{ key: "customers.view", label: "Kunden ansehen" },
|
||||
{ key: "customers.edit", label: "Kunden bearbeiten" },
|
||||
{ key: "customers.delete", label: "Kundenkonten löschen" },
|
||||
{ key: "coupons.edit", label: "Gutscheine und Sales verwalten" },
|
||||
{ key: "newsletter.view", label: "Newsletter-Anmeldungen ansehen" },
|
||||
],
|
||||
|
|
|
|||
Loading…
Reference in a new issue