The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
mergePartnerAccountsAction
Kiran K26eb9e6b543c
diff --git a/apps/web/lib/actions/partners/merge-partner-accounts.ts b/apps/web/lib/actions/partners/merge-partner-accounts.tsindex 37dcf3efab..fea480fd6d 100644--- a/apps/web/lib/actions/partners/merge-partner-accounts.ts+++ b/apps/web/lib/actions/partners/merge-partner-accounts.ts@@ -1,18 +1,29 @@"use server";+import { EMAIL_OTP_EXPIRY_IN } from "@/lib/auth/constants";+import { generateOTP } from "@/lib/auth/utils";+import { redis } from "@/lib/upstash";+import { emailSchema } from "@/lib/zod/schemas/auth";+import { resend } from "@dub/email/resend";+import { VARIANT_TO_FROM_MAP } from "@dub/email/resend/constants";+import { prisma } from "@dub/prisma";+import { waitUntil } from "@vercel/functions";import { z } from "zod";import { authPartnerActionClient } from "../safe-action";+const CACHE_KEY_PREFIX = "merge-partner-accounts";+const CACHE_EXPIRY_IN = 10 * 60;+const sendTokensSchema = z.object({step: z.literal("send-tokens"),- sourceEmail: z.string().email().min(1),- targetEmail: z.string().email().min(1),+ sourceEmail: emailSchema,+ targetEmail: emailSchema,});const verifyTokensSchema = z.object({step: z.literal("verify-tokens"),- sourceEmail: z.string().email().min(1),- targetEmail: z.string().email().min(1),+ sourceEmail: emailSchema,+ targetEmail: emailSchema,sourceCode: z.string().min(1),targetCode: z.string().min(1),});@@ -37,9 +48,14 @@ export const mergePartnerAccountsAction = authPartnerActionClientcase "send-tokens":return await sendTokens(parsedInput);case "verify-tokens":- return await verifyTokens(parsedInput);+ return await verifyTokens({+ ...parsedInput,+ userId: user.id,+ });case "merge-accounts":- return await mergeAccounts();+ return await mergeAccounts({+ userId: user.id,+ });default:throw new Error(`Unknown step: ${step}.`);}@@ -53,7 +69,89 @@ const sendTokens = async ({sourceEmail: string;targetEmail: string;}) => {- //+ if (sourceEmail === targetEmail) {+ throw new Error("Source and target emails cannot be the same.");+ }++ const partnerAccounts = await prisma.partner.findMany({+ where: {+ email: {+ in: [sourceEmail, targetEmail],+ },+ },+ select: {+ id: true,+ email: true,+ },+ });++ if (partnerAccounts.length === 0) {+ throw new Error(+ "One or both partner accounts not found. Please check the emails you entered.",+ );+ }++ const sourceAccount = partnerAccounts.find(+ (account) => account?.email === sourceEmail,+ );++ const targetAccount = partnerAccounts.find(+ (account) => account?.email === targetEmail,+ );++ if (!sourceAccount || !targetAccount) {+ throw new Error(+ "One or both partner accounts not found. Please check the emails you entered.",+ );+ }++ await prisma.emailVerificationToken.deleteMany({+ where: {+ identifier: {+ in: [sourceEmail, targetEmail],+ },+ },+ });++ const sourceEmailCode = generateOTP();+ const targetEmailCode = generateOTP();+ const expires = new Date(Date.now() + EMAIL_OTP_EXPIRY_IN * 1000);++ await prisma.emailVerificationToken.createMany({+ data: [+ {+ identifier: sourceEmail,+ token: sourceEmailCode,+ expires,+ },+ {+ identifier: targetEmail,+ token: targetEmailCode,+ expires,+ },+ ],+ });++ if (!resend) {+ throw new Error("Resend is not configured.");+ }++ waitUntil(+ resend.batch.send([+ {+ from: VARIANT_TO_FROM_MAP.notifications,+ to: sourceEmail,+ subject: "Verify your email to merge your Dub Partners accounts",+ react: "",+ },+ {+ from: VARIANT_TO_FROM_MAP.notifications,+ to: targetEmail,+ subject: "Connect your payout details on Dub Partners",+ react: "",+ },+ ]),+ );};// Step 2: Verify email verification tokens@@ -62,16 +160,83 @@ const verifyTokens = async ({targetEmail,sourceCode,targetCode,+ userId,}: {sourceEmail: string;targetEmail: string;sourceCode: string;targetCode: string;+ userId: string;}) => {- // TODO: Implement+ const tokens = await prisma.emailVerificationToken.findMany({+ where: {+ identifier: {+ in: [sourceEmail, targetEmail],+ },+ },+ });++ if (tokens.length === 0) {+ throw new Error(+ "That code doesn’t match our records. Please double-check it and enter it again.",+ );+ }++ const sourceToken = tokens.find((token) => token.identifier === sourceEmail);++ if (sourceToken?.token !== sourceCode) {+ throw new Error(+ "The code entered for the source email does not match. Please double-check it and enter it again.",+ );+ }++ const targetToken = tokens.find((token) => token.identifier === targetEmail);++ if (targetToken?.token !== targetCode) {+ throw new Error(+ "The code entered for the target email does not match. Please double-check it and enter it again.",+ );+ }++ await prisma.emailVerificationToken.deleteMany({+ where: {+ identifier: {+ in: [sourceEmail, targetEmail],+ },+ },+ });++ await redis.set(+ `${CACHE_KEY_PREFIX}:${userId}`,+ {+ sourceEmail,+ targetEmail,+ },+ {+ ex: CACHE_EXPIRY_IN,+ },+ );};// Step 3: Merge partner accounts-const mergeAccounts = async () => {- // TODO: Implement+const mergeAccounts = async ({ userId }: { userId: string }) => {+ const accountInfo = await redis.get<{+ sourceEmail: string;+ targetEmail: string;+ }>(`${CACHE_KEY_PREFIX}:${userId}`);++ if (!accountInfo) {+ throw new Error(+ "The verification process has been expired. Please restart the process again from the beginning.",+ );+ }++ if (!accountInfo.sourceEmail || !accountInfo.targetEmail) {+ throw new Error("Unknown error occurred. Please try again.");+ }++ const { sourceEmail, targetEmail } = accountInfo;++ // TODO:+ // Do the real work here};diff --git a/apps/web/lib/auth/utils.ts b/apps/web/lib/auth/utils.tsindex 2b21ef8efa..405ecf8c04 100644--- a/apps/web/lib/auth/utils.ts+++ b/apps/web/lib/auth/utils.ts@@ -41,7 +41,5 @@ export function generateOTP() {const randomNumber = Math.floor(Math.random() * 1000000);// Pad the number with leading zeros if necessary to ensure it is always 6 digits- const otp = randomNumber.toString().padStart(6, "0");-- return otp;+ return randomNumber.toString().padStart(6, "0");}