Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 139 additions & 0 deletions apps/next/src/app/delete-account/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
"use client";

import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import posthog from "posthog-js";
import { type ReactNode, Suspense, useEffect, useState } from "react";
import { Button } from "@/components/ui/shadcn/button";
import { useSnackbarStore } from "@/context/useSnackbar";
import { getSignInUrl } from "@/lib/auth-actions";
import { SESSION_FRESH_AGE } from "@/lib/auth-constants";
import { Provider } from "@/lib/auth-types";
import { authClient, signOut, useSession } from "@/utils/auth-client";

export default function DeleteAccountPage() {
return (
<Suspense>
<DeleteAccount />
</Suspense>
);
}

function DeleteAccount() {
const router = useRouter();
const searchParams = useSearchParams();
const { data: session, isPending } = useSession();
const { showSnackbar } = useSnackbarStore();
const [isWorking, setIsWorking] = useState(false);
const [isDeleted, setIsDeleted] = useState(false);
const [error, setError] = useState<string | null>(null);

useEffect(() => {
if (isPending || isWorking) return;

if (!session) {
showSnackbar("Login to delete your account!", "error");
router.push("/");
}
}, [session, isPending, isWorking, router, showSnackbar]);

const handleSignInAgain = async () => {
setError(null);
setIsWorking(true);
try {
const { data: accounts } = await authClient.listAccounts();
const provider = accounts?.[0]?.accountId.startsWith("apple_")
? Provider.Apple
: Provider.Google;
window.location.href = await getSignInUrl(provider, {
returnUrl: "/delete-account?step=confirm",
// Skips auth.icssc.club's saved session so the user really signs in.
authorizationUrlParams: { prompt: "consent" },
});
} catch (signInError) {
console.error("Error signing in again", signInError);
posthog.captureException(signInError);
setError("Couldn't start sign-in. Please try again.");
setIsWorking(false);
}
};

const handleDelete = async () => {
setError(null);
setIsWorking(true);
const { error: deleteError } = await authClient.deleteUser();
if (deleteError) {
console.error("Error deleting account", deleteError);
setError("Couldn't delete your account. Please try again.");
setIsWorking(false);
return;
}

setIsDeleted(true);
window.alert("Your account has been deleted.");
await signOut();
};

if (isPending || (!session && !isDeleted)) return null;

// Only offer deletion right after signing in again from this page.
const isConfirmStep =
searchParams.get("step") === "confirm" &&
!!session &&
Date.now() - new Date(session.session.createdAt).getTime() <
SESSION_FRESH_AGE * 1000;

let content: ReactNode;
if (isDeleted) {
content = <p>Your account has been deleted.</p>;
} else if (!isConfirmStep) {
content = (
<>
<p>To delete your account, sign in again to confirm it&apos;s you.</p>
<Button onClick={handleSignInAgain} disabled={isWorking}>
Sign In Again
</Button>
<Button asChild variant="outline">
<Link href="/">Cancel</Link>
</Button>
</>
);
} else {
content = (
<>
<p>
This permanently deletes the PeterPlate account for{" "}
<span className="font-semibold">{session?.user.email}</span>,
including your ratings, favorites, logged meals, and preferences. This
can&apos;t be undone.
</p>
<Button
variant="destructive"
onClick={handleDelete}
disabled={isWorking}
>
Delete Account
</Button>
<Button asChild variant="outline">
<Link href="/">Cancel</Link>
</Button>
</>
);
}

return (
<div className="flex justify-center px-4 py-12">
<div className="flex w-full max-w-md flex-col gap-4 rounded-2xl border border-gray-300 bg-white p-6 text-gray-900 dark:border-zinc-700 dark:bg-[var(--surface-elevated)] dark:text-zinc-200">
<h1 className="text-2xl font-bold text-sky-700 dark:text-blue-300">
Delete Account
</h1>
{content}
{error && (
<p className="text-sm text-destructive" role="alert">
{error}
</p>
)}
</div>
</div>
);
}
18 changes: 17 additions & 1 deletion apps/next/src/components/ui/sidebar/sidebar-content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import {
Close as CloseIcon,
DarkMode as DarkModeIcon,
DeleteOutline as DeleteIcon,
DesktopWindows as DesktopWindowsIcon,
Edit as EditIcon,
ContentPaste as FeedbackIcon,
Expand Down Expand Up @@ -232,6 +233,19 @@ export default function SidebarContent({
>
About PeterPlate
</MenuLink>

{user && (
<MenuLink
href="/delete-account"
onClick={onClose}
icon={
<DeleteIcon fontSize="small" sx={{ color: "error.main" }} />
}
color="error.main"
>
Delete Account
</MenuLink>
)}
</div>
</div>

Expand Down Expand Up @@ -289,11 +303,13 @@ function MenuLink({
href,
onClick,
icon,
color = "text.primary",
children,
}: {
href: string;
onClick: () => void;
icon: ReactNode;
color?: string;
children: ReactNode;
}) {
return (
Expand All @@ -304,7 +320,7 @@ function MenuLink({
dark:hover:bg-gray-700`}
>
<Box sx={{ color: "primary.main" }}>{icon}</Box>
<Typography variant="body2" fontWeight={500} color="text.primary">
<Typography variant="body2" fontWeight={500} color={color}>
{children}
</Typography>
</Link>
Expand Down
3 changes: 3 additions & 0 deletions apps/next/src/lib/auth-constants.ts
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
export const AUTH_PROVIDER_ID = "icssc";

/** Seconds since sign-in during which a session can delete its account. */
export const SESSION_FRESH_AGE = 5 * 60;
9 changes: 8 additions & 1 deletion apps/next/src/lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { betterAuth } from "better-auth/minimal";
import { nextCookies } from "better-auth/next-js";
import { genericOAuth } from "better-auth/plugins";

import { AUTH_PROVIDER_ID } from "@/lib/auth-constants";
import { AUTH_PROVIDER_ID, SESSION_FRESH_AGE } from "@/lib/auth-constants";
import type { AuthAdditionalData } from "@/lib/auth-types";
import { getSafeAuthRedirectPath } from "@/lib/auth-utils";

Expand Down Expand Up @@ -41,8 +41,15 @@ export const auth = betterAuth({
enabled: true,
maxAge: 5 * 60,
},
// Account deletion requires a sign-in this recent.
freshAge: SESSION_FRESH_AGE,
},
user: {
deleteUser: {
enabled: true,
// TODO: When auth.icssc.club adds account deletion, call it from a
// beforeDelete hook to revoke Sign in with Apple tokens and end ICSSC sessions.
},
additionalFields: {
hasOnboarded: {
type: "boolean",
Expand Down
Loading