Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

UserNotificationPreferences (#3289)

Steven Teya1955690de94
diff --git a/apps/web/app/(ee)/api/admin/ban/route.ts b/apps/web/app/(ee)/api/admin/ban/route.ts
index 3db70ec713..ceaef5d50d 100644
--- a/apps/web/app/(ee)/api/admin/ban/route.ts
+++ b/apps/web/app/(ee)/api/admin/ban/route.ts
@@ -2,7 +2,6 @@ import { deleteWorkspaceAdmin } from "@/lib/api/workspaces/delete-workspace";
import { withAdmin } from "@/lib/auth";
import { updateConfig } from "@/lib/edge-config";
import { isStored, storage } from "@/lib/storage";
-import { unsubscribe } from "@dub/email/resend/unsubscribe";
import { prisma } from "@dub/prisma";
import { R2_URL } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
@@ -50,7 +49,6 @@ export const POST = withAdmin(async ({ req }) => {
user.image &&
isStored(user.image) &&
storage.delete({ key: user.image.replace(`${R2_URL}/`, "") }),
- unsubscribe({ email }),
updateConfig({
key: "emails",
value: email,
diff --git a/apps/web/app/(ee)/api/cron/welcome-user/route.ts b/apps/web/app/(ee)/api/cron/welcome-user/route.ts
index f3b8181d96..d6c3574f80 100644
--- a/apps/web/app/(ee)/api/cron/welcome-user/route.ts
+++ b/apps/web/app/(ee)/api/cron/welcome-user/route.ts
@@ -1,7 +1,6 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
import { sendEmail } from "@dub/email";
-import { subscribe } from "@dub/email/resend/subscribe";
import WelcomeEmail from "@dub/email/templates/welcome-email";
import WelcomeEmailPartner from "@dub/email/templates/welcome-email-partner";
import { prisma } from "@dub/prisma";
@@ -57,13 +56,6 @@ export async function POST(req: Request) {
}),
variant: "marketing",
}),
- // only subscribe non-partner users to the mailing list
- !isPartner
- ? subscribe({
- email: user.email,
- name: user.name || undefined,
- })
- : Promise.resolve(),
]);
return new Response("Welcome email sent and user subscribed.", {
diff --git a/apps/web/app/(ee)/partners.dub.co/(auth)/auth/reset-password/[token]/page.tsx b/apps/web/app/(ee)/partners.dub.co/(auth)/auth/reset-password/[token]/page.tsx
index 709b2f5e12..28a17396e5 100644
--- a/apps/web/app/(ee)/partners.dub.co/(auth)/auth/reset-password/[token]/page.tsx
+++ b/apps/web/app/(ee)/partners.dub.co/(auth)/auth/reset-password/[token]/page.tsx
@@ -1,59 +1 @@
-import { ResetPasswordForm } from "@/ui/auth/reset-password-form";
-import { AuthLayout } from "@/ui/layout/auth-layout";
-import EmptyState from "@/ui/shared/empty-state";
-import { prisma } from "@dub/prisma";
-import { InputPassword } from "@dub/ui";
-interface Props {
- params: Promise<{
- token: string;
- }>;
-}
-
-export default async function ResetPasswordPage(props: Props) {
- const params = await props.params;
-
- const { token } = params;
-
- const validToken = await isValidToken(token);
-
- if (!validToken) {
- return (
- <AuthLayout>
- <EmptyState
- icon={InputPassword}
- title="Invalid Reset Token"
- description="The password reset token is invalid or expired. Please request a new one."
- />
- </AuthLayout>
- );
- }
-
- return (
- <AuthLayout>
- <div className="w-full max-w-sm">
- <h3 className="text-center text-xl font-semibold">
- Reset your password
- </h3>
- <div className="mt-8">
- <ResetPasswordForm />
- </div>
- </div>
- </AuthLayout>
- );
-}
-
-const isValidToken = async (token: string) => {
- const resetToken = await prisma.passwordResetToken.findUnique({
- where: {
- token,
- expires: {
- gte: new Date(),
- },
- },
- select: {
- token: true,
- },
- });
-
- return !!resetToken;
-};
+export { default } from "app/app.dub.co/(auth)/auth/reset-password/[token]/page";
diff --git a/apps/web/app/(ee)/partners.dub.co/(auth)/unsubscribe/[token]/page.tsx b/apps/web/app/(ee)/partners.dub.co/(auth)/unsubscribe/[token]/page.tsx
new file mode 100644
index 0000000000..9ff3caa120
--- /dev/null
+++ b/apps/web/app/(ee)/partners.dub.co/(auth)/unsubscribe/[token]/page.tsx
@@ -0,0 +1 @@
+export { default } from "app/app.dub.co/(auth)/unsubscribe/[token]/page";
diff --git a/apps/web/app/api/auth/reset-password/route.ts b/apps/web/app/api/auth/reset-password/route.ts
index d33b144c3f..44afd346f1 100644
--- a/apps/web/app/api/auth/reset-password/route.ts
+++ b/apps/web/app/api/auth/reset-password/route.ts
@@ -90,7 +90,7 @@ export async function POST(req: NextRequest) {
// Send the email to inform the user that their password has been reset
waitUntil(
sendEmail({
- subject: `Your ${process.env.NEXT_PUBLIC_APP_NAME} account password has been reset`,
+ subject: "Your Dub account password has been reset",
to: identifier,
react: PasswordUpdated({
email: identifier,
diff --git a/apps/web/app/api/resend/webhook/contact-updated.ts b/apps/web/app/api/resend/webhook/contact-updated.ts
deleted file mode 100644
index 83a2754ab5..0000000000
--- a/apps/web/app/api/resend/webhook/contact-updated.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { prisma } from "@dub/prisma";
-
-export async function contactUpdated({
- email,
- unsubscribed,
-}: {
- email: string;
- unsubscribed: boolean;
-}) {
- if (!email) {
- return;
- }
-
- console.log(
- `${email} ${unsubscribed ? "unsubscribed from" : "subscribed to"} mailing list. Updating user...`,
- );
-
- try {
- const res = await prisma.user.update({
- where: {
- email,
- },
- data: {
- subscribed: !unsubscribed,
- },
- });
- console.log(`Updated user ${email}: ${JSON.stringify(res, null, 2)}`);
- } catch (error) {
- console.error(`Error updating user ${email}: ${error.message}`);
- }
-}
diff --git a/apps/web/app/api/resend/webhook/route.ts b/apps/web/app/api/resend/webhook/route.ts
index 67fe259fbc..ef479c5137 100644
--- a/apps/web/app/api/resend/webhook/route.ts
+++ b/apps/web/app/api/resend/webhook/route.ts
@@ -1,6 +1,5 @@
import { NextResponse } from "next/server";
import { Webhook } from "svix";
-import { contactUpdated } from "./contact-updated";
import { emailBounced } from "./email-bounced";
import { emailDelivered } from "./email-delivered";
import { emailOpened } from "./email-opened";
@@ -22,9 +21,6 @@ export const POST = async (req: Request) => {
const { type, data } = JSON.parse(rawBody) || {};
switch (type) {
- case "contact.updated":
- await contactUpdated(data);
- break;
case "email.opened":
await emailOpened(data);
break;
diff --git a/apps/web/app/api/user/notification-preferences/route.ts b/apps/web/app/api/user/notification-preferences/route.ts
new file mode 100644
index 0000000000..25910508ba
--- /dev/null
+++ b/apps/web/app/api/user/notification-preferences/route.ts
@@ -0,0 +1,152 @@
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { ratelimitOrThrow } from "@/lib/api/utils";
+import { NOTIFICATION_PREFERENCE_TYPES } from "@/lib/constants/notification-preferences";
+import { verifyUnsubscribeToken } from "@/lib/email/unsubscribe-token";
+import { prisma } from "@dub/prisma";
+import { NextRequest, NextResponse } from "next/server";
+import { z } from "zod";
+
+const requestSchema = z.object({
+ token: z.string(),
+ preferences: z.record(
+ z.enum(NOTIFICATION_PREFERENCE_TYPES as unknown as [string, ...string[]]),
+ z.boolean(),
+ ),
+});
+
+// GET /api/user/notification-preferences?token=... – get notification preferences via unsubscribe link
+export async function GET(request: NextRequest) {
+ try {
+ await ratelimitOrThrow(request, "notification-preferences");
+
+ const { searchParams } = new URL(request.url);
+ const token = searchParams.get("token");
+
+ if (!token) {
+ return NextResponse.json({ error: "Token is required" }, { status: 400 });
+ }
+
+ // Verify the token and extract the email
+ const email = verifyUnsubscribeToken(token);
+
+ if (!email) {
+ return NextResponse.json(
+ { error: "Invalid or expired token" },
+ { status: 400 },
+ );
+ }
+
+ // Find the user by email
+ const user = await prisma.user.findUnique({
+ where: { email },
+ select: {
+ id: true,
+ notificationPreferences: {
+ select: {
+ dubLinks: true,
+ dubPartners: true,
+ partnerAccount: true,
+ },
+ },
+ },
+ });
+
+ if (!user) {
+ return NextResponse.json({ error: "User not found" }, { status: 404 });
+ }
+
+ // Return preferences directly (field names match schema)
+ const preferences = user.notificationPreferences
+ ? {
+ dubLinks: user.notificationPreferences.dubLinks,
+ dubPartners: user.notificationPreferences.dubPartners,
+ partnerAccount: user.notificationPreferences.partnerAccount,
+ }
+ : {
+ dubLinks: true,
+ dubPartners: true,
+ partnerAccount: true,
+ };
+
+ return NextResponse.json(preferences);
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+}
+
+// POST /api/user/notification-preferences – update notification preferences via unsubscribe link
+export async function POST(request: NextRequest) {
+ try {
+ await ratelimitOrThrow(request, "notification-preferences");
+
+ const body = await request.json();
+ const { token, preferences } = requestSchema.parse(body);
+
+ // Verify the token and extract the email
+ const email = verifyUnsubscribeToken(token);
+
+ if (!email) {
+ return NextResponse.json(
+ { error: "Invalid or expired token" },
+ { status: 400 },
+ );
+ }
+
+ // Find the user by email
+ const user = await prisma.user.findUnique({
+ where: { email },
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ notificationPreferences: {
+ select: {
+ dubLinks: true,
+ dubPartners: true,
+ partnerAccount: true,
+ },
+ },
+ },
+ });
+
+ if (!user) {
+ return NextResponse.json({ error: "User not found" }, { status: 404 });
+ }
+
+ // Get existing preferences or use defaults
+ const existingPrefs = user.notificationPreferences || {
+ dubLinks: true,
+ dubPartners: true,
+ partnerAccount: true,
+ };
+
+ // Merge preferences with existing values (field names now match schema directly)
+ const updatedPrefs = {
+ dubLinks: preferences.dubLinks ?? existingPrefs.dubLinks,
+ dubPartners: preferences.dubPartners ?? existingPrefs.dubPartners,
+ partnerAccount:
+ preferences.partnerAccount ?? existingPrefs.partnerAccount,
+ };
+
+ // Update or create notification preferences using upsert pattern
+ await prisma.user.update({
+ where: { id: user.id },
+ data: {
+ notificationPreferences: {
+ upsert: {
+ create: updatedPrefs,
+ update: updatedPrefs,
+ },
+ },
+ },
+ });
+
+ // Return updated preferences
+ return NextResponse.json({
+ success: true,
+ preferences: updatedPrefs,
+ });
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+}
diff --git a/apps/web/app/api/user/route.ts b/apps/web/app/api/user/route.ts
index fbba8e2cdd..eb1317af3d 100644
--- a/apps/web/app/api/user/route.ts
+++ b/apps/web/app/api/user/route.ts
@@ -3,7 +3,6 @@ import { withSession } from "@/lib/auth";
import { confirmEmailChange } from "@/lib/auth/confirm-email-change";
import { storage } from "@/lib/storage";
import { uploadedImageSchema } from "@/lib/zod/schemas/misc";
-import { unsubscribe } from "@dub/email/resend/unsubscribe";
import { prisma } from "@dub/prisma";
import {
APP_DOMAIN,
@@ -37,7 +36,6 @@ export const GET = withSession(async ({ session }) => {
name: true,
email: true,
image: true,
- subscribed: true,
source: true,
defaultWorkspace: true,
defaultPartnerId: true,
@@ -171,13 +169,13 @@ export const DELETE = withSession(async ({ session }) => {
id: session.user.id,
},
});
- const response = await Promise.allSettled([
- // if the user has a custom avatar and it is stored by their userId, delete it
+ // if the user has a custom avatar and it is stored by their userId, delete it
+ if (
user.image &&
- user.image.startsWith(`${R2_URL}/avatars/${session.user.id}`) &&
- storage.delete({ key: user.image.replace(`${R2_URL}/`, "") }),
- unsubscribe({ email: session.user.email }),
- ]);
- return NextResponse.json(response);
+ user.image.startsWith(`${R2_URL}/avatars/${session.user.id}`)
+ ) {
+ await storage.delete({ key: user.image.replace(`${R2_URL}/`, "") });
+ }
+ return NextResponse.json(user);
}
});
diff --git a/apps/web/app/api/user/subscribe/route.ts b/apps/web/app/api/user/subscribe/route.ts
deleted file mode 100644
index bc5fdbd002..0000000000
--- a/apps/web/app/api/user/subscribe/route.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { withSession } from "@/lib/auth";
-import { subscribe } from "@dub/email/resend/subscribe";
-import { unsubscribe } from "@dub/email/resend/unsubscribe";
-import { prisma } from "@dub/prisma";
-import { NextResponse } from "next/server";
-
-// GET /api/user/subscribe – get a specific user
-export const GET = withSession(async ({ session }) => {
- const user = await prisma.user.findUnique({
- where: {
- id: session.user.id,
- },
- select: {
- id: true,
- name: true,
- email: true,
- subscribed: true,
- },
- });
-
- if (!user) {
- return new Response("User not found", { status: 404 });
- }
-
- return NextResponse.json(user);
-});
-
-// POST /api/user/subscribe – subscribe a specific user
-export const POST = withSession(async ({ session }) => {
- const [user, _] = await Promise.all([
- prisma.user.update({
- where: {
- id: session.user.id,
- },
- data: {
- subscribed: true,
- },
- select: {
- id: true,
- name: true,
- email: true,
- subscribed: true,
- },
- }),
- subscribe({ email: session.user.email, name: session.user.name }),
- ]);
-
- return NextResponse.json(user);
-});
-
-// DELETE /api/user/subscribe – unsubscribe a specific user
-export const DELETE = withSession(async ({ session }) => {
- const [user, _] = await Promise.allSettled([
- prisma.user.update({
- where: {
- id: session.user.id,
- },
- data: {
- subscribed: false,
- },
- select: {
- id: true,
- name: true,
- email: true,
- subscribed: true,
- },
- }),
- unsubscribe({ email: session.user.email }),
- ]);
-
- return NextResponse.json(user);
-});
diff --git a/apps/web/app/api/workspaces/route.ts b/apps/web/app/api/workspaces/route.ts
index 589b760d54..28fd80b4e0 100644
--- a/apps/web/app/api/workspaces/route.ts
+++ b/apps/web/app/api/workspaces/route.ts
@@ -9,7 +9,6 @@ import {
createWorkspaceSchema,
WorkspaceSchema,
} from "@/lib/zod/schemas/workspaces";
-import { subscribe } from "@dub/email/resend/subscribe";
import { prisma } from "@dub/prisma";
import { Prisma } from "@dub/prisma/client";
import { FREE_WORKSPACES_LIMIT, nanoid, R2_URL } from "@dub/utils";
@@ -162,11 +161,7 @@ export const POST = withSession(async ({ req, session }) => {
defaultWorkspace: workspace.slug,
},
}),
- // Subscribe the user to the Resend audience
- subscribe({
- email: session.user.email,
- name: session.user.name || undefined,
- }),
+
// Upload logo to R2 if uploaded
logo &&
uploadedImageUrl &&
diff --git a/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/[token]/page.tsx b/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/[token]/page.tsx
index 93d4b4cc7e..76e517d799 100644
--- a/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/[token]/page.tsx
+++ b/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/[token]/page.tsx
@@ -2,8 +2,6 @@ import { getSession, hashToken } from "@/lib/auth";
import { redis } from "@/lib/upstash";
import EmptyState from "@/ui/shared/empty-state";
import { sendEmail } from "@dub/email";
-import { subscribe } from "@dub/email/resend/subscribe";
-import { unsubscribe } from "@dub/email/resend/unsubscribe";
import EmailUpdated from "@dub/email/templates/email-updated";
import { prisma } from "@dub/prisma";
import { User, VerificationToken } from "@dub/prisma/client";
@@ -132,9 +130,6 @@ const VerifyEmailChange = async ({ params, searchParams }: PageProps) => {
data: {
email: data.newEmail,
},
- select: {
- subscribed: true,
- },
});
}
@@ -142,13 +137,6 @@ const VerifyEmailChange = async ({ params, searchParams }: PageProps) => {
Promise.allSettled([
deleteRequest(tokenFound),
- ...(user?.subscribed
- ? [
- unsubscribe({ email: data.email }),
- subscribe({ email: data.newEmail }),
- ]
- : []),
-
sendEmail({
subject: "Your email address has been changed",
to: data.email,
diff --git a/apps/web/app/app.dub.co/(auth)/unsubscribe/[token]/page.tsx b/apps/web/app/app.dub.co/(auth)/unsubscribe/[token]/page.tsx
new file mode 100644
index 0000000000..8193bd2b8c
--- /dev/null
+++ b/apps/web/app/app.dub.co/(auth)/unsubscribe/[token]/page.tsx
@@ -0,0 +1,35 @@
+import { verifyUnsubscribeToken } from "@/lib/email/unsubscribe-token";
+import EmptyState from "@/ui/shared/empty-state";
+import { LinkBroken } from "@dub/ui/icons";
+import { constructMetadata } from "@dub/utils";
+import { UnsubscribeForm } from "./unsubscribe-form";
+
+export const metadata = constructMetadata({
+ title: "Email Preferences – Dub",
+ description: "Manage your email subscription preferences on Dub",
+ noIndex: true,
+});
+
+export default async function UnsubscribePage(props: {
+ params: Promise<{ token: string }>;
+}) {
+ const { token } = await props.params;
+
+ const email = verifyUnsubscribeToken(token);
+
+ if (!email) {
+ return (
+ <EmptyState
+ icon={LinkBroken}
+ title="Invalid Unsubscribe Link"
+ description="This unsubscribe link is invalid or has expired. Please use the link from a recent email to manage your preferences."
+ />
+ );
+ }
+
+ return (
+ <div className="m-auto w-full max-w-lg overflow-hidden border border-neutral-200 shadow-xl sm:rounded-2xl">
+ <UnsubscribeForm email={email} token={token} />
+ </div>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(auth)/unsubscribe/[token]/unsubscribe-form.tsx b/apps/web/app/app.dub.co/(auth)/unsubscribe/[token]/unsubscribe-form.tsx
new file mode 100644
index 0000000000..6e2969c05c
--- /dev/null
+++ b/apps/web/app/app.dub.co/(auth)/unsubscribe/[token]/unsubscribe-form.tsx
@@ -0,0 +1,228 @@
+"use client";
+
+import {
+ NOTIFICATION_PREFERENCE_LABELS,
+ NOTIFICATION_PREFERENCE_TYPES,
+ NotificationPreferenceType,
+} from "@/lib/constants/notification-preferences";
+import { Button, Switch } from "@dub/ui";
+import { DubLinksIcon, DubPartnersIcon, UserPlus } from "@dub/ui/icons";
+import { fetcher } from "@dub/utils";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { toast } from "sonner";
+import useSWRImmutable from "swr/immutable";
+
+type PreferenceState = Record<NotificationPreferenceType, boolean>;
+
+const NOTIFICATION_ICONS: Record<
+ NotificationPreferenceType,
+ React.ComponentType<{ className?: string }>
+> = {
+ dubLinks: DubLinksIcon,
+ dubPartners: DubPartnersIcon,
+ partnerAccount: UserPlus,
+};
+
+export function UnsubscribeForm({
+ email,
+ token,
+}: {
+ email: string;
+ token: string;
+}) {
+ const [preferences, setPreferences] = useState<PreferenceState>(() => {
+ const initial: Partial<PreferenceState> = {};
+ NOTIFICATION_PREFERENCE_TYPES.forEach((type) => {
+ initial[type] = true;
+ });
+ return initial as PreferenceState;
+ });
+
+ const [saving, setSaving] = useState(false);
+ const [originalPreferences, setOriginalPreferences] =
+ useState<PreferenceState | null>(null);
+
+ // Fetch initial preferences from API
+ const {
+ data: fetchedPreferences,
+ error,
+ isLoading: loading,
+ } = useSWRImmutable<PreferenceState>(
+ `/api/user/notification-preferences?token=${encodeURIComponent(token)}`,
+ fetcher,
+ );
+
+ // Sync fetched preferences to state
+ useEffect(() => {
+ if (fetchedPreferences) {
+ setPreferences(fetchedPreferences);
+ setOriginalPreferences(fetchedPreferences);
+ }
+ }, [fetchedPreferences]);
+
+ // Handle errors
+ useEffect(() => {
+ if (error) {
+ toast.error(
+ error instanceof Error ? error.message : "Failed to load preferences",
+ );
+ }
+ }, [error]);
+
+ // Check if form is dirty (has changes)
+ const isDirty = useMemo(() => {
+ if (!originalPreferences) return false;
+ return NOTIFICATION_PREFERENCE_TYPES.some(
+ (type) => preferences[type] !== originalPreferences[type],
+ );
+ }, [preferences, originalPreferences]);
+
+ const handleToggle = useCallback(
+ (type: NotificationPreferenceType) => (checked: boolean) => {
+ setPreferences((prev) => ({
+ ...prev,
+ [type]: checked,
+ }));
+ },
+ [],
+ );
+
+ const handleSave = useCallback(async () => {
+ setSaving(true);
+
+ try {
+ const res = await fetch("/api/user/notification-preferences", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ token, preferences }),
+ });
+
+ if (!res.ok) {
+ const data = await res.json();
+ throw new Error(data.error || "Failed to save preferences");
+ }
+
+ // Update original preferences after successful save
+ setOriginalPreferences(preferences);
+ toast.success("Your preferences have been saved!");
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Something went wrong");
+ } finally {
+ setSaving(false);
+ }
+ }, [token, preferences]);
+
+ const handleUnsubscribeAll = useCallback(async () => {
+ const confirmed = window.confirm(
+ "Are you sure you want to unsubscribe from all emails?",
+ );
+ if (!confirmed) {
+ return;
+ }
+
+ setSaving(true);
+
+ const allOff: PreferenceState = {} as PreferenceState;
+ NOTIFICATION_PREFERENCE_TYPES.forEach((type) => {
+ allOff[type] = false;
+ });
+
+ try {
+ const res = await fetch("/api/user/notification-preferences", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ token, preferences: allOff }),
+ });
+
+ if (!res.ok) {
+ const data = await res.json();
+ throw new Error(data.error || "Failed to unsubscribe");
+ }
+
+ setPreferences(allOff);
+ setOriginalPreferences(allOff);
+ toast.success("You have been unsubscribed from all emails!");
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Something went wrong");
+ } finally {
+ setSaving(false);
+ }
+ }, [token]);
+
+ return (
+ <>
+ <div className="flex flex-col items-center justify-center gap-3 border-b border-neutral-200 bg-white px-4 py-6 pt-8 text-center sm:rounded-t-2xl sm:px-6 md:px-16">
+ <h2 className="text-lg font-semibold text-neutral-900">
+ Email Preferences
+ </h2>
+ <p className="text-sm text-neutral-500">
+ Manage your email subscriptions for{" "}
+ <span className="font-medium text-neutral-700">{email}</span>
+ </p>
+ </div>
+ <div className="flex flex-col space-y-3 bg-white px-4 py-6 sm:px-6 md:px-10">
+ <div className="divide-y divide-neutral-100">
+ {NOTIFICATION_PREFERENCE_TYPES.map((type) => {
+ const { title, description, link } =
+ NOTIFICATION_PREFERENCE_LABELS[type];
+ const isEnabled = preferences[type];
+ const Icon = NOTIFICATION_ICONS[type];
+
+ return (
+ <div
+ key={type}
+ className="flex items-start justify-between gap-3 py-5 first:pt-0 sm:items-center sm:gap-4"
+ >
+ <div className="flex min-w-0 items-start gap-3 sm:items-center sm:gap-4">
+ <a
+ href={link}
+ target="_blank"
+ className="flex shrink-0 items-center justify-center rounded-full border border-neutral-200 bg-gradient-to-t from-neutral-100 p-2 transition-colors hover:border-neutral-300 hover:from-neutral-200 sm:p-2.5"
+ >
+ <Icon className="size-4 sm:size-5" />
+ </a>
+ <div className="min-w-0 flex-1 pr-2 sm:pr-4">
+ <div className="flex flex-wrap items-center gap-1.5 sm:gap-2">
+ <a href={link} target="_blank">
+ <h3 className="cursor-help text-sm font-medium text-neutral-900 underline decoration-dotted underline-offset-2 transition-colors hover:text-neutral-600">
+ {title}
+ </h3>
+ </a>
+ </div>
+ <p className="mt-0.5 text-xs text-neutral-500 sm:text-sm">
+ {description}
+ </p>
+ </div>
+ </div>
+ <Switch
+ loading={loading}
+ checked={isEnabled}
+ disabled={saving}
+ fn={handleToggle(type)}
+ />
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ <div className="flex flex-col space-y-2 border-t border-neutral-200 bg-white px-4 py-6 sm:rounded-b-2xl sm:px-6 md:px-10">
+ <Button
+ text={saving ? "Saving..." : "Save Preferences"}
+ onClick={handleSave}
+ loading={saving}
+ disabled={!isDirty || saving}
+ className="w-full"
+ />
+
+ <button
+ type="button"
+ onClick={handleUnsubscribeAll}
+ disabled={saving}
+ className="mt-2 w-full text-center text-xs text-neutral-400 transition-colors hover:text-neutral-600 disabled:cursor-not-allowed disabled:text-neutral-400"
+ >
+ Unsubscribe from all emails
+ </button>
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/notifications/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/notifications/page-client.tsx
index 7cfcd07a12..d56cba828c 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/notifications/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/notifications/page-client.tsx
@@ -1,6 +1,6 @@
"use client";
-import { updateNotificationPreference } from "@/lib/actions/update-notification-preference";
+import { updateWorkspaceNotificationPreference } from "@/lib/actions/update-workspace-notification-preference";
import useWorkspace from "@/lib/swr/use-workspace";
import { notificationTypes } from "@/lib/zod/schemas/workspaces";
import { Switch, useOptimisticUpdate } from "@dub/ui";
@@ -16,7 +16,7 @@ type Preferences = Record<PreferenceType, boolean>;
export default function NotificationsSettingsPageClient() {
const { id: workspaceId } = useWorkspace();
- const { executeAsync } = useAction(updateNotificationPreference);
+ const { executeAsync } = useAction(updateWorkspaceNotificationPreference);
const workspaceNotifications = [
{
diff --git a/apps/web/lib/actions/create-user-account.ts b/apps/web/lib/actions/create-user-account.ts
index be157bc27c..a3baf2a907 100644
--- a/apps/web/lib/actions/create-user-account.ts
+++ b/apps/web/lib/actions/create-user-account.ts
@@ -87,6 +87,9 @@ export const createUserAccountAction = actionClient
email,
passwordHash: await hashPassword(password),
emailVerified: new Date(),
+ notificationPreferences: {
+ create: {},
+ },
},
});
}
diff --git a/apps/web/lib/actions/generate-unsubscribe-url.ts b/apps/web/lib/actions/generate-unsubscribe-url.ts
new file mode 100644
index 0000000000..a9bbc209a1
--- /dev/null
+++ b/apps/web/lib/actions/generate-unsubscribe-url.ts
@@ -0,0 +1,15 @@
+"use server";
+
+import { generateUnsubscribeToken } from "../email/unsubscribe-token";
+import { authUserActionClient } from "./safe-action";
+
+// Generate an unsubscribe token for a user
+export const generateUnsubscribeTokenAction = authUserActionClient.action(
+ async ({ ctx }) => {
+ const { user } = ctx;
+
+ const token = generateUnsubscribeToken(user.email);
+
+ return { token };
+ },
+);
diff --git a/apps/web/lib/actions/update-notification-preference.ts b/apps/web/lib/actions/update-workspace-notification-preference.ts
similarity index 92%
rename from apps/web/lib/actions/update-notification-preference.ts
rename to apps/web/lib/actions/update-workspace-notification-preference.ts
index 95c1705f7c..dc7e30338c 100644
--- a/apps/web/lib/actions/update-notification-preference.ts
+++ b/apps/web/lib/actions/update-workspace-notification-preference.ts
@@ -12,7 +12,7 @@ const schema = z.object({
});
// Update the notification preference for a user in a workspace
-export const updateNotificationPreference = authActionClient
+export const updateWorkspaceNotificationPreference = authActionClient
.schema(schema)
.action(async ({ ctx, parsedInput }) => {
const { user, workspace } = ctx;
diff --git a/apps/web/lib/auth/options.ts b/apps/web/lib/auth/options.ts
index 61c06ccd13..9517ad8e6b 100644
--- a/apps/web/lib/auth/options.ts
+++ b/apps/web/lib/auth/options.ts
@@ -39,6 +39,9 @@ const CustomPrismaAdapter = (p: PrismaClient) => {
data: {
...data,
id: createId({ prefix: "user_" }),
+ notificationPreferences: {
+ create: {},
+ },
},
});
},
@@ -104,6 +107,9 @@ export const authOptions: NextAuthOptions = {
name: `${profile.firstName || ""} ${
profile.lastName || ""
}`.trim(),
+ notificationPreferences: {
+ create: {},
+ },
},
});
}
@@ -175,6 +181,9 @@ export const authOptions: NextAuthOptions = {
name: `${userInfo.firstName || ""} ${
userInfo.lastName || ""
}`.trim(),
+ notificationPreferences: {
+ create: {},
+ },
},
});
}
diff --git a/apps/web/lib/constants/notification-preferences.ts b/apps/web/lib/constants/notification-preferences.ts
new file mode 100644
index 0000000000..33922c9c6a
--- /dev/null
+++ b/apps/web/lib/constants/notification-preferences.ts
@@ -0,0 +1,54 @@
+// User-level notification preferences for email communications
+export const NOTIFICATION_PREFERENCE_TYPES = [
+ "dubLinks", // Dub Links product updates on app.dub.co
+ "dubPartners", // Dub Partners product updates on app.dub.co
+ "partnerAccount", // Updates to partner accounts on partners.dub.co
+] as const;
+
+export type NotificationPreferenceType =
+ (typeof NOTIFICATION_PREFERENCE_TYPES)[number];
+
+// Mapping from preference type to UserNotificationPreferences schema field names
+// (1:1 mapping since we're using the same names as the schema)
+export const NOTIFICATION_PREFERENCE_FIELD_MAP: Record<
+ NotificationPreferenceType,
+ "dubLinks" | "dubPartners" | "partnerAccount"
+> = {
+ dubLinks: "dubLinks",
+ dubPartners: "dubPartners",
+ partnerAccount: "partnerAccount",
+};
+
+// Default all preferences to true (opted in)
+export const DEFAULT_NOTIFICATION_PREFERENCES: Record<
+ NotificationPreferenceType,
+ boolean
+> = {
+ dubLinks: true,
+ dubPartners: true,
+ partnerAccount: true,
+};
+
+export const NOTIFICATION_PREFERENCE_LABELS: Record<
+ NotificationPreferenceType,
+ { title: string; description: string; link: string }
+> = {
+ dubLinks: {
+ title: "Dub Links",
+ description:
+ "New Dub Links features and guides on how to manage and track your links",
+ link: "https://dub.co/links",
+ },
+ dubPartners: {
+ title: "Dub Partners",
+ description:
+ "New Dub Partners features and tips on how to grow your affiliate program",
+ link: "https://dub.co/partners",
+ },
+ partnerAccount: {
+ title: "Partner Account",
+ description:
+ "New program launches, feature updates, and tutorials on how to succeed as a partner",
+ link: "https://partners.dub.co",
+ },
+};
diff --git a/apps/web/lib/email/unsubscribe-token.ts b/apps/web/lib/email/unsubscribe-token.ts
new file mode 100644
index 0000000000..ab206796a1
--- /dev/null
+++ b/apps/web/lib/email/unsubscribe-token.ts
@@ -0,0 +1,56 @@
+import { createHmac, timingSafeEqual } from "crypto";
+
+const TOKEN_SECRET = process.env.UNSUBSCRIBE_TOKEN_SECRET;
+
+/**
+ * Generate a secure unsubscribe token for an email address.
+ * The token is a combination of the email and a signature that can be verified.
+ */
+export function generateUnsubscribeToken(email: string): string {
+ if (!TOKEN_SECRET) throw new Error("UNSUBSCRIBE_TOKEN_SECRET is not set");
+
+ const signature = createHmac("sha256", TOKEN_SECRET)
+ .update(email.toLowerCase())
+ .digest("hex")
+ .slice(0, 16); // Truncate for shorter URLs
+
+ // Base64 encode the email and append the signature
+ const encodedEmail = Buffer.from(email.toLowerCase()).toString("base64url");
+ return `${encodedEmail}.${signature}`;
+}
+
+/**
+ * Verify and decode an unsubscribe token.
+ * Returns the email if valid, null otherwise.
+ */
+export function verifyUnsubscribeToken(token: string): string | null {
+ try {
+ const [encodedEmail, signature] = token.split(".");
+ if (!encodedEmail || !signature) {
+ return null;
+ }
+
+ const email = Buffer.from(encodedEmail, "base64url").toString("utf-8");
+
+ if (!TOKEN_SECRET) throw new Error("UNSUBSCRIBE_TOKEN_SECRET is not set");
+
+ // Verify the signature
+ const expectedSignature = createHmac("sha256", TOKEN_SECRET)
+ .update(email.toLowerCase())
+ .digest("hex")
+ .slice(0, 16);
+
+ if (
+ !timingSafeEqual(
+ Uint8Array.from(Buffer.from(signature)),
+ Uint8Array.from(Buffer.from(expectedSignature)),
+ )
+ ) {
+ return null;
+ }
+
+ return email;
+ } catch {
+ return null;
+ }
+}
diff --git a/apps/web/scripts/get-subscribers.ts b/apps/web/scripts/get-subscribers.ts
deleted file mode 100644
index 664502cb76..0000000000
--- a/apps/web/scripts/get-subscribers.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { prisma } from "@dub/prisma";
-import "dotenv-flow/config";
-import * as fs from "fs";
-import * as Papa from "papaparse";
-
-let emailOpens: string[] = [];
-
-async function main() {
- Papa.parse(fs.createReadStream("email_opens.csv", "utf-8"), {
- header: true,
- skipEmptyLines: true,
- step: (result: {
- data: {
- email_address: string;
- };
- }) => {
- emailOpens.push(result.data.email_address);
- },
- });
-
- const subscribers = await prisma.user.findMany({
- where: {
- subscribed: true,
- },
- select: {
- email: true,
- name: true,
- },
- orderBy: {
- createdAt: "asc",
- },
- });
-
- const subscribersThatOpenedEmail = subscribers
- // .filter((subscriber) => emailOpens.includes(subscriber.email!))
- .map(({ email, name }) => ({
- email,
- ...(name && {
- firstName: name.split(" ")[0],
- lastName: name.split(" ").slice(1).join(" "),
- }),
- }));
-
- console.table(subscribersThatOpenedEmail.slice(0, 10));
-
- fs.writeFileSync(
- "all_email_subscribers.csv",
- Papa.unparse(subscribersThatOpenedEmail),
- );
-}
-
-main();
diff --git a/apps/web/scripts/migrations/backfill-notification-preferences.ts b/apps/web/scripts/migrations/backfill-notification-preferences.ts
index 1b03a27ee5..2051a2baa2 100644
--- a/apps/web/scripts/migrations/backfill-notification-preferences.ts
+++ b/apps/web/scripts/migrations/backfill-notification-preferences.ts
@@ -2,32 +2,23 @@ import { prisma } from "@dub/prisma";
import "dotenv-flow/config";
async function main() {
- const partnerUsers = await prisma.partnerUser.findMany({
+ const users = await prisma.user.findMany({
where: {
notificationPreferences: null,
},
select: {
id: true,
},
- take: 100,
+ take: 1000,
});
- if (partnerUsers.length === 0) {
- console.log("No partner users found without notification preferences");
- return;
- }
-
- const result = await prisma.partnerNotificationPreferences.createMany({
- data: partnerUsers.map((partnerUser) => ({
- partnerUserId: partnerUser.id,
+ const res = await prisma.userNotificationPreferences.createMany({
+ data: users.map((user) => ({
+ userId: user.id,
})),
});
- console.log(
- "Created notification preferences for",
- result.count,
- "partner users",
- );
+ console.log(`Created ${res.count} notification preferences`);
}
main();
diff --git a/apps/web/scripts/send-batch-emails.ts b/apps/web/scripts/send-batch-emails.ts
index 9cda3cc70e..cb20f44875 100644
--- a/apps/web/scripts/send-batch-emails.ts
+++ b/apps/web/scripts/send-batch-emails.ts
@@ -11,7 +11,9 @@ async function main() {
users: {
some: {
user: {
- subscribed: true,
+ notificationPreferences: {
+ partnerAccount: true,
+ },
},
},
},
diff --git a/apps/web/scripts/unsubscribe-inactive-users.ts b/apps/web/scripts/unsubscribe-inactive-users.ts
deleted file mode 100644
index 54ee04e277..0000000000
--- a/apps/web/scripts/unsubscribe-inactive-users.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-// @ts-nocheck – install resend lib before running this script
-
-import { limiter } from "@/lib/cron/limiter";
-import { prisma } from "@dub/prisma";
-import { Prisma } from "@dub/prisma/client";
-import "dotenv-flow/config";
-import { Resend } from "resend";
-
-const resend = process.env.RESEND_API_KEY
- ? new Resend(process.env.RESEND_API_KEY)
- : null;
-
-async function main() {
- if (!resend) {
- console.error(
- "No RESEND_API_KEY is set in the environment variables. Skipping.",
- );
- return;
- }
-
- const where: Prisma.UserWhereInput = {
- email: {
- not: null,
- },
- subscribed: true,
- // more than 6 months
- createdAt: {
- lte: new Date(Date.now() - 1000 * 60 * 60 * 24 * 180),
- },
- projects: {
- none: {},
- },
- partners: {
- none: {},
- },
- };
-
- const users = await prisma.user.findMany({
- where,
- skip: 20000,
- take: 5000,
- });
-
- console.table(users, ["email", "createdAt"]);
-
- const response = await Promise.all(
- users.map((user) =>
- limiter.schedule(() =>
- resend.contacts.remove({
- email: user.email!,
- audienceId: "f5ff0661-4234-43f6-b0ca-a3f3682934e3",
- }),
- ),
- ),
- );
-
- console.table(response.map((r) => r.data));
- console.log(`Removed ${response.length} users from Resend audience`);
-}
-
-main();
diff --git a/apps/web/ui/account/update-subscription.tsx b/apps/web/ui/account/update-subscription.tsx
index 0346240cb2..a949d93f0b 100644
--- a/apps/web/ui/account/update-subscription.tsx
+++ b/apps/web/ui/account/update-subscription.tsx
@@ -1,36 +1,48 @@
-import { Switch, useOptimisticUpdate } from "@dub/ui";
-import { APP_NAME } from "@dub/utils";
+import { generateUnsubscribeTokenAction } from "@/lib/actions/generate-unsubscribe-url";
+import useUser from "@/lib/swr/use-user";
+import { ExpandingArrow, LoadingSpinner } from "@dub/ui";
+import { cn } from "@dub/utils";
+import { useAction } from "next-safe-action/hooks";
+import { useRouter } from "next/navigation";
export default function UpdateSubscription() {
- const { data, isLoading, update } = useOptimisticUpdate<{
- subscribed: boolean;
- }>("/api/user/subscribe", {
- loading: "Updating email preferences...",
- success: `Your ${APP_NAME} email preferences has been updated!`,
- error: "Failed to update email preferences. Please try again.",
- });
+ const router = useRouter();
+ const { user } = useUser();
- const subscribe = async (checked: boolean) => {
- const method = checked ? "POST" : "DELETE";
- const res = await fetch("/api/user/subscribe", {
- method,
- });
- if (!res.ok) {
- throw new Error("Failed to update email preferences");
- }
- return { subscribed: checked };
- };
+ const { executeAsync, isPending } = useAction(
+ generateUnsubscribeTokenAction,
+ {
+ onSuccess: ({ data }) => {
+ if (!data?.token) {
+ return;
+ }
+ router.push(`/unsubscribe/${data.token}`);
+ },
+ },
+ );
+
+ if (!user?.email) {
+ return <div />;
+ }
return (
- <div className="flex items-center gap-x-2">
- <Switch
- checked={data?.subscribed}
- loading={isLoading}
- fn={(checked: boolean) => {
- update(() => subscribe(checked), { subscribed: checked });
- }}
- />
- <p className="text-sm text-neutral-500">Subscribed to product updates</p>
- </div>
+ <button
+ type="button"
+ onClick={() => executeAsync()}
+ disabled={isPending}
+ className={cn(
+ "group flex items-center gap-x-1 text-sm text-neutral-500 transition-colors hover:text-neutral-700",
+ isPending && "cursor-not-allowed",
+ )}
+ >
+ <span className="underline decoration-dotted underline-offset-2">
+ Manage email preferences
+ </span>{" "}
+ {isPending ? (
+ <LoadingSpinner className="size-3" />
+ ) : (
+ <ExpandingArrow className="size-3" />
+ )}
+ </button>
);
}
diff --git a/packages/email/src/components/footer.tsx b/packages/email/src/components/footer.tsx
index a653841637..5f17320ac7 100644
--- a/packages/email/src/components/footer.tsx
+++ b/packages/email/src/components/footer.tsx
@@ -3,24 +3,25 @@ import { Hr, Link, Tailwind, Text } from "@react-email/components";
export function Footer({
email,
marketing,
+ unsubscribeUrl,
notificationSettingsUrl,
}: {
email: string;
marketing?: boolean;
+ unsubscribeUrl?: string;
notificationSettingsUrl?: string;
}) {
if (marketing) {
+ const unsubscribeHref =
+ unsubscribeUrl || "https://app.dub.co/account/settings";
+
return (
<Tailwind>
<Hr className="mx-0 my-6 w-full border border-neutral-200" />
<Text className="text-[12px] leading-6 text-neutral-500">
- We send out product update emails once a month – no spam, no nonsense.
- Don't want to get these emails?{" "}
- <Link
- className="text-neutral-700 underline"
- href="https://app.dub.co/account/settings"
- >
- Unsubscribe here.
+ We send out product update emails once a month – no spam, no nonsense.{" "}
+ <Link className="text-neutral-700 underline" href={unsubscribeHref}>
+ Manage your email preferences.
</Link>
</Text>
<Text className="text-[12px] text-neutral-500">
diff --git a/packages/email/src/resend/index.ts b/packages/email/src/resend/index.ts
index 59449c6ff7..5ec76921e1 100644
--- a/packages/email/src/resend/index.ts
+++ b/packages/email/src/resend/index.ts
@@ -1,3 +1 @@
export * from "./client";
-export * from "./subscribe";
-export * from "./unsubscribe";
diff --git a/packages/email/src/resend/subscribe.ts b/packages/email/src/resend/subscribe.ts
deleted file mode 100644
index f503d57c55..0000000000
--- a/packages/email/src/resend/subscribe.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { resend } from "./client";
-import { RESEND_AUDIENCE_ID } from "./constants";
-
-export async function subscribe({
- email,
- name,
-}: {
- email: string;
- name?: string | null;
-}) {
- if (!resend) {
- console.error(
- "No RESEND_API_KEY is set in the environment variables. Skipping.",
- );
- return;
- }
-
- if (email.endsWith("@dub-internal-test.com")) {
- // don't subscribe internal test emails
- return;
- }
-
- return await resend.contacts.create({
- email,
- ...(name && {
- firstName: name.split(" ")[0],
- lastName: name.split(" ").slice(1).join(" "),
- }),
- audienceId: RESEND_AUDIENCE_ID,
- });
-}
diff --git a/packages/email/src/resend/types.ts b/packages/email/src/resend/types.ts
index 19a774feb4..88433309f1 100644
--- a/packages/email/src/resend/types.ts
+++ b/packages/email/src/resend/types.ts
@@ -5,6 +5,7 @@ export interface ResendEmailOptions
to: string;
from?: string;
variant?: "primary" | "notifications" | "marketing";
+ unsubscribeUrl?: string; // Custom unsubscribe URL for List-Unsubscribe header
}
export type ResendBulkEmailOptions = ResendEmailOptions[];
diff --git a/packages/email/src/resend/unsubscribe.ts b/packages/email/src/resend/unsubscribe.ts
deleted file mode 100644
index 324d7b47c2..0000000000
--- a/packages/email/src/resend/unsubscribe.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { resend } from "./client";
-import { RESEND_AUDIENCE_ID } from "./constants";
-
-export async function unsubscribe({ email }: { email: string }) {
- if (!resend) {
- console.error(
- "No RESEND_API_KEY is set in the environment variables. Skipping.",
- );
- return;
- }
-
- return await resend.contacts.remove({
- email,
- audienceId: RESEND_AUDIENCE_ID,
- });
-}
diff --git a/packages/email/src/send-via-resend.ts b/packages/email/src/send-via-resend.ts
index d6d1aa09c6..7d917bec3c 100644
--- a/packages/email/src/send-via-resend.ts
+++ b/packages/email/src/send-via-resend.ts
@@ -18,6 +18,7 @@ const resendEmailForOptions = (
scheduledAt,
headers,
tags,
+ unsubscribeUrl,
} = opts;
// Build base options without rendered outputs (react/text)
@@ -36,7 +37,8 @@ const resendEmailForOptions = (
? {
headers: {
...(headers || {}),
- "List-Unsubscribe": "https://app.dub.co/account/settings",
+ "List-Unsubscribe":
+ unsubscribeUrl || "https://app.dub.co/account/settings",
},
}
: headers && { headers }),
diff --git a/packages/prisma/schema/notification.prisma b/packages/prisma/schema/notification.prisma
index 418509dc4d..4e0eda561b 100644
--- a/packages/prisma/schema/notification.prisma
+++ b/packages/prisma/schema/notification.prisma
@@ -31,6 +31,19 @@ model NotificationEmail {
@@index(partnerId)
}
+model UserNotificationPreferences {
+ id String @id @default(cuid())
+ userId String @unique
+ dubLinks Boolean @default(true)
+ dubPartners Boolean @default(true)
+ partnerAccount Boolean @default(true)
+
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+
+ @@index(userId)
+}
+
+// TODO: update this to WorkspaceNotificationPreferences
model NotificationPreference {
id String @id @default(cuid())
projectUserId String @unique
diff --git a/packages/prisma/schema/schema.prisma b/packages/prisma/schema/schema.prisma
index c983648688..1d16b2fb86 100644
--- a/packages/prisma/schema/schema.prisma
+++ b/packages/prisma/schema/schema.prisma
@@ -21,31 +21,32 @@ model User {
invalidLoginAttempts Int @default(0)
lockedAt DateTime?
- createdAt DateTime @default(now())
- subscribed Boolean @default(true) // email subscription
- source String? // where the user came from
- defaultWorkspace String? // slug of the user's default workspace
- defaultPartnerId String? // the user's default partner ID
+ createdAt DateTime @default(now())
+ subscribed Boolean @default(true) // TODO: deprecrate once notificationPreferences is fully migrated
+ notificationPreferences UserNotificationPreferences?
+ source String? // where the user came from
+ defaultWorkspace String? // slug of the user's default workspace
+ defaultPartnerId String? // the user's default partner ID
// relational data
- accounts Account[]
- sessions Session[]
- projects ProjectUsers[]
- partners PartnerUser[]
- links Link[]
- dashboards Dashboard[]
- tokens Token[]
- restrictedTokens RestrictedToken[]
- oAuthCodes OAuthCode[]
- integrations Integration[] // Integrations user created in their workspace
- installedIntegrations InstalledIntegration[] // Integrations user installed in their workspace
- folders FolderUser[]
- folderAccessRequests FolderAccessRequest[]
- utmTemplates UtmTemplate[]
- payouts Payout[]
- bountySubmissions BountySubmission[]
- sentMessages Message[]
- partnerComments PartnerComment[]
- fraudEventGroups FraudEventGroup[]
+ accounts Account[]
+ sessions Session[]
+ projects ProjectUsers[]
+ partners PartnerUser[]
+ links Link[]
+ dashboards Dashboard[]
+ tokens Token[]
+ restrictedTokens RestrictedToken[]
+ oAuthCodes OAuthCode[]
+ integrations Integration[] // Integrations user created in their workspace
+ installedIntegrations InstalledIntegration[] // Integrations user installed in their workspace
+ folders FolderUser[]
+ folderAccessRequests FolderAccessRequest[]
+ utmTemplates UtmTemplate[]
+ payouts Payout[]
+ bountySubmissions BountySubmission[]
+ sentMessages Message[]
+ partnerComments PartnerComment[]
+ fraudEventGroups FraudEventGroup[]
@@index(source)
@@index(defaultWorkspace)