The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
sync partner profile and account
Pedro Ladeira12621336e4c8
diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsxindex 3505369d39..87d12e6d96 100644--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx@@ -4,6 +4,7 @@ import { hasPermission } from "@/lib/auth/partner-users/partner-user-permissionsimport { mutatePrefix } from "@/lib/swr/mutate";import usePartnerPayoutsCount from "@/lib/swr/use-partner-payouts-count";import { PartnerProps } from "@/lib/types";+import { useConfirmModal } from "@/ui/modals/confirm-modal";import { CountryCombobox } from "@/ui/partners/country-combobox";import {PartnerPlatformsForm,@@ -22,8 +23,17 @@ import {import { OG_AVATAR_URL, cn } from "@dub/utils";import { PartnerProfileType } from "@prisma/client";import { AnimatePresence, LayoutGroup, motion } from "motion/react";+import { useSession } from "next-auth/react";import { useAction } from "next-safe-action/hooks";-import { Dispatch, RefObject, SetStateAction, useEffect, useRef } from "react";+import {+ Dispatch,+ RefObject,+ SetStateAction,+ useEffect,+ useRef,+ useState,+ type ReactNode,+} from "react";import {Controller,FormProvider,@@ -44,6 +54,63 @@ type BasicInfoFormData = {companyName: string | null;};+type PendingProfileSubmit = {+ data: BasicInfoFormData;+ imageChanged: boolean;+};++function getProfileSyncCandidates({+ data,+ partner,+ user,+ imageChanged,+}: {+ data: BasicInfoFormData;+ partner?: PartnerProps;+ user?: { name?: string | null; email?: string | null; image?: string | null };+ imageChanged: boolean;+}) {+ const candidates: string[] = [];++ if (data.name !== partner?.name && data.name !== user?.name) {+ candidates.push("name");+ }++ if (data.email !== partner?.email && data.email !== user?.email) {+ candidates.push("email");+ }++ if (imageChanged && data.image !== user?.image) {+ candidates.push("image");+ }++ return candidates;+}++function buildProfileSyncDescription(candidates: string[]) {+ const lines = candidates.map((field) => {+ if (field === "name") return "Display name";+ if (field === "email") {+ return "Email (requires a confirmation email)";+ }+ return "Profile picture";+ });++ return (+ <div className="space-y-2 text-left">+ <p>+ You're updating your partner profile. These fields differ from your+ login account:+ </p>+ <ul className="list-inside list-disc">+ {lines.map((line) => (+ <li key={line}>{line}</li>+ ))}+ </ul>+ </div>+ );+}+export function ProfileDetailsForm({partner,setShowMergePartnerAccountsModal,@@ -182,18 +249,11 @@ function BasicInfoForm({}, [isSubmitSuccessful, reset, getValues]);const { profileType } = watch();+ const { data: session, update: updateSession } = useSession();+ const pendingSubmitRef = useRef<PendingProfileSubmit | null>(null);+ const [syncDescription, setSyncDescription] = useState<ReactNode>("");const { executeAsync } = useAction(updatePartnerProfileAction, {- onSuccess: async ({ data }) => {- if (data?.needsEmailVerification) {- toast.success(- "Please check your email to verify your new email address.",- );- } else {- toast.success("Your profile has been updated.");- }- mutatePrefix("/api/partner-profile");- },onError({ error }) {if (error.validationErrors) {toast.error(parseActionError(error, "Could not update your profile."));@@ -217,249 +277,331 @@ function BasicInfoForm({},});+ const saveProfile = async ({+ data,+ imageChanged,+ syncIdentity,+ }: PendingProfileSubmit & { syncIdentity: boolean }) => {+ const result = await executeAsync({+ ...data,+ username: data.username || undefined,+ image: imageChanged ? data.image : null,+ syncIdentity,+ });++ if (!result?.data) {+ return;+ }++ if (result.data.needsEmailVerification) {+ toast.success(+ "Please check your email to verify your new email address.",+ );+ } else {+ toast.success("Your profile has been updated.");+ }++ setTimeout(() => {+ mutatePrefix("/api/partner-profile");+ }, 0);++ if (syncIdentity && !result.data.needsEmailVerification) {+ await updateSession();+ }+ };++ const submitProfile = async (syncIdentity: boolean) => {+ const pending = pendingSubmitRef.current;++ if (!pending) {+ return;+ }++ try {+ await saveProfile({ ...pending, syncIdentity });+ } finally {+ pendingSubmitRef.current = null;+ }+ };++ const { setShowConfirmModal, confirmModal } = useConfirmModal({+ title: "Also update your login account?",+ description: syncDescription,+ confirmText: "Update both",+ cancelText: "Only update profile",+ onConfirm: async () => {+ await submitProfile(true);+ },+ onCancel: async () => {+ await submitProfile(false);+ },+ });+return (- <form- ref={formRef}- onKeyDown={(e) => {- if (e.key !== "Enter") return;-- const target = e.target as HTMLElement;- if (target.tagName !== "INPUT") return;-- e.preventDefault();- onSubmitAction();- }}- onSubmit={handleSubmit(async (data) => {- const imageChanged = data.image !== partner?.image;-- await executeAsync({- ...data,- username: data.username || undefined,- image: imageChanged ? data.image : null,- });- })}- >- <div className="flex flex-col gap-6">- <label>- <div className="flex items-center gap-5">- <Controller- control={control}- name="image"- render={({ field }) => (- <FileUpload- accept="images"- className="size-20 shrink-0 rounded-full border border-neutral-300 sm:size-32"- iconClassName="w-5 h-5"- previewClassName="size-20 sm:size-32 rounded-full"- variant="plain"- imageSrc={field.value || `${OG_AVATAR_URL}${partner?.name}`}- readFile- disabled={disabled}- onChange={({ src }) => field.onChange(src)}- content={null}- maxFileSizeMB={2}- targetResolution={{ width: 160, height: 160 }}- />- )}- />+ <>+ {confirmModal}+ <form+ ref={formRef}+ onKeyDown={(e) => {+ if (e.key !== "Enter") return;++ const target = e.target as HTMLElement;+ if (target.tagName !== "INPUT") return;++ e.preventDefault();+ onSubmitAction();+ }}+ onSubmit={handleSubmit(async (data) => {+ const imageChanged = data.image !== partner?.image;+ const syncCandidates = getProfileSyncCandidates({+ data,+ partner,+ user: session?.user,+ imageChanged,+ });++ if (syncCandidates.length === 0) {+ await saveProfile({+ data,+ imageChanged,+ syncIdentity: false,+ });+ return;+ }++ pendingSubmitRef.current = { data, imageChanged };+ setSyncDescription(buildProfileSyncDescription(syncCandidates));+ setShowConfirmModal(true);+ })}+ >+ <div className="flex flex-col gap-6">+ <label>+ <div className="flex items-center gap-5">+ <Controller+ control={control}+ name="image"+ render={({ field }) => (+ <FileUpload+ accept="images"+ className="size-20 shrink-0 rounded-full border border-neutral-300 sm:size-32"+ iconClassName="w-5 h-5"+ previewClassName="size-20 sm:size-32 rounded-full"+ variant="plain"+ imageSrc={field.value || `${OG_AVATAR_URL}${partner?.name}`}+ readFile+ disabled={disabled}+ onChange={({ src }) => field.onChange(src)}+ content={null}+ maxFileSizeMB={2}+ targetResolution={{ width: 160, height: 160 }}+ />+ )}+ />+ <div>+ <div+ className={cn(+ buttonVariants({ variant: "secondary" }),+ "flex h-8 w-fit cursor-pointer items-center rounded-md border px-2.5 text-xs",+ )}+ >+ Upload image+ </div>+ <p className="mt-1.5 text-xs text-neutral-500">+ Recommended size: 160x160px+ </p>+ </div>+ </div>+ </label>+ <label className="flex flex-col gap-1.5">+ <span className="text-sm font-medium text-neutral-800">+ Full name+ </span><div>- <div+ <input+ type="text"+ disabled={disabled}className={cn(- buttonVariants({ variant: "secondary" }),- "flex h-8 w-fit cursor-pointer items-center rounded-md border px-2.5 text-xs",+ "block w-full rounded-md focus:outline-none sm:text-sm",+ disabled &&+ "cursor-not-allowed bg-neutral-50 text-neutral-400",+ errors.name+ ? "border-red-300 pr-10 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500"+ : "border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:ring-neutral-500",)}- >- Upload image- </div>- <p className="mt-1.5 text-xs text-neutral-500">- Recommended size: 160x160px- </p>+ placeholder="Brendon Urie"+ {...register("name", {+ required: true,+ })}+ /></div>- </div>- </label>- <label className="flex flex-col gap-1.5">- <span className="text-sm font-medium text-neutral-800">- Full name- </span>- <div>+ </label>+ <label className="flex flex-col gap-1.5">+ <span className="text-sm font-medium text-neutral-800">Email</span><input- type="text"+ type="email"disabled={disabled}className={cn("block w-full rounded-md focus:outline-none sm:text-sm",disabled && "cursor-not-allowed bg-neutral-50 text-neutral-400",- errors.name+ errors.email? "border-red-300 pr-10 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500": "border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:ring-neutral-500",)}- placeholder="Brendon Urie"- {...register("name", {+ placeholder="[email protected]"+ {...register("email", {required: true,})}/>- </div>- </label>- <label className="flex flex-col gap-1.5">- <span className="text-sm font-medium text-neutral-800">Email</span>- <input- type="email"- disabled={disabled}- className={cn(- "block w-full rounded-md focus:outline-none sm:text-sm",- disabled && "cursor-not-allowed bg-neutral-50 text-neutral-400",- errors.email- ? "border-red-300 pr-10 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500"- : "border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:ring-neutral-500",- )}- placeholder="[email protected]"- {...register("email", {- required: true,- })}- />- </label>+ </label>- <label className="flex flex-col gap-1.5">- <span className="text-sm font-medium text-neutral-800">Username</span>- <div className="relative w-full">- <span className="pointer-events-none absolute inset-y-0 left-3 flex items-center text-sm text-neutral-400">- @+ <label className="flex flex-col gap-1.5">+ <span className="text-sm font-medium text-neutral-800">+ Username</span>- <input- type="text"- disabled={disabled}- className={cn(- "block w-full rounded-md pl-7 focus:outline-none sm:text-sm",- disabled && "cursor-not-allowed bg-neutral-50 text-neutral-400",- errors.username- ? "border-red-300 pr-10 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500"- : "border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:ring-neutral-500",- )}- placeholder={partner?.email?.split("@")[0] ?? ""}- autoCapitalize="off"- autoCorrect="off"- spellCheck={false}- pattern="^[a-z0-9]+(?:-[a-z0-9]+)*$"- minLength={3}- maxLength={30}- {...register("username")}- />- </div>- <p className="text-xs text-neutral-500">- 3–30 characters. Lowercase letters, numbers, hyphens, and- underscores only.- </p>- </label>-- <label className="flex flex-col">- <span className="text-sm font-medium text-neutral-800">Country</span>- <Controller- control={control}- name="country"- rules={{ required: true }}- render={({ field }) => (- <CountryCombobox- value={field.value || ""}- onChange={field.onChange}- disabledTooltip={- <TooltipContent- title="Your profile country is based on your current location and cannot be changed. If you need to update your country, please contact support."- cta="Contact support"- href="https://dub.co/support"- target="_blank"- />- }+ <div className="relative w-full">+ <span className="pointer-events-none absolute inset-y-0 left-3 flex items-center text-sm text-neutral-400">+ @+ </span>+ <input+ type="text"+ disabled={disabled}+ className={cn(+ "block w-full rounded-md pl-7 focus:outline-none sm:text-sm",+ disabled &&+ "cursor-not-allowed bg-neutral-50 text-neutral-400",+ errors.username+ ? "border-red-300 pr-10 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500"+ : "border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:ring-neutral-500",+ )}+ placeholder={partner?.email?.split("@")[0] ?? ""}+ autoCapitalize="off"+ autoCorrect="off"+ spellCheck={false}+ pattern="^[a-z0-9]+(?:-[a-z0-9]+)*$"+ minLength={3}+ maxLength={30}+ {...register("username")}/>- )}- />- </label>-- <label className="flex flex-col gap-1.5">- <span className="text-sm font-medium text-neutral-800">- Profile type- </span>- <DynamicTooltipWrapper- tooltipProps={{- content: disabled- ? "You don't have permission to update this field"- : undefined,- }}- >- <LayoutGroup>- <div className="w-full">- <ToggleGroup- options={[- {- value: "individual",- label: "Individual",- },- {- value: "company",- label: "Company",- },- ]}- selected={profileType}- selectAction={(option: "individual" | "company") => {- if (!disabled) {- setValue("profileType", option);- }- }}- className={cn(- "flex w-full items-center gap-0.5 rounded-lg border-neutral-300 bg-neutral-100 p-0.5",- disabled && "cursor-not-allowed",- )}- optionClassName={cn(- "h-9 flex items-center justify-center rounded-lg flex-1",- disabled && "pointer-events-none text-neutral-400",- )}- indicatorClassName="bg-white"+ </div>+ <p className="text-xs text-neutral-500">+ 3–30 characters. Lowercase letters, numbers, hyphens, and+ underscores only.+ </p>+ </label>++ <label className="flex flex-col">+ <span className="text-sm font-medium text-neutral-800">+ Country+ </span>+ <Controller+ control={control}+ name="country"+ rules={{ required: true }}+ render={({ field }) => (+ <CountryCombobox+ value={field.value || ""}+ onChange={field.onChange}+ disabledTooltip={+ <TooltipContent+ title="Your profile country is based on your current location and cannot be changed. If you need to update your country, please contact support."+ cta="Contact support"+ href="https://dub.co/support"+ target="_blank"+ />+ }/>- </div>- </LayoutGroup>- </DynamicTooltipWrapper>- </label>-- <AnimatePresence mode="popLayout">- {profileType === "company" && (- <motion.div- layout- initial={{ opacity: 0, height: 0 }}- animate={{ opacity: 1, height: "auto" }}- exit={{ opacity: 0, height: 0 }}- transition={{- type: "spring",- stiffness: 300,- damping: 30,- opacity: { duration: 0.2 },- layout: { duration: 0.3, type: "spring" },+ )}+ />+ </label>++ <label className="flex flex-col gap-1.5">+ <span className="text-sm font-medium text-neutral-800">+ Profile type+ </span>+ <DynamicTooltipWrapper+ tooltipProps={{+ content: disabled+ ? "You don't have permission to update this field"+ : undefined,}}- className="contents">- <label className="flex flex-col gap-1.5">- <span className="text-sm font-medium text-neutral-800">- Legal company name- </span>- <div>- <input- type="text"- disabled={disabled}+ <LayoutGroup>+ <div className="w-full">+ <ToggleGroup+ options={[+ {+ value: "individual",+ label: "Individual",+ },+ {+ value: "company",+ label: "Company",+ },+ ]}+ selected={profileType}+ selectAction={(option: "individual" | "company") => {+ if (!disabled) {+ setValue("profileType", option);+ }+ }}className={cn(- "block w-full rounded-md focus:outline-none sm:text-sm",- disabled &&- "cursor-not-allowed bg-neutral-50 text-neutral-400",- errors.companyName- ? "border-red-300 pr-10 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500"- : "border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:ring-neutral-500",+ "flex w-full items-center gap-0.5 rounded-lg border-neutral-300 bg-neutral-100 p-0.5",+ disabled && "cursor-not-allowed",+ )}+ optionClassName={cn(+ "h-9 flex items-center justify-center rounded-lg flex-1",+ disabled && "pointer-events-none text-neutral-400",)}- {...register("companyName", {- required: profileType === "company",- })}+ indicatorClassName="bg-white"/></div>- </label>- </motion.div>- )}- </AnimatePresence>- </div>- </form>+ </LayoutGroup>+ </DynamicTooltipWrapper>+ </label>++ <AnimatePresence mode="popLayout">+ {profileType === "company" && (+ <motion.div+ layout+ initial={{ opacity: 0, height: 0 }}+ animate={{ opacity: 1, height: "auto" }}+ exit={{ opacity: 0, height: 0 }}+ transition={{+ type: "spring",+ stiffness: 300,+ damping: 30,+ opacity: { duration: 0.2 },+ layout: { duration: 0.3, type: "spring" },+ }}+ className="contents"+ >+ <label className="flex flex-col gap-1.5">+ <span className="text-sm font-medium text-neutral-800">+ Legal company name+ </span>+ <div>+ <input+ type="text"+ disabled={disabled}+ className={cn(+ "block w-full rounded-md focus:outline-none sm:text-sm",+ disabled &&+ "cursor-not-allowed bg-neutral-50 text-neutral-400",+ errors.companyName+ ? "border-red-300 pr-10 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500"+ : "border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:ring-neutral-500",+ )}+ {...register("companyName", {+ required: profileType === "company",+ })}+ />+ </div>+ </label>+ </motion.div>+ )}+ </AnimatePresence>+ </div>+ </form>+ </>);}diff --git a/apps/web/app/api/user/route.ts b/apps/web/app/api/user/route.tsindex e8838ec396..c040378992 100644--- a/apps/web/app/api/user/route.ts+++ b/apps/web/app/api/user/route.ts@@ -1,6 +1,13 @@import { DubApiError } from "@/lib/api/errors";import { withSession } from "@/lib/auth";import { confirmEmailChange } from "@/lib/auth/confirm-email-change";+import { hasPermission } from "@/lib/auth/partner-users/partner-user-permissions";+import {+ assertEmailAvailableForIdentitySync,+ isImageReferencedByPartner,+ requestSyncedEmailChange,+ syncNameAndImageToPartner,+} from "@/lib/partners/sync-partner-identity";import { prisma } from "@/lib/prisma";import { storage } from "@/lib/storage";import { uploadedImageSchema } from "@/lib/zod/schemas/images";@@ -22,6 +29,7 @@ const updateUserSchema = z.object({image: uploadedImageSchema.nullish(),source: z.preprocess(trim, z.string().min(1).max(32)).optional(),defaultWorkspace: z.preprocess(trim, z.string().min(1)).optional(),+ syncIdentity: z.boolean().optional(),});// GET /api/user – get a specific user@@ -64,9 +72,40 @@ export const GET = withSession(async ({ session }) => {// PATCH /api/user – edit a specific userexport const PATCH = withSession(async ({ req, session }) => {- let { name, email, image, source, defaultWorkspace } =+ let { name, email, image, source, defaultWorkspace, syncIdentity } =await updateUserSchema.parseAsync(await req.json());+ const hostName = req.headers.get("host") || "";+ const isPartnersDomain = !APP_HOSTNAMES.has(hostName);+ const partnerId = session.user.defaultPartnerId;+ const shouldSyncIdentity =+ syncIdentity === true && isPartnersDomain && !!partnerId;++ if (shouldSyncIdentity && partnerId) {+ const partnerUser = await prisma.partnerUser.findUnique({+ where: {+ userId_partnerId: {+ userId: session.user.id,+ partnerId,+ },+ },+ select: {+ role: true,+ },+ });++ if (+ !partnerUser ||+ !hasPermission(partnerUser.role, "partner_profile.update")+ ) {+ throw new DubApiError({+ code: "forbidden",+ message:+ "You don't have permission to update the partner profile linked to this account.",+ });+ }+ }+if (image) {const { url } = await storage.upload({key: `avatars/${session.user.id}_${nanoid(7)}`,@@ -95,27 +134,41 @@ export const PATCH = withSession(async ({ req, session }) => {// Verify email ownership if the email is being changedif (email && email !== session.user.email) {- const userWithEmail = await prisma.user.findUnique({- where: {- email,- },- });+ if (shouldSyncIdentity && partnerId) {+ await assertEmailAvailableForIdentitySync({+ newEmail: email,+ userId: session.user.id,+ partnerId,+ });- if (userWithEmail) {- throw new DubApiError({- code: "conflict",- message: "Email is already in use.",+ await requestSyncedEmailChange({+ currentEmail: session.user.email!,+ newEmail: email,+ userId: session.user.id,+ hostName: PARTNERS_DOMAIN,+ redirectTo: "/account/settings",+ });+ } else {+ const userWithEmail = await prisma.user.findUnique({+ where: {+ email,+ },});- }- const hostName = req.headers.get("host") || "";+ if (userWithEmail) {+ throw new DubApiError({+ code: "conflict",+ message: "Email is already in use.",+ });+ }- await confirmEmailChange({- email: session.user.email,- newEmail: email,- identifier: session.user.id,- hostName: APP_HOSTNAMES.has(hostName) ? APP_DOMAIN : PARTNERS_DOMAIN,- });+ await confirmEmailChange({+ email: session.user.email,+ newEmail: email,+ identifier: session.user.id,+ hostName: APP_HOSTNAMES.has(hostName) ? APP_DOMAIN : PARTNERS_DOMAIN,+ });+ }}const response = await prisma.user.update({@@ -130,17 +183,36 @@ export const PATCH = withSession(async ({ req, session }) => {},});+ if (shouldSyncIdentity && partnerId) {+ await syncNameAndImageToPartner({+ partnerId,+ ...(name && { name }),+ ...(image && { image }),+ });+ }+waitUntil((async () => {- // Delete only if a new image is uploaded and the old image exists+ // Delete only if a new image is uploaded and the old image exists.+ // Skip if the partner profile still references the old image (e.g. user+ // chose to update login account only after a prior identity sync).if (image &&session.user.image &&session.user.image.startsWith(`${R2_URL}/avatars/${session.user.id}`)) {- await storage.delete({- key: session.user.image.replace(`${R2_URL}/`, ""),- });+ const partnerStillUsesImage =+ partnerId &&+ (await isImageReferencedByPartner({+ partnerId,+ imageUrl: session.user.image,+ }));++ if (!partnerStillUsesImage) {+ await storage.delete({+ key: session.user.image.replace(`${R2_URL}/`, ""),+ });+ }}})(),);diff --git a/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/[token]/page-client.tsx b/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/[token]/page-client.tsxindex ff28702638..ebc9107d32 100644--- a/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/[token]/page-client.tsx+++ b/apps/web/app/app.dub.co/(auth)/auth/confirm-email-change/[token]/page-client.tsx@@ -6,10 +6,12 @@ import { useRouter } from "next/navigation";import { useEffect, useRef } from "react";import { toast } from "sonner";-export default async function ConfirmEmailChangePageClient({+export default function ConfirmEmailChangePageClient({isPartnerProfile,+ redirectTo,}: {isPartnerProfile: boolean;+ redirectTo?: "/profile" | "/account/settings";}) {const router = useRouter();const { update, status } = useSession();@@ -24,11 +26,13 @@ export default async function ConfirmEmailChangePageClient({hasUpdatedSession.current = true;await update();toast.success("Successfully updated your email!");- router.replace(isPartnerProfile ? "/profile" : "/account/settings");+ router.replace(+ redirectTo ?? (isPartnerProfile ? "/profile" : "/account/settings"),+ );}updateSession();- }, [status, update]);+ }, [status, update, isPartnerProfile, redirectTo, router]);return (<EmptyStatediff --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.tsxindex 1d99a882a2..abe3911465 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@@ -85,6 +85,8 @@ const VerifyEmailChange = async ({ params, searchParams }: PageProps) => {email: string;newEmail: string;isPartnerProfile?: boolean;+ syncIdentity?: boolean;+ redirectTo?: "/profile" | "/account/settings";}>(`email-change-request:user:${identifier}`);if (!data) {@@ -97,8 +99,39 @@ const VerifyEmailChange = async ({ params, searchParams }: PageProps) => {);}+ if (data.syncIdentity) {+ if (!partnerId) {+ return (+ <EmptyState+ icon={InputPassword}+ title="No Partner Profile Found"+ description="We couldn't find a partner profile for your account. Please make sure you're logged in with the correct account at https://partners.dub.co"+ />+ );+ }++ await prisma.$transaction([+ prisma.user.update({+ where: {+ id: userId,+ },+ data: {+ email: data.newEmail,+ },+ }),+ prisma.partner.update({+ where: {+ id: partnerId,+ },+ data: {+ email: data.newEmail,+ },+ }),+ ]);+ }+// Update the partner profile email- if (data.isPartnerProfile) {+ else if (data.isPartnerProfile) {if (!partnerId) {return (<EmptyState@@ -148,7 +181,10 @@ const VerifyEmailChange = async ({ params, searchParams }: PageProps) => {);return (- <ConfirmEmailChangePageClient isPartnerProfile={!!data.isPartnerProfile} />+ <ConfirmEmailChangePageClient+ isPartnerProfile={!!data.isPartnerProfile}+ redirectTo={data.redirectTo}+ />);};diff --git a/apps/web/app/app.dub.co/(dashboard)/account/settings/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/account/settings/page-client.tsxindex 87a360dfc4..cec7518e3f 100644--- a/apps/web/app/app.dub.co/(dashboard)/account/settings/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/account/settings/page-client.tsx@@ -1,83 +1,269 @@"use client";+import { mutatePrefix } from "@/lib/swr/mutate";+import usePartnerProfile from "@/lib/swr/use-partner-profile";import DeleteAccountSection from "@/ui/account/delete-account";import UpdateDefaultWorkspace from "@/ui/account/update-default-workspace";import UpdateSubscription from "@/ui/account/update-subscription";import UploadAvatar from "@/ui/account/upload-avatar";import UserId from "@/ui/account/user-id";import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";+import { useConfirmModal } from "@/ui/modals/confirm-modal";import { Form, useCurrentSubdomain } from "@dub/ui";import { useSession } from "next-auth/react";+import { ReactNode, useRef, useState } from "react";import { toast } from "sonner";+type PendingUserPatch = {+ body: Record<string, unknown>;+ onSuccess: () => void;+};++function getAccountSyncCandidates({+ field,+ value,+ user,+ partner,+}: {+ field: "name" | "email" | "image";+ value: string | null;+ user?: { name?: string | null; email?: string | null; image?: string | null };+ partner?: {+ name?: string | null;+ email?: string | null;+ image?: string | null;+ };+}) {+ if (field === "name") {+ if (value === user?.name || value === partner?.name) {+ return [];+ }++ return ["name"];+ }++ if (field === "email") {+ if (value === user?.email || value === partner?.email) {+ return [];+ }++ return ["email"];+ }++ if (value === user?.image || value === partner?.image) {+ return [];+ }++ return ["image"];+}++function buildAccountSyncDescription(candidates: string[]) {+ const lines = candidates.map((field) => {+ if (field === "name") return "Display name";+ if (field === "email") {+ return "Email (requires a confirmation email)";+ }+ return "Profile picture";+ });++ return (+ <div className="space-y-2 text-left">+ <p>+ You're updating your login account. These fields differ from your+ partner profile:+ </p>+ <ul className="list-inside list-disc">+ {lines.map((line) => (+ <li key={line}>{line}</li>+ ))}+ </ul>+ </div>+ );+}+export function SettingsPageClient() {const { data: session, update, status } = useSession();const { subdomain } = useCurrentSubdomain();+ const isPartnerDomain = subdomain !== "app";+ const { partner } = usePartnerProfile();+ const pendingPatchRef = useRef<PendingUserPatch | null>(null);+ const [syncDescription, setSyncDescription] = useState<ReactNode>("");++ const patchUser = async (body: Record<string, unknown>) => {+ const res = await fetch("/api/user", {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(body),+ });++ if (res.status !== 200) {+ const { error } = await res.json();+ throw new Error(error.message);+ }++ const isPendingEmailChange =+ typeof body.email === "string" && body.email !== session?.user?.email;++ // Email isn't updated until the user confirms via link — skip session refresh+ if (!isPendingEmailChange) {+ await update();+ }++ if (body.syncIdentity) {+ mutatePrefix("/api/partner-profile");+ }+ };++ const finishPendingPatch = async (syncIdentity: boolean) => {+ const pending = pendingPatchRef.current;++ if (!pending) {+ return;+ }++ try {+ await patchUser({+ ...pending.body,+ syncIdentity,+ });+ pending.onSuccess();+ } catch (error) {+ toast.error(+ error instanceof Error ? error.message : "Something went wrong.",+ );+ } finally {+ pendingPatchRef.current = null;+ }+ };++ const { setShowConfirmModal, confirmModal } = useConfirmModal({+ title: "Also update your partner profile?",+ description: syncDescription,+ confirmText: "Update both",+ cancelText: "Only update login account",+ onConfirm: async () => {+ await finishPendingPatch(true);+ },+ onCancel: async () => {+ await finishPendingPatch(false);+ },+ });++ const requestSubmit = ({+ body,+ field,+ value,+ onSuccess,+ }: {+ body: Record<string, unknown>;+ field: "name" | "email" | "image";+ value: string | null;+ onSuccess: () => void;+ }): Promise<void> => {+ if (!isPartnerDomain) {+ return patchUser({ ...body, syncIdentity: false })+ .then(onSuccess)+ .catch((error) => {+ toast.error(error.message);+ })+ .then(() => undefined);+ }++ const syncCandidates = getAccountSyncCandidates({+ field,+ value,+ user: session?.user,+ partner,+ });++ if (syncCandidates.length === 0) {+ return patchUser({ ...body, syncIdentity: false })+ .then(onSuccess)+ .catch((error) => {+ toast.error(error.message);+ })+ .then(() => undefined);+ }++ pendingPatchRef.current = { body, onSuccess };+ setSyncDescription(buildAccountSyncDescription(syncCandidates));+ setShowConfirmModal(true);++ return Promise.resolve();+ };return (- <PageWidthWrapper className="mb-8 grid gap-8">- <Form- title="Your Name"- description="This is your display name on Dub."- inputAttrs={{- name: "name",- defaultValue:- status === "loading" ? undefined : session?.user?.name || "",- placeholder: "Steve Jobs",- maxLength: 32,- }}- helpText="Max 32 characters."- handleSubmit={(data) =>- fetch("/api/user", {- method: "PATCH",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(data),- }).then(async (res) => {- if (res.status === 200) {- update();- toast.success("Successfully updated your name!");- } else {- const { error } = await res.json();- toast.error(error.message);- }- })- }- />- <Form- title="Your Email"- description="This will be the email you use to log in to Dub and receive notifications. A confirmation is required for changes."- inputAttrs={{- name: "email",- type: "email",- defaultValue: session?.user?.email || undefined,- placeholder: "[email protected]",- }}- helpText={<UpdateSubscription />}- handleSubmit={(data) =>- fetch("/api/user", {- method: "PATCH",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(data),- }).then(async (res) => {- if (res.status === 200) {- toast.success(- `A confirmation email has been sent to ${data.email}.`,- );- } else {- const { error } = await res.json();- toast.error(error.message);- }- })- }- />- <UploadAvatar />- <UserId />- {subdomain === "app" && <UpdateDefaultWorkspace />}- <DeleteAccountSection />- </PageWidthWrapper>+ <>+ {isPartnerDomain && confirmModal}+ <PageWidthWrapper className="mb-8 grid gap-8">+ <Form+ title="Your Name"+ description="This is your display name on Dub."+ inputAttrs={{+ name: "name",+ defaultValue:+ status === "loading" ? undefined : session?.user?.name || "",+ placeholder: "Steve Jobs",+ maxLength: 32,+ }}+ helpText="Max 32 characters."+ handleSubmit={(data) =>+ requestSubmit({+ body: data,+ field: "name",+ value: data.name,+ onSuccess: () => {+ toast.success("Successfully updated your name!");+ },+ })+ }+ />+ <Form+ title="Your Email"+ description="This will be the email you use to log in to Dub and receive notifications. A confirmation is required for changes."+ inputAttrs={{+ name: "email",+ type: "email",+ defaultValue: session?.user?.email || undefined,+ placeholder: "[email protected]",+ }}+ helpText={<UpdateSubscription />}+ handleSubmit={(data) =>+ requestSubmit({+ body: data,+ field: "email",+ value: data.email,+ onSuccess: () => {+ toast.success(+ `A confirmation email has been sent to ${data.email}.`,+ );+ },+ })+ }+ />+ <UploadAvatar+ onSubmit={+ isPartnerDomain+ ? (image) =>+ requestSubmit({+ body: { image },+ field: "image",+ value: image,+ onSuccess: () => {+ toast.success(+ "Successfully updated your profile picture!",+ );+ },+ })+ : undefined+ }+ />+ <UserId />+ {subdomain === "app" && <UpdateDefaultWorkspace />}+ <DeleteAccountSection />+ </PageWidthWrapper>+ </>);}diff --git a/apps/web/lib/actions/partners/update-partner-profile.ts b/apps/web/lib/actions/partners/update-partner-profile.tsindex ddbe6eb04f..c6ef34dfca 100644--- a/apps/web/lib/actions/partners/update-partner-profile.ts+++ b/apps/web/lib/actions/partners/update-partner-profile.ts@@ -5,6 +5,11 @@ import { confirmEmailChange } from "@/lib/auth/confirm-email-change";import { throwIfNoPermission } from "@/lib/auth/partner-users/throw-if-no-permission";import { qstash } from "@/lib/cron";import { isReservedUsername } from "@/lib/edge-config";+import {+ assertEmailAvailableForIdentitySync,+ requestSyncedEmailChange,+ syncNameAndImageToUser,+} from "@/lib/partners/sync-partner-identity";import { prisma } from "@/lib/prisma";import { storage } from "@/lib/storage";import { ratelimit } from "@/lib/upstash";@@ -36,6 +41,7 @@ const updatePartnerProfileSchema = zdescription: z.string().max(MAX_PARTNER_DESCRIPTION_LENGTH).nullish(),profileType: z.enum(PartnerProfileType).optional(),companyName: z.string().nullish(),+ syncIdentity: z.boolean().optional(),}).extend(PartnerProfileDetailsSchema.partial().shape).transform((data) => ({@@ -60,7 +66,7 @@ const updatePartnerProfileSchema = zexport const updatePartnerProfileAction = authPartnerActionClient.inputSchema(updatePartnerProfileSchema).action(async ({ ctx, parsedInput }) => {- const { partner, partnerUser } = ctx;+ const { partner, partnerUser, user } = ctx;throwIfNoPermission({role: partnerUser.role,@@ -79,6 +85,7 @@ export const updatePartnerProfileAction = authPartnerActionClientpreferredEarningStructures,salesChannels,username,+ syncIdentity,} = parsedInput;await updatedComplianceFieldsChecks({@@ -178,29 +185,53 @@ export const updatePartnerProfileAction = authPartnerActionClient// If the email is being changed, we need to verify the new email addressif (emailChanged) {- const partnerWithEmail = await prisma.partner.findUnique({- where: {- email: newEmail,- },- });+ if (syncIdentity) {+ await assertEmailAvailableForIdentitySync({+ newEmail,+ userId: user.id,+ partnerId: partner.id,+ });++ await requestSyncedEmailChange({+ currentEmail: user.email!,+ newEmail,+ userId: user.id,+ hostName: PARTNERS_DOMAIN,+ redirectTo: "/profile",+ });+ } else {+ const partnerWithEmail = await prisma.partner.findUnique({+ where: {+ email: newEmail,+ },+ });- if (partnerWithEmail) {- throw new Error(- `Email ${newEmail} is already in use. Do you want to merge your partner accounts instead? (https://d.to/merge-partners)`,- );+ if (partnerWithEmail) {+ throw new Error(+ `Email ${newEmail} is already in use. Do you want to merge your partner accounts instead? (https://d.to/merge-partners)`,+ );+ }++ await confirmEmailChange({+ email: partner.email!,+ newEmail,+ identifier: partner.id,+ isPartnerProfile: true,+ hostName: PARTNERS_DOMAIN,+ });}- await confirmEmailChange({- email: partner.email!,- newEmail,- identifier: partner.id,- isPartnerProfile: true,- hostName: PARTNERS_DOMAIN,- });-needsEmailVerification = true;}+ if (syncIdentity) {+ await syncNameAndImageToUser({+ userId: user.id,+ ...(name && { name }),+ ...(imageUrl && { image: imageUrl }),+ });+ }+waitUntil(Promise.allSettled([(async () => {diff --git a/apps/web/lib/auth/confirm-email-change.ts b/apps/web/lib/auth/confirm-email-change.tsindex 38489c3579..fb6e1fe9dc 100644--- a/apps/web/lib/auth/confirm-email-change.ts+++ b/apps/web/lib/auth/confirm-email-change.ts@@ -13,12 +13,16 @@ export const confirmEmailChange = async ({newEmail,identifier,isPartnerProfile = false,+ syncIdentity = false,+ redirectTo,hostName,}: {email: string;newEmail: string;identifier: string;isPartnerProfile?: boolean; // If true, the email is being changed for a partner profile+ syncIdentity?: boolean; // If true, update both user and partner email on confirm+ redirectTo?: "/profile" | "/account/settings";hostName: string;}) => {const { success } = await ratelimit(3, "1 d").limit(@@ -59,6 +63,8 @@ export const confirmEmailChange = async ({email,newEmail,...(isPartnerProfile && { isPartnerProfile }),+ ...(syncIdentity && { syncIdentity }),+ ...(redirectTo && { redirectTo }),},{px: expiresIn,diff --git a/apps/web/lib/partners/sync-partner-identity.ts b/apps/web/lib/partners/sync-partner-identity.tsnew file mode 100644index 0000000000..d771a7c329--- /dev/null+++ b/apps/web/lib/partners/sync-partner-identity.ts@@ -0,0 +1,169 @@+import { DubApiError } from "@/lib/api/errors";+import { confirmEmailChange } from "@/lib/auth/confirm-email-change";+import { prisma } from "@/lib/prisma";+import { storage } from "@/lib/storage";+import { nanoid } from "@dub/utils";++export async function assertEmailAvailableForIdentitySync({+ newEmail,+ userId,+ partnerId,+}: {+ newEmail: string;+ userId: string;+ partnerId: string;+}) {+ const [userWithEmail, partnerWithEmail] = await Promise.all([+ prisma.user.findUnique({+ where: { email: newEmail },+ select: { id: true },+ }),+ prisma.partner.findUnique({+ where: { email: newEmail },+ select: { id: true },+ }),+ ]);++ if (userWithEmail && userWithEmail.id !== userId) {+ throw new DubApiError({+ code: "conflict",+ message: "Email is already in use.",+ });+ }++ if (partnerWithEmail && partnerWithEmail.id !== partnerId) {+ throw new Error(+ `Email ${newEmail} is already in use. Do you want to merge your partner accounts instead? (https://d.to/merge-partners)`,+ );+ }+}++async function copyImageToPartnerStorage({+ partnerId,+ imageUrl,+}: {+ partnerId: string;+ imageUrl: string;+}) {+ const { url } = await storage.upload({+ key: `partners/${partnerId}/image_${nanoid(7)}`,+ body: imageUrl,+ });++ return url;+}++async function copyImageToUserStorage({+ userId,+ imageUrl,+}: {+ userId: string;+ imageUrl: string;+}) {+ const { url } = await storage.upload({+ key: `avatars/${userId}_${nanoid(7)}`,+ body: imageUrl,+ });++ return url;+}++export async function syncNameAndImageToPartner({+ partnerId,+ name,+ image,+}: {+ partnerId: string;+ name?: string;+ image?: string | null;+}) {+ if (!name && !image) {+ return;+ }++ let partnerImage = image;++ if (image) {+ partnerImage = await copyImageToPartnerStorage({+ partnerId,+ imageUrl: image,+ });+ }++ await prisma.partner.update({+ where: { id: partnerId },+ data: {+ ...(name && { name }),+ ...(partnerImage && { image: partnerImage }),+ },+ });+}++export async function syncNameAndImageToUser({+ userId,+ name,+ image,+}: {+ userId: string;+ name?: string;+ image?: string | null;+}) {+ if (!name && !image) {+ return;+ }++ let userImage = image;++ if (image) {+ userImage = await copyImageToUserStorage({ userId, imageUrl: image });+ }++ await prisma.user.update({+ where: { id: userId },+ data: {+ ...(name && { name }),+ ...(userImage && { image: userImage }),+ },+ });+}++export async function isImageReferencedByPartner({+ partnerId,+ imageUrl,+}: {+ partnerId: string;+ imageUrl: string;+}) {+ const partner = await prisma.partner.findFirst({+ where: {+ id: partnerId,+ image: imageUrl,+ },+ select: { id: true },+ });++ return !!partner;+}++export async function requestSyncedEmailChange({+ currentEmail,+ newEmail,+ userId,+ hostName,+ redirectTo,+}: {+ currentEmail: string;+ newEmail: string;+ userId: string;+ hostName: string;+ redirectTo: "/profile" | "/account/settings";+}) {+ await confirmEmailChange({+ email: currentEmail,+ newEmail,+ identifier: userId,+ hostName,+ syncIdentity: true,+ redirectTo,+ });+}diff --git a/apps/web/ui/account/upload-avatar.tsx b/apps/web/ui/account/upload-avatar.tsxindex 7bfa32b002..81e79f03ff 100644--- a/apps/web/ui/account/upload-avatar.tsx+++ b/apps/web/ui/account/upload-avatar.tsx@@ -6,7 +6,11 @@ import { useSession } from "next-auth/react";import { useEffect, useState } from "react";import { toast } from "sonner";-export default function UploadAvatar() {+export default function UploadAvatar({+ onSubmit,+}: {+ onSubmit?: (image: string | null) => Promise<void> | void;+}) {const { data: session, update } = useSession();const [image, setImage] = useState<string | null>(null);@@ -24,22 +28,34 @@ export default function UploadAvatar() {onSubmit={async (e) => {setUploading(true);e.preventDefault();- fetch("/api/user", {- method: "PATCH",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({ image }),- }).then(async (res) => {- setUploading(false);- if (res.status === 200) {- await update();- toast.success("Successfully updated your profile picture!");++ try {+ if (onSubmit) {+ await onSubmit(image);} else {- const { error } = await res.json();- toast.error(error.message);+ const res = await fetch("/api/user", {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ image }),+ });++ if (res.status === 200) {+ await update();+ toast.success("Successfully updated your profile picture!");+ } else {+ const { error } = await res.json();+ toast.error(error.message);+ }}- });+ } catch (error) {+ toast.error(+ error instanceof Error ? error.message : "Something went wrong.",+ );+ } finally {+ setUploading(false);+ }}}className="rounded-xl border border-neutral-200 bg-white">diff --git a/apps/web/ui/modals/confirm-modal.tsx b/apps/web/ui/modals/confirm-modal.tsxindex 1ffaf1181c..fc0791cefc 100644--- a/apps/web/ui/modals/confirm-modal.tsx+++ b/apps/web/ui/modals/confirm-modal.tsx@@ -76,9 +76,14 @@ function ConfirmModal({variant="secondary"className="h-8 w-fit"text={cancelText}- onClick={() => {- onCancel?.();- setShowConfirmModal(false);+ onClick={async () => {+ setIsLoading(true);+ try {+ await onCancel?.();+ setShowConfirmModal(false);+ } finally {+ setIsLoading(false);+ }}}/><Button