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.

Handle unsubscribes

Steven Tey6b9a74a22cf3
diff --git a/apps/web/.env.example b/apps/web/.env.example
index 6265ece699..1e1557a8f4 100644
--- a/apps/web/.env.example
+++ b/apps/web/.env.example
@@ -97,7 +97,4 @@ NGROK_URL=
NEXT_PUBLIC_IS_DUB=
# For cron jobs
-CRON_SECRET=
-
-# For marketing emails
-RESEND_AUDIENCE_ID=
\ No newline at end of file
+CRON_SECRET=
\ No newline at end of file
diff --git a/apps/web/app/admin.dub.co/actions.ts b/apps/web/app/admin.dub.co/actions.ts
index 4bf8a7764d..eefc01b6bf 100644
--- a/apps/web/app/admin.dub.co/actions.ts
+++ b/apps/web/app/admin.dub.co/actions.ts
@@ -192,16 +192,6 @@ export async function banUser(data: FormData) {
cloudinary.v2.uploader.destroy(`avatars/${user.id}`, {
invalidate: true,
}),
- fetch(
- `https://api.resend.com/audiences/${process.env.RESEND_AUDIENCE_ID}/contacts/${user.email}`,
- {
- method: "DELETE",
- headers: {
- Authorization: `Bearer ${process.env.RESEND_API_KEY}`,
- "Content-Type": "application/json",
- },
- },
- ),
fetch(
`https://api.vercel.com/v1/edge-config/${process.env.EDGE_CONFIG_ID}/items?teamId=${process.env.TEAM_ID_VERCEL}`,
{
diff --git a/apps/web/app/api/user/route.ts b/apps/web/app/api/user/route.ts
index f02cb7047e..8ca8e3fb9a 100644
--- a/apps/web/app/api/user/route.ts
+++ b/apps/web/app/api/user/route.ts
@@ -75,16 +75,6 @@ export const DELETE = withSession(async ({ session }) => {
cloudinary.v2.uploader.destroy(`avatars/${session?.user?.id}`, {
invalidate: true,
}),
- fetch(
- `https://api.resend.com/audiences/${process.env.RESEND_AUDIENCE_ID}/contacts/${session?.user?.email}`,
- {
- method: "DELETE",
- headers: {
- Authorization: `Bearer ${process.env.RESEND_API_KEY}`,
- "Content-Type": "application/json",
- },
- },
- ),
]);
return NextResponse.json(response);
}
diff --git a/apps/web/app/api/user/subscribe/route.ts b/apps/web/app/api/user/subscribe/route.ts
new file mode 100644
index 0000000000..fcd3784afa
--- /dev/null
+++ b/apps/web/app/api/user/subscribe/route.ts
@@ -0,0 +1,53 @@
+import { withSession } from "@/lib/auth";
+import prisma from "@/lib/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: {
+ subscribed: true,
+ },
+ });
+
+ if (!user) {
+ return new Response("User not found", { status: 404 });
+ }
+
+ return NextResponse.json({
+ subscribed: user.subscribed,
+ });
+});
+
+// POST /api/user/subscribe – subscribe a specific user
+export const POST = withSession(async ({ session }) => {
+ const user = await prisma.user.update({
+ where: {
+ id: session.user.id,
+ },
+ data: {
+ subscribed: true,
+ },
+ });
+ return NextResponse.json({
+ subscribed: user.subscribed,
+ });
+});
+
+// DELETE /api/user/subscribe – unsubscribe a specific user
+export const DELETE = withSession(async ({ session }) => {
+ const user = await prisma.user.update({
+ where: {
+ id: session.user.id,
+ },
+ data: {
+ subscribed: false,
+ },
+ });
+ return NextResponse.json({
+ subscribed: user.subscribed,
+ });
+});
diff --git a/apps/web/app/app.dub.co/(auth)/auth/saml/page.tsx b/apps/web/app/app.dub.co/(auth)/auth/saml/page.tsx
index 32877936f0..f0de848c08 100644
--- a/apps/web/app/app.dub.co/(auth)/auth/saml/page.tsx
+++ b/apps/web/app/app.dub.co/(auth)/auth/saml/page.tsx
@@ -1,4 +1,5 @@
import { LoadingSpinner } from "@dub/ui";
+import { APP_NAME } from "@dub/utils";
import { Suspense } from "react";
import SAMLIDPForm from "./form";
@@ -11,7 +12,7 @@ export default function SAMLPage() {
<div className="flex h-screen flex-col items-center justify-center space-y-6 text-center">
<h1 className="font-display text-4xl font-bold">Authenticating</h1>
<p className="text-lg text-gray-600">
- {process.env.NEXT_PUBLIC_APP_NAME} is verifying your identity.
+ {APP_NAME} is verifying your identity.
<br /> Please wait...
</p>
<LoadingSpinner className="h-7 w-7" />
diff --git a/apps/web/app/app.dub.co/(auth)/settings/unsubscribe/form.tsx b/apps/web/app/app.dub.co/(auth)/settings/unsubscribe/form.tsx
new file mode 100644
index 0000000000..ec84c09c59
--- /dev/null
+++ b/apps/web/app/app.dub.co/(auth)/settings/unsubscribe/form.tsx
@@ -0,0 +1,30 @@
+"use client";
+
+import { LoadingSpinner, Logo } from "@dub/ui";
+import { APP_NAME, HOME_DOMAIN } from "@dub/utils";
+import Link from "next/link";
+import { useEffect, useState } from "react";
+
+export default function UnsubscribeForm() {
+ const [unsubscribing, setUnsubscribing] = useState(true);
+
+ useEffect(() => {
+ fetch("/api/user/subscribe", {
+ method: "DELETE",
+ }).then(() => setUnsubscribing(false));
+ }, []);
+
+ return (
+ <div className="flex h-screen max-w-xs flex-col items-center justify-center space-y-6 text-center">
+ <Link href={HOME_DOMAIN} target="_blank">
+ <Logo className="h-12 w-12" />
+ </Link>
+ <p className="text-lg text-gray-600">
+ {unsubscribing
+ ? `Unsubscribing you from all ${APP_NAME} marketing emails...`
+ : `You have been unsubscribed from all ${APP_NAME} marketing emails`}
+ </p>
+ {unsubscribing && <LoadingSpinner className="h-7 w-7" />}
+ </div>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(auth)/settings/unsubscribe/page.tsx b/apps/web/app/app.dub.co/(auth)/settings/unsubscribe/page.tsx
new file mode 100644
index 0000000000..55c051d488
--- /dev/null
+++ b/apps/web/app/app.dub.co/(auth)/settings/unsubscribe/page.tsx
@@ -0,0 +1,10 @@
+import { Suspense } from "react";
+import UnsubscribeForm from "./form";
+
+export default function UnsubscribePage() {
+ return (
+ <Suspense>
+ <UnsubscribeForm />
+ </Suspense>
+ );
+}
diff --git a/apps/web/emails/components/footer.tsx b/apps/web/emails/components/footer.tsx
index 19810f5abc..d3caf67f70 100644
--- a/apps/web/emails/components/footer.tsx
+++ b/apps/web/emails/components/footer.tsx
@@ -16,7 +16,10 @@ export default function Footer({
<span className="text-black">{email}</span>. If you were not expecting
this email, you can ignore this email. If you don't want to receive
emails like this in the future, you can{" "}
- <a href="{{{RESEND_UNSUBSCRIBE_URL}}}" className="text-gray-600">
+ <a
+ href="https://app.dub.co/settings/unsubscribe"
+ className="text-gray-600"
+ >
unsubscribe here
</a>
.
diff --git a/apps/web/lib/auth/options.ts b/apps/web/lib/auth/options.ts
index 862e9cef19..91fe081c4d 100644
--- a/apps/web/lib/auth/options.ts
+++ b/apps/web/lib/auth/options.ts
@@ -327,32 +327,15 @@ export const authOptions: NextAuthOptions = {
new Date(user.createdAt).getTime() > Date.now() - 10000 &&
process.env.NEXT_PUBLIC_IS_DUB
) {
- await Promise.allSettled([
- fetch(
- `https://api.resend.com/audiences/${process.env.RESEND_AUDIENCE_ID}/contacts`,
- {
- method: "POST",
- headers: {
- Authorization: `Bearer ${process.env.RESEND_API_KEY}`,
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- email,
- first_name: user.name?.split(" ")[0] || null,
- last_name: user.name?.split(" ")[1] || null,
- }),
- },
- ),
- sendEmail({
- subject: "Welcome to Dub.co!",
+ await sendEmail({
+ subject: "Welcome to Dub.co!",
+ email,
+ react: WelcomeEmail({
email,
- react: WelcomeEmail({
- email,
- name: user.name || null,
- }),
- marketing: true,
+ name: user.name || null,
}),
- ]);
+ marketing: true,
+ });
}
}
},
diff --git a/apps/web/package.json b/apps/web/package.json
index d2d32bacc5..e815c6057a 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -3,7 +3,7 @@
"private": true,
"license": "AGPL-3.0-or-later",
"scripts": {
- "dev": "concurrently --kill-others \"prisma generate && next dev --port 8888\" \"prisma studio --browser none\" \"email dev --port 3333\"",
+ "dev": "concurrently --kill-others \"prisma generate && next dev --port 8888\" \"prisma generate && prisma studio --browser none\" \"email dev --port 3333\"",
"build": "prisma generate & next build",
"format": "prettier --write \"**/*.{ts,tsx,md}\"",
"lint": "next lint",
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index 608c6f4152..a454e0f9a8 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -19,28 +19,29 @@ model User {
emailVerified DateTime?
image String?
- accounts Account[]
- sessions Session[]
- projects ProjectUsers[]
- links Link[]
- tokens Token[]
- createdAt DateTime @default(now())
+ accounts Account[]
+ sessions Session[]
+ projects ProjectUsers[]
+ links Link[]
+ tokens Token[]
+ createdAt DateTime @default(now())
+ subscribed Boolean @default(true)
}
model Account {
- id String @id @default(cuid())
- userId String
- type String
- provider String
- providerAccountId String
- refresh_token String? @db.Text
- refresh_token_expires_in Int?
- access_token String? @db.Text
- expires_at Int?
- token_type String?
- scope String?
- id_token String? @db.Text
- session_state String?
+ id String @id @default(cuid())
+ userId String
+ type String
+ provider String
+ providerAccountId String
+ refresh_token String? @db.Text
+ refresh_token_expires_in Int?
+ access_token String? @db.Text
+ expires_at Int?
+ token_type String?
+ scope String?
+ id_token String? @db.Text
+ session_state String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@ -67,48 +68,48 @@ model VerificationToken {
}
model Token {
- id String @id @default(cuid())
- name String
- hashedKey String @unique
+ id String @id @default(cuid())
+ name String
+ hashedKey String @unique
partialKey String
- expires DateTime?
- lastUsed DateTime?
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
- userId String
+ expires DateTime?
+ lastUsed DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ userId String
@@index([userId])
}
model Project {
- id String @id @default(cuid())
- name String
- slug String @unique
- logo String?
-
- plan String @default("free")
- stripeId String? @unique // Stripe subscription ID
- billingCycleStart Int // day of the month when the billing cycle starts
- usage Int @default(0)
- usageLimit Int @default(1000)
- linksUsage Int @default(0)
- linksLimit Int @default(25)
- domainsLimit Int @default(3)
- tagsLimit Int @default(5)
- usersLimit Int @default(1)
- monitoringId String? @unique // cron job ID for monitoring
-
- users ProjectUsers[]
- invites ProjectInvite[]
- sentEmails SentEmail[]
- links Link[]
- domains Domain[]
- tags Tag[]
-
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- metadata Json? @default("{\"defaultDomains\":[\"dub.sh\",\"chatg.pt\",\"spti.fi\",\"amzn.id\"]}")
+ id String @id @default(cuid())
+ name String
+ slug String @unique
+ logo String?
+
+ plan String @default("free")
+ stripeId String? @unique // Stripe subscription ID
+ billingCycleStart Int // day of the month when the billing cycle starts
+ usage Int @default(0)
+ usageLimit Int @default(1000)
+ linksUsage Int @default(0)
+ linksLimit Int @default(25)
+ domainsLimit Int @default(3)
+ tagsLimit Int @default(5)
+ usersLimit Int @default(1)
+ monitoringId String? @unique // cron job ID for monitoring
+
+ users ProjectUsers[]
+ invites ProjectInvite[]
+ sentEmails SentEmail[]
+ links Link[]
+ domains Domain[]
+ tags Tag[]
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ metadata Json? @default("{\"defaultDomains\":[\"dub.sh\",\"chatg.pt\",\"spti.fi\",\"amzn.id\"]}")
}
model ProjectInvite {
@@ -129,7 +130,7 @@ enum Role {
model ProjectUsers {
id String @id @default(cuid())
- role Role @default(member)
+ role Role @default(member)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@ -142,33 +143,33 @@ model ProjectUsers {
}
model SentEmail {
- id String @id @default(cuid())
+ id String @id @default(cuid())
type String
- createdAt DateTime @default(now())
- project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ createdAt DateTime @default(now())
+ project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)
projectId String?
@@index([projectId])
}
model Domain {
- id String @id @default(cuid())
- slug String @unique
- verified Boolean @default(false)
- target String?
- type String @default("redirect")
- placeholder String @default("https://dub.co/help/article/what-is-dub")
- description String?
- project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)
- projectId String?
- primary Boolean @default(false)
- archived Boolean @default(false)
- links Link[]
- clicks Int @default(0)
- lastClicked DateTime? // when the link was last clicked
- lastChecked DateTime @default(now())
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ id String @id @default(cuid())
+ slug String @unique
+ verified Boolean @default(false)
+ target String?
+ type String @default("redirect")
+ placeholder String @default("https://dub.co/help/article/what-is-dub")
+ description String?
+ project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ projectId String?
+ primary Boolean @default(false)
+ archived Boolean @default(false)
+ links Link[]
+ clicks Int @default(0)
+ lastClicked DateTime? // when the link was last clicked
+ lastChecked DateTime @default(now())
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
@@index(projectId)
@@index(clicks(sort: Desc))
@@ -198,12 +199,12 @@ model Link {
utm_content String? // UTM content for the link (e.g. description)
// Link cloaking/masking via rewrite
- rewrite Boolean @default(false) // whether to rewrite the link or not
+ rewrite Boolean @default(false) // whether to rewrite the link or not
// Custom device targeting
ios String? @db.LongText // custom link for iOS devices
android String? @db.LongText // custom link for Android devices
- geo Json? @db.Json // custom link for specific countries
+ geo Json? @db.Json // custom link for specific countries
// User who created the link
user User? @relation(fields: [userId], references: [id])
@@ -215,19 +216,19 @@ model Link {
// Relational reference to the project domain
projectDomain Domain? @relation(fields: [domain], references: [slug], onUpdate: Cascade, onDelete: Cascade)
- publicStats Boolean @default(false) // whether to show public stats or not
- clicks Int @default(0) // number of clicks
+ publicStats Boolean @default(false) // whether to show public stats or not
+ clicks Int @default(0) // number of clicks
lastClicked DateTime? // when the link was last clicked
- checkDisabled Boolean @default(false) // disable 404 checking
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ checkDisabled Boolean @default(false) // disable 404 checking
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
// Link tags
tag Tag? @relation(fields: [tagId], references: [id])
tagId String?
// Comments on the particular shortlink
- comments String? @db.LongText
+ comments String? @db.LongText
// TODO: might wanna add indices for utm_source, utm_medium, utm_campaign
@@ -269,13 +270,13 @@ model jackson_index {
}
model jackson_store {
- key String @id @db.VarChar(250)
- value String @db.Text
- iv String? @db.VarChar(64)
- tag String? @db.VarChar(64)
- namespace String? @db.VarChar(64)
- createdAt DateTime @default(now()) @db.Timestamp(0)
- modifiedAt DateTime? @db.Timestamp(0)
+ key String @id @db.VarChar(250)
+ value String @db.Text
+ iv String? @db.VarChar(64)
+ tag String? @db.VarChar(64)
+ namespace String? @db.VarChar(64)
+ createdAt DateTime @default(now()) @db.Timestamp(0)
+ modifiedAt DateTime? @db.Timestamp(0)
@@index([namespace], map: "_jackson_store_namespace")
}
@@ -285,4 +286,4 @@ model jackson_ttl {
expiresAt BigInt
@@index([expiresAt], map: "_jackson_ttl_expires_at")
-}
\ No newline at end of file
+}
diff --git a/apps/web/scripts/get-users.ts b/apps/web/scripts/get-users.ts
deleted file mode 100644
index 6a6bc0cbd5..0000000000
--- a/apps/web/scripts/get-users.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import prisma from "@/lib/prisma";
-import "dotenv-flow/config";
-import fs from "fs";
-
-async function main() {
- const unsubscribedUsers = await fetch(
- `https://api.resend.com/audiences/${process.env.RESEND_AUDIENCE_ID}/contacts`,
- {
- method: "GET",
- headers: {
- Authorization: `Bearer ${process.env.RESEND_API_KEY}`,
- "Content-Type": "application/json",
- },
- },
- ).then((res) => res.json());
-
- const unsubscribedUserEmails = unsubscribedUsers.data.map(
- (user) => user.email,
- );
-
- const users = await prisma.user.findMany({
- select: {
- email: true,
- name: true,
- createdAt: true,
- },
- where: {
- email: {
- notIn: unsubscribedUserEmails,
- },
- },
- });
- const processedUsers = users.map(({ email, name, createdAt }) => ({
- email,
- firstName: name?.split(" ")[0] || "",
- lastName: name?.split(" ")[1] || "",
- createdAt: createdAt.toISOString(),
- }));
-
- // write to csv file, with headers
- const csv = [
- ["Email", "First Name", "Last Name", "Joined"].join(","),
- ...processedUsers.map(({ email, firstName, lastName, createdAt }) =>
- [email, firstName, lastName, createdAt].join(","),
- ),
- ].join("\n");
- fs.writeFileSync("users.csv", csv);
-}
-
-main();
diff --git a/apps/web/scripts/unsubscribe.ts b/apps/web/scripts/unsubscribe.ts
new file mode 100644
index 0000000000..4fc7b98a1d
--- /dev/null
+++ b/apps/web/scripts/unsubscribe.ts
@@ -0,0 +1,34 @@
+import prisma from "@/lib/prisma";
+import "dotenv-flow/config";
+import * as fs from "fs";
+import * as Papa from "papaparse";
+
+const emails: string[] = [];
+
+async function main() {
+ Papa.parse(fs.createReadStream("unsubscribed.csv", "utf-8"), {
+ header: true,
+ skipEmptyLines: true,
+ step: (result: { data: { email: string } }) => {
+ emails.push(result.data.email);
+ },
+ complete: async () => {
+ console.log(emails.length);
+
+ const response = await prisma.user.updateMany({
+ where: {
+ email: {
+ in: emails,
+ },
+ },
+ data: {
+ subscribed: false,
+ },
+ });
+
+ console.log(response);
+ },
+ });
+}
+
+main();