⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.
TypeScript bookmarkbookmark-managercollaborationnextjsreact-nativeread-it-laterself-hostedtypescript
implement account deletion functionality for non subscribed users
daniel31x13da1ea61de1cf
diff --git a/apps/mobile/app/subscribe.tsx b/apps/mobile/app/subscribe.tsxindex 43bd3a68..d060d576 100644--- a/apps/mobile/app/subscribe.tsx+++ b/apps/mobile/app/subscribe.tsx@@ -16,11 +16,13 @@ import {Bookmark,BookOpen,Check,+ ChevronDown,CircleHelp,Search,Sparkles,} from "lucide-react-native";import FontAwesome5 from "@expo/vector-icons/FontAwesome5";+import * as DropdownMenu from "zeego/dropdown-menu";import Purchases, { type PurchasesPackage } from "react-native-purchases";import { useEffect, useMemo, useState } from "react";import {@@ -308,14 +310,6 @@ export default function SubscribeScreen() {}};- const close = () => {- if (isForcedSubscribe) {- signOut();- } else {- router.replace("/(tabs)/dashboard");- }- };-return (<View className="flex-1 bg-zinc-100 dark:bg-zinc-900"><ScrollView@@ -490,15 +484,65 @@ export default function SubscribeScreen() {</TouchableOpacity></View>- <TouchableOpacity- activeOpacity={0.7}- className="self-center mt-3"- onPress={close}- >- <Text className="text-neutral text-center text-sm font-semibold">- {isForcedSubscribe ? "Sign out" : "Subscribe Later"}- </Text>- </TouchableOpacity>+ {isForcedSubscribe ? (+ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ <TouchableOpacity+ activeOpacity={0.7}+ className="self-center mt-3 flex-row items-center gap-1"+ >+ <Text className="text-neutral text-center text-sm font-semibold">+ Manage your account+ </Text>+ <ChevronDown size={15} color={theme["neutral"]} />+ </TouchableOpacity>+ </DropdownMenu.Trigger>++ <DropdownMenu.Content>+ {Platform.OS === "ios" /* Reverse order for iOS */ ? (+ <>+ <DropdownMenu.Item+ key="delete-account"+ destructive+ onSelect={() => SheetManager.show("delete-account-sheet")}+ >+ <DropdownMenu.ItemTitle>+ Delete account+ </DropdownMenu.ItemTitle>+ </DropdownMenu.Item>+ <DropdownMenu.Item key="sign-out" onSelect={() => signOut()}>+ <DropdownMenu.ItemTitle>Sign out</DropdownMenu.ItemTitle>+ </DropdownMenu.Item>+ </>+ ) : (+ <>+ <DropdownMenu.Item key="sign-out" onSelect={() => signOut()}>+ <DropdownMenu.ItemTitle>Sign out</DropdownMenu.ItemTitle>+ </DropdownMenu.Item>+ <DropdownMenu.Item+ key="delete-account"+ destructive+ onSelect={() => SheetManager.show("delete-account-sheet")}+ >+ <DropdownMenu.ItemTitle>+ Delete account+ </DropdownMenu.ItemTitle>+ </DropdownMenu.Item>+ </>+ )}+ </DropdownMenu.Content>+ </DropdownMenu.Root>+ ) : (+ <TouchableOpacity+ activeOpacity={0.7}+ className="self-center mt-3"+ onPress={() => router.replace("/(tabs)/dashboard")}+ >+ <Text className="text-neutral text-center text-sm font-semibold">+ Subscribe Later+ </Text>+ </TouchableOpacity>+ )}</SafeAreaView><TouchableOpacitydiff --git a/apps/mobile/components/ActionSheets/DeleteAccountSheet.tsx b/apps/mobile/components/ActionSheets/DeleteAccountSheet.tsxnew file mode 100644index 00000000..18dd5bff--- /dev/null+++ b/apps/mobile/components/ActionSheets/DeleteAccountSheet.tsx@@ -0,0 +1,206 @@+import { useRef, useState } from "react";+import { Alert, Text, TouchableOpacity, View } from "react-native";+import ActionSheet, {+ ActionSheetRef,+ SheetManager,+} from "react-native-actions-sheet";+import { useColorScheme } from "nativewind";+import { useSafeAreaInsets } from "react-native-safe-area-context";+import { useUser } from "@linkwarden/router/user";+import useAuthStore from "@/store/auth";+import { rawTheme, ThemeName } from "@/lib/colors";+import { Button } from "../ui/Button";+import Input from "../ui/Input";+import SheetHeader from "./SheetHeader";++const FEEDBACK_OPTIONS = [+ { value: "customer_service", label: "Customer Service" },+ { value: "low_quality", label: "Low Quality" },+ { value: "missing_features", label: "Missing Features" },+ { value: "switched_service", label: "Switched Service" },+ { value: "too_complex", label: "Too Complex" },+ { value: "too_expensive", label: "Too Expensive" },+ { value: "unused", label: "Unused" },+ { value: "other", label: "Other" },+];++export default function DeleteAccountSheet() {+ const actionSheetRef = useRef<ActionSheetRef>(null);+ const { colorScheme } = useColorScheme();+ const theme = rawTheme[colorScheme as ThemeName];+ const insets = useSafeAreaInsets();++ const { auth, signOut } = useAuthStore();+ const { data: user } = useUser(auth);++ const [password, setPassword] = useState("");+ const [feedback, setFeedback] = useState<string>();+ const [comment, setComment] = useState("");+ const [confirmation, setConfirmation] = useState("");+ const [loading, setLoading] = useState(false);++ const canDelete = user?.hasPassword+ ? password !== ""+ : confirmation.trim() === "confirm";++ const reset = () => {+ setPassword("");+ setFeedback(undefined);+ setComment("");+ setConfirmation("");+ setLoading(false);+ };++ const closeSheet = () => {+ actionSheetRef.current?.hide();+ };++ const handleDelete = async () => {+ if (!canDelete || loading || !user?.id || !auth.instance || !auth.session) {+ return;+ }++ setLoading(true);++ try {+ const response = await fetch(`${auth.instance}/api/v1/users/${user.id}`, {+ method: "DELETE",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${auth.session}`,+ },+ body: JSON.stringify({+ password,+ cancellation_details: { comment, feedback },+ }),+ });++ if (!response.ok) {+ const data = await response.json().catch(() => ({}));+ throw new Error(data?.response || "Could not delete your account.");+ }++ await SheetManager.hide("delete-account-sheet");+ await signOut();+ } catch (error: any) {+ Alert.alert(+ "Delete failed",+ error?.message || "Could not delete your account."+ );+ setLoading(false);+ }+ };++ return (+ <ActionSheet+ ref={actionSheetRef}+ gestureEnabled+ indicatorStyle={{ display: "none" }}+ containerStyle={{ backgroundColor: theme["base-100"] }}+ safeAreaInsets={insets}+ onClose={reset}+ >+ <SheetHeader+ title="Delete account"+ onClose={closeSheet}+ titleClassName="text-red-500"+ align="left"+ />++ <View className="px-8 pb-5">+ <Text className="text-base-content">+ This will permanently delete all the Links, Collections, Tags, and+ archived data you own. It will also log you out. This action is+ irreversible!+ </Text>++ <Text className="text-neutral text-sm mt-5 mb-2">+ Reason for cancellation (optional, but it really helps us improve!)+ </Text>+ <View className="flex-row flex-wrap gap-2">+ {FEEDBACK_OPTIONS.map((option) => {+ const isSelected = feedback === option.value;+ return (+ <TouchableOpacity+ key={option.value}+ activeOpacity={0.7}+ onPress={() =>+ setFeedback(isSelected ? undefined : option.value)+ }+ className="rounded-full border px-3 py-1.5"+ style={{+ borderColor: isSelected+ ? theme.accent+ : theme["neutral-content"],+ backgroundColor: isSelected ? theme.accent : "transparent",+ }}+ >+ <Text+ className="text-sm"+ style={{+ color: isSelected ? "#FFFFFF" : theme["base-content"],+ }}+ >+ {option.label}+ </Text>+ </TouchableOpacity>+ );+ })}+ </View>++ <Input+ placeholder="More information (optional)"+ placeholderTextColor={theme.neutral}+ className="mt-4 bg-base-200 min-h-20"+ multiline+ textAlignVertical="top"+ value={comment}+ onChangeText={setComment}+ />++ {user?.hasPassword ? (+ <>+ <Text className="text-base-content mt-5 mb-2">+ Confirm password+ </Text>+ <Input+ placeholder="Password"+ placeholderTextColor={theme.neutral}+ className="bg-base-200"+ secureTextEntry+ autoCapitalize="none"+ autoCorrect={false}+ value={password}+ onChangeText={setPassword}+ />+ </>+ ) : (+ <>+ <Text className="text-base-content mt-5 mb-2">+ Type "confirm" below to delete your account+ </Text>+ <Input+ placeholder="confirm"+ placeholderTextColor={theme.neutral}+ className="bg-base-200"+ autoCapitalize="none"+ autoCorrect={false}+ value={confirmation}+ onChangeText={setConfirmation}+ />+ </>+ )}++ <Button+ onPress={handleDelete}+ isLoading={loading}+ disabled={!canDelete}+ variant="destructive"+ className="mt-5"+ >+ <Text className="text-white font-semibold">Delete Your Account</Text>+ </Button>+ </View>+ </ActionSheet>+ );+}diff --git a/apps/mobile/components/ActionSheets/Sheets.tsx b/apps/mobile/components/ActionSheets/Sheets.tsxindex 95fa22ff..5c55c06f 100644--- a/apps/mobile/components/ActionSheets/Sheets.tsx+++ b/apps/mobile/components/ActionSheets/Sheets.tsx@@ -16,6 +16,7 @@ import ReaderSettingsSheet from "./ReaderSettingsSheet";import LoginSheet from "./LoginSheet";import SignUpSheet from "./SignUpSheet";import SelfHostedServerSheet from "./SelfHostedServerSheet";+import DeleteAccountSheet from "./DeleteAccountSheet";import { LinkIncludingShortenedCollectionAndTags } from "@linkwarden/types/global";registerSheet("support-sheet", SupportSheet);@@ -29,6 +30,7 @@ registerSheet("new-collection-sheet", NewCollectionSheet);registerSheet("readable-highlight-sheet", ReadableHighlightSheet);registerSheet("readable-highlights-sheet", ReadableHighlightsSheet);registerSheet("reader-settings-sheet", ReaderSettingsSheet);+registerSheet("delete-account-sheet", DeleteAccountSheet);declare module "react-native-actions-sheet" {interface Sheets {@@ -71,6 +73,7 @@ declare module "react-native-actions-sheet" {returnValue: number | null;}>;"reader-settings-sheet": SheetDefinition;+ "delete-account-sheet": SheetDefinition;}}diff --git a/apps/mobile/components/ui/Button.tsx b/apps/mobile/components/ui/Button.tsxindex b1c97e88..f15fb082 100644--- a/apps/mobile/components/ui/Button.tsx+++ b/apps/mobile/components/ui/Button.tsx@@ -17,7 +17,7 @@ const buttonVariants = cva(default: "bg-slate-500 text-white",primary: "bg-primary text-base-content",accent: "bg-accent border border-violet-400 text-white",- destructive: "bg-destructive text-white",+ destructive: "bg-error text-white",outline: "border border-base-content",secondary: "bg-secondary text-secondary-foreground",input:diff --git a/apps/web/components/ModalContent/DeleteOwnAccountModal.tsx b/apps/web/components/ModalContent/DeleteOwnAccountModal.tsxnew file mode 100644index 00000000..3eb7d6ac--- /dev/null+++ b/apps/web/components/ModalContent/DeleteOwnAccountModal.tsx@@ -0,0 +1,140 @@+import { useState } from "react";+import { toast } from "react-hot-toast";+import { signOut, useSession } from "next-auth/react";+import { useTranslation } from "next-i18next";+import { useUser } from "@linkwarden/router/user";+import Modal from "../Modal";+import TextInput from "@/components/TextInput";+import { Button } from "@/components/ui/button";+import { Separator } from "../ui/separator";++type Props = {+ onClose: Function;+};++export default function DeleteOwnAccountModal({ onClose }: Props) {+ const { t } = useTranslation();+ const { data } = useSession();+ const { data: user } = useUser();++ const [password, setPassword] = useState("");+ const [comment, setComment] = useState<string>();+ const [feedback, setFeedback] = useState<string>();+ const [confirmation, setConfirmation] = useState("");+ const [submitLoader, setSubmitLoader] = useState(false);++ const canDelete = user?.hasPassword+ ? password !== ""+ : confirmation.trim() === "confirm";++ const submit = async () => {+ if (!canDelete || submitLoader) return;++ setSubmitLoader(true);+ const load = toast.loading(t("deleting_message"));++ const response = await fetch(`/api/v1/users/${data?.user.id}`, {+ method: "DELETE",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ password,+ cancellation_details: {+ comment,+ feedback,+ },+ }),+ });++ const message = (await response.json()).response;++ toast.dismiss(load);++ if (response.ok) {+ signOut();+ } else {+ toast.error(message);+ setSubmitLoader(false);+ }+ };++ return (+ <Modal toggleModal={onClose}>+ <p className="text-xl font-thin text-red-500">{t("delete_account")}</p>++ <Separator className="my-3" />++ <div className="flex flex-col gap-3">+ <p>{t("delete_warning")}</p>++ <fieldset className="border rounded-md p-2 border-primary">+ <legend className="px-3 py-1 text-sm sm:text-base border rounded-md border-primary">+ <b>{t("optional")}</b> <i>{t("feedback_help")}</i>+ </legend>+ <label className="w-full flex min-[430px]:items-center items-start gap-2 mb-3 min-[430px]:flex-row flex-col">+ <p className="text-sm">{t("reason_for_cancellation")}:</p>+ <select+ className="rounded-md p-1 outline-none bg-base-100"+ value={feedback}+ onChange={(e) => setFeedback(e.target.value)}+ >+ <option value={undefined}>{t("please_specify")}</option>+ <option value="customer_service">{t("customer_service")}</option>+ <option value="low_quality">{t("low_quality")}</option>+ <option value="missing_features">{t("missing_features")}</option>+ <option value="switched_service">{t("switched_service")}</option>+ <option value="too_complex">{t("too_complex")}</option>+ <option value="too_expensive">{t("too_expensive")}</option>+ <option value="unused">{t("unused")}</option>+ <option value="other">{t("other")}</option>+ </select>+ </label>+ <div>+ <p className="text-sm mb-2">{t("more_information")}</p>+ <textarea+ value={comment}+ onChange={(e) => setComment(e.target.value)}+ placeholder={t("feedback_placeholder")}+ className="resize-none w-full rounded-md p-2 border-neutral-content bg-base-100 focus:border-sky-300 dark:focus:border-sky-600 border-solid border outline-none duration-100"+ />+ </div>+ </fieldset>++ {user?.hasPassword ? (+ <div>+ <p className="mb-2">{t("confirm_password")}</p>+ <TextInput+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ placeholder="••••••••••••••"+ className="bg-base-100"+ type="password"+ />+ </div>+ ) : (+ <div>+ <p className="mb-2">{t("type_confirm_to_delete")}</p>+ <TextInput+ value={confirmation}+ onChange={(e) => setConfirmation(e.target.value)}+ placeholder="confirm"+ className="bg-base-100"+ autoComplete="off"+ />+ </div>+ )}++ <Button+ className="ml-auto"+ variant="destructive"+ disabled={!canDelete || submitLoader}+ onClick={submit}+ >+ <i className="bi-trash text-xl" />+ {t("delete_your_account")}+ </Button>+ </div>+ </Modal>+ );+}diff --git a/apps/web/lib/api/controllers/users/userId/deleteUserById.ts b/apps/web/lib/api/controllers/users/userId/deleteUserById.tsindex b8afec6a..95c6ee0d 100644--- a/apps/web/lib/api/controllers/users/userId/deleteUserById.ts+++ b/apps/web/lib/api/controllers/users/userId/deleteUserById.ts@@ -11,7 +11,8 @@ export default async function deleteUserById(userId: number,body: DeleteUserBody,isServerAdmin: boolean,- queryId: number+ queryId: number,+ bypassPassword: boolean = false) {const user = await prisma.user.findUnique({where: { id: userId },@@ -38,24 +39,28 @@ export default async function deleteUserById(if (!isServerAdmin) {if (queryId === userId) {- if (user.password) {- const isPasswordValid = bcrypt.compareSync(- body.password,- user.password- );+ // Non-subscribers (only granted when billing is enabled) may delete their+ // own account without re-entering their password.+ if (!bypassPassword) {+ if (user.password) {+ const isPasswordValid = bcrypt.compareSync(+ body.password,+ user.password+ );- if (!isPasswordValid && !isServerAdmin) {+ if (!isPasswordValid) {+ return {+ response: "Invalid credentials.",+ status: 401,+ };+ }+ } else {return {- response: "Invalid credentials.",+ response:+ "User has no password. Please create one from the password settings page.",status: 401,};}- } else {- return {- response:- "User has no password. Please create one from the password settings page.",- status: 401,- };}} else {if (user.parentSubscriptionId) {@@ -136,18 +141,20 @@ export default async function deleteUserById(await removeFile({ filePath: `uploads/avatar/${queryId}.jpg` });- if (- process.env.STRIPE_SECRET_KEY &&- user.subscriptions?.provider === "STRIPE"- ) {- const stripe = stripeSDK();+ const billingEnabled =+ Boolean(process.env.STRIPE_SECRET_KEY) ||+ Boolean(+ process.env.REVENUECAT_PROJECT_ID && process.env.REVENUECAT_API_KEY+ );- // Send an email about cancellation reason if provided- if (- body.cancellation_details?.comment ||+ // Send an email about cancellation reason if provided+ if (+ billingEnabled &&+ (body.cancellation_details?.comment ||body.cancellation_details?.feedback ||- user.acceptPromotionalEmails- )+ user.acceptPromotionalEmails)+ ) {+ try {await transporter.sendMail({from: process.env.EMAIL_FROM,to: "[email protected]",@@ -158,6 +165,16 @@ export default async function deleteUserById(body.cancellation_details?.comment || "N/A"}\nPromotional Emails: ${String(user.acceptPromotionalEmails)}`,});+ } catch (err) {+ console.log(err);+ }+ }++ if (+ process.env.STRIPE_SECRET_KEY &&+ user.subscriptions?.provider === "STRIPE"+ ) {+ const stripe = stripeSDK();try {if (user.subscriptions?.id && queryId !== userId) {diff --git a/apps/web/pages/api/v1/users/[id]/index.ts b/apps/web/pages/api/v1/users/[id]/index.tsindex 7d404c5d..a827d381 100644--- a/apps/web/pages/api/v1/users/[id]/index.ts+++ b/apps/web/pages/api/v1/users/[id]/index.ts@@ -6,7 +6,9 @@ import { prisma } from "@linkwarden/prisma";import verifySubscription from "@/lib/api/billing/verifySubscription";import verifyToken from "@/lib/api/verifyToken";-const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;+const BILLING_ENABLED =+ Boolean(process.env.STRIPE_SECRET_KEY) ||+ Boolean(process.env.REVENUECAT_PROJECT_ID && process.env.REVENUECAT_API_KEY);export default async function users(req: NextApiRequest, res: NextApiResponse) {const token = await verifyToken({ req });@@ -40,7 +42,10 @@ export default async function users(req: NextApiRequest, res: NextApiResponse) {return res.status(users.status).json({ response: users.response });}- if (STRIPE_SECRET_KEY) {+ // Non-subscribers (when billing is enabled) are normally blocked below, but they are still allowed to delete their own account. The password check is only bypassed for accounts that don't have a password (e.g. SSO users).+ let bypassPasswordForDeletion = false;++ if (BILLING_ENABLED) {const user = await prisma.user.findUnique({where: {id: token.id,@@ -54,10 +59,16 @@ export default async function users(req: NextApiRequest, res: NextApiResponse) {if (user) {const subscribedUser = await verifySubscription(user);if (!subscribedUser) {- return res.status(401).json({- response:- "You are not a subscriber, feel free to reach out to us at [email protected] if you think this is an issue.",- });+ const isSelfDeletion = req.method === "DELETE" && userId === queryId;++ if (!isSelfDeletion) {+ return res.status(401).json({+ response:+ "You are not a subscriber, feel free to reach out to us at [email protected] if you think this is an issue.",+ });+ }++ bypassPasswordForDeletion = !user.password;}} else {return res.status(404).json({ response: "User not found." });@@ -87,7 +98,8 @@ export default async function users(req: NextApiRequest, res: NextApiResponse) {userId,req.body,isServerAdmin,- queryId+ queryId,+ bypassPasswordForDeletion);return res.status(updated.status).json({ response: updated.response });}diff --git a/apps/web/pages/subscribe.tsx b/apps/web/pages/subscribe.tsxindex f226fe0b..c0fbf024 100644--- a/apps/web/pages/subscribe.tsx+++ b/apps/web/pages/subscribe.tsx@@ -10,6 +10,13 @@ import { Trans, useTranslation } from "next-i18next";import { useUser } from "@linkwarden/router/user";import { Separator } from "@/components/ui/separator";import { cn } from "@/lib/utils";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import DeleteOwnAccountModal from "@/components/ModalContent/DeleteOwnAccountModal";const TRIAL_PERIOD_DAYS =Number(process.env.NEXT_PUBLIC_TRIAL_PERIOD_DAYS) || 14;@@ -18,6 +25,7 @@ const REQUIRE_CC = process.env.NEXT_PUBLIC_REQUIRE_CC === "true";export default function Subscribe() {const { t } = useTranslation();const [submitLoader, setSubmitLoader] = useState(false);+ const [deleteModalOpen, setDeleteModalOpen] = useState(false);const session = useSession();const [plan, setPlan] = useState<Plan>(1);@@ -176,12 +184,30 @@ export default function Subscribe() {</Button>{REQUIRE_CC || daysLeft <= 0 ? (- <div- onClick={() => signOut()}- className="w-fit mx-auto cursor-pointer text-neutral font-semibold "- >- {t("sign_out")}- </div>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ className="w-fit mx-auto flex items-center gap-1 cursor-pointer text-neutral text-sm"+ >+ {t("manage_your_account")}+ <i className="bi-chevron-down text-sm" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="center">+ <DropdownMenuItem onClick={() => signOut()}>+ <i className="bi-box-arrow-right" />+ {t("sign_out")}+ </DropdownMenuItem>+ <DropdownMenuItem+ className="text-red-500 focus:text-red-500"+ onClick={() => setDeleteModalOpen(true)}+ >+ <i className="bi-trash" />+ {t("delete_account")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>) : (<ButtonclassName=""@@ -194,6 +220,10 @@ export default function Subscribe() {)}</div></div>++ {deleteModalOpen && (+ <DeleteOwnAccountModal onClose={() => setDeleteModalOpen(false)} />+ )}</CenteredForm>);}diff --git a/apps/web/public/locales/en/common.json b/apps/web/public/locales/en/common.jsonindex 7cff71fe..1b2734af 100644--- a/apps/web/public/locales/en/common.json+++ b/apps/web/public/locales/en/common.json@@ -148,6 +148,8 @@"more_information": "More information (the more details, the more helpful it'd be)","feedback_placeholder": "e.g. I needed a feature that...","delete_your_account": "Delete Your Account",+ "manage_your_account": "Manage Your Account",+ "type_confirm_to_delete": "Type \"confirm\" below to delete your account","change_password": "Change Password","create_password": "Create Password","password_length_error": "Passwords must be at least 8 characters.",