Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -205,8 +205,14 @@ function ProfileForm({
const { handleKeyDown } = useEnterSubmit();

const { executeAsync } = useAction(updatePartnerProfileAction, {
onSuccess: async () => {
toast.success("Profile updated successfully.");
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.");
}
},
onError({ error }) {
setError("root.serverError", {
Expand Down
61 changes: 8 additions & 53 deletions apps/web/app/api/user/route.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { DubApiError } from "@/lib/api/errors";
import { hashToken, withSession } from "@/lib/auth";
import { withSession } from "@/lib/auth";
import { confirmEmailChange } from "@/lib/auth/confirm-email-change";
import { storage } from "@/lib/storage";
import { ratelimit, redis } from "@/lib/upstash";
import { uploadedImageSchema } from "@/lib/zod/schemas/misc";
import { sendEmail } from "@dub/email";
import { unsubscribe } from "@dub/email/resend/unsubscribe";
import ConfirmEmailChange from "@dub/email/templates/confirm-email-change";
import { prisma } from "@dub/prisma";
import {
APP_DOMAIN,
Expand All @@ -16,7 +14,6 @@ import {
trim,
} from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { randomBytes } from "crypto";
import { NextResponse } from "next/server";
import { z } from "zod";

Expand Down Expand Up @@ -113,56 +110,14 @@ export const PATCH = withSession(async ({ req, session }) => {
});
}

const { success } = await ratelimit(10, "1 d").limit(
`email-change-request:${session.user.id}`,
);

if (!success) {
throw new DubApiError({
code: "rate_limit_exceeded",
message:
"You've requested too many email change requests. Please try again later.",
});
}

const token = randomBytes(32).toString("hex");
const expiresIn = 15 * 60 * 1000;

await prisma.verificationToken.create({
data: {
identifier: session.user.id,
token: await hashToken(token, { secret: true }),
expires: new Date(Date.now() + expiresIn),
},
});

await redis.set(
`email-change-request:user:${session.user.id}`,
{
email: session.user.email,
newEmail: email,
},
{
px: expiresIn,
},
);

const hostName = req.headers.get("host") || "";
const confirmUrl = APP_HOSTNAMES.has(hostName)
? `${APP_DOMAIN}/auth/confirm-email-change/${token}`
: `${PARTNERS_DOMAIN}/auth/confirm-email-change/${token}`;

waitUntil(
sendEmail({
subject: "Confirm your email address change",
email,
react: ConfirmEmailChange({
email: session.user.email,
newEmail: email,
confirmUrl,
}),
}),
);
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({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ import { useRouter } from "next/navigation";
import { useEffect, useRef } from "react";
import { toast } from "sonner";

export default async function ConfirmEmailChangePageClient() {
export default async function ConfirmEmailChangePageClient({
isPartnerProfile,
}: {
isPartnerProfile: boolean;
}) {
const router = useRouter();
const { update, status } = useSession();
const hasUpdatedSession = useRef(false);
Expand All @@ -20,7 +24,7 @@ export default async function ConfirmEmailChangePageClient() {
hasUpdatedSession.current = true;
await update();
toast.success("Successfully updated your email!");
router.replace("/account/settings");
router.replace(isPartnerProfile ? "/profile" : "/account/settings");
}

updateSession();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ 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 { VerificationToken } from "@dub/prisma/client";
import { User, VerificationToken } from "@dub/prisma/client";
import { InputPassword, LoadingSpinner } from "@dub/ui";
import { waitUntil } from "@vercel/functions";
import { redirect } from "next/navigation";
Expand Down Expand Up @@ -80,12 +80,17 @@ const VerifyEmailChange = async ({
redirect(`/login?next=/auth/confirm-email-change/${token}`);
}

const currentUserId = session.user.id;
const { id: userId, defaultPartnerId: partnerId } = session.user;

const identifier = tokenFound.identifier.startsWith("pn_")
? partnerId
: userId;

const data = await redis.get<{
email: string;
newEmail: string;
}>(`email-change-request:user:${currentUserId}`);
isPartnerProfile?: boolean;
}>(`email-change-request:user:${identifier}`);

if (!data) {
return (
Expand All @@ -97,23 +102,50 @@ const VerifyEmailChange = async ({
);
}

const user = await prisma.user.update({
where: {
id: currentUserId,
},
data: {
email: data.newEmail,
},
select: {
subscribed: true,
},
});
let user: Pick<User, "subscribed"> | null = null;

// Update the partner profile email
if (data.isPartnerProfile) {
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.partner.update({
where: {
id: partnerId,
},
data: {
email: data.newEmail,
},
});
}

// Update the user email
else {
user = await prisma.user.update({
where: {
id: userId,
},
data: {
email: data.newEmail,
},
select: {
subscribed: true,
},
});
}

waitUntil(
Promise.all([
Promise.allSettled([
deleteRequest(tokenFound),

...(user.subscribed
...(user?.subscribed
? [
unsubscribe({ email: data.email }),
subscribe({ email: data.newEmail }),
Expand All @@ -131,11 +163,13 @@ const VerifyEmailChange = async ({
]),
);

return <ConfirmEmailChangePageClient />;
return (
<ConfirmEmailChangePageClient isPartnerProfile={!!data.isPartnerProfile} />
);
};

const deleteRequest = async (tokenFound: VerificationToken) => {
await Promise.all([
await Promise.allSettled([
prisma.verificationToken.delete({
where: {
token: tokenFound.token,
Expand Down
Loading