The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add OTP resending
Tim Wilson073be328c921
diff --git a/apps/web/app/app.dub.co/(auth)/register/verify-email/page.tsx b/apps/web/app/app.dub.co/(auth)/register/verify-email/page.tsxindex beb6907967..43e8b56f4e 100644--- a/apps/web/app/app.dub.co/(auth)/register/verify-email/page.tsx+++ b/apps/web/app/app.dub.co/(auth)/register/verify-email/page.tsx@@ -2,6 +2,7 @@ import { BlurImage, Button, Wordmark } from "@dub/ui";import { constructMetadata, truncate } from "@dub/utils";import { Suspense } from "react";import VerifyEmailForm from "./form";+import { ResendCode } from "./resend-code";export const metadata = constructMetadata({title: `Create your ${process.env.NEXT_PUBLIC_APP_NAME} account`,@@ -61,6 +62,7 @@ export default function VerifyEmailPage({</Suspense></div></div>+ <ResendCode email={email} /></div></div><div className="hidden h-full flex-col justify-center space-y-12 overflow-hidden border-l border-gray-200 bg-white/10 shadow-[inset_10px_-50px_94px_0_rgb(199,199,199,0.2)] backdrop-blur md:col-span-2 md:flex">diff --git a/apps/web/app/app.dub.co/(auth)/register/verify-email/resend-code.tsx b/apps/web/app/app.dub.co/(auth)/register/verify-email/resend-code.tsxnew file mode 100644index 0000000000..4c2c9b2405--- /dev/null+++ b/apps/web/app/app.dub.co/(auth)/register/verify-email/resend-code.tsx@@ -0,0 +1,81 @@+"use client";++import { resendOtpAction } from "@/lib/actions/resend-otp";+import { LoadingSpinner } from "@dub/ui";+import { cn } from "@dub/utils";+import { useAction } from "next-safe-action/hooks";+import { useEffect, useState } from "react";++export function ResendCode({ email }: { email: string }) {+ const [delaySeconds, setDelaySeconds] = useState(0);+ const [state, setState] = useState<"default" | "success" | "error">(+ "default",+ );++ const { executeAsync, result, status, isExecuting } = useAction(+ resendOtpAction,+ {+ onSuccess: () => {+ setState("success");+ },+ onError: () => setState("error"),+ },+ );++ useEffect(() => {+ if (state === "success") setDelaySeconds(60);+ else if (state === "error") setDelaySeconds(5);+ }, [state]);++ useEffect(() => {+ if (delaySeconds > 0) {+ const interval = setInterval(+ () => setDelaySeconds(delaySeconds - 1),+ 1000,+ );+ return () => clearInterval(interval);+ } else setState("default");+ }, [delaySeconds]);++ return (+ <div className="relative mt-4 text-center text-sm text-gray-500">+ {state === "default" && (+ <>+ {isExecuting && (+ <div className="absolute left-0 top-1/2 -translate-x-full -translate-y-1/2 pr-1.5">+ <LoadingSpinner className="h-3 w-3" />+ </div>+ )}+ <p className={cn(isExecuting && "opacity-80")}>+ Didn't receive a code?{" "}+ <button+ onClick={() => executeAsync({ email })}+ className={cn(+ "font-semibold text-gray-500 underline underline-offset-2 transition-colors hover:text-black",+ isExecuting && "pointer-events-none",+ )}+ >+ Resend+ </button>+ </p>+ </>+ )}+ {state === "success" && (+ <p className="text-sm text-gray-500">+ Code sent successfully. <Delay seconds={delaySeconds} />+ </p>+ )}+ {state === "error" && (+ <p className="text-sm text-gray-500">+ Failed to send code. <Delay seconds={delaySeconds} />+ </p>+ )}+ </div>+ );+}++function Delay({ seconds }: { seconds: number }) {+ return (+ <span className="ml-1 text-sm tabular-nums text-gray-400">{seconds}s</span>+ );+}diff --git a/apps/web/lib/actions/resend-otp.ts b/apps/web/lib/actions/resend-otp.tsnew file mode 100644index 0000000000..1b12f203e7--- /dev/null+++ b/apps/web/lib/actions/resend-otp.ts@@ -0,0 +1,66 @@+"use server";++import { prisma } from "@/lib/prisma";+import { ratelimit } from "@/lib/upstash";+import { sendEmail } from "emails";+import VerifyEmail from "emails/verify-email";+import { flattenValidationErrors } from "next-safe-action";+import { getIP } from "../api/utils";+import { generateOTP } from "../auth";+import { EMAIL_OTP_EXPIRY_IN } from "../auth/constants";+import { resendOtpSchema } from "../zod/schemas/auth";+import { throwIfAuthenticated } from "./middlewares/throw-if-authenticated";+import { actionClient } from "./safe-action";++// Sign up a new user using email and password+export const resendOtpAction = actionClient+ .schema(resendOtpSchema, {+ handleValidationErrorsShape: (ve) =>+ flattenValidationErrors(ve).fieldErrors,+ })+ .use(throwIfAuthenticated)+ .action(async ({ parsedInput }) => {+ const { email } = parsedInput;++ const { success } = await ratelimit(2, "1 m").limit(+ `resend-otp:${getIP()}`,+ );++ if (!success) {+ throw new Error("Too many requests. Please try again later.");+ }++ // Check user with email exists+ const user = await prisma.user.findUnique({+ where: {+ email,+ },+ });++ if (!user) {+ throw new Error("An user with this email does not exist.");+ }++ // Generate the OTP+ const code = generateOTP();++ await prisma.verificationToken.create({+ data: {+ identifier: email,+ token: code,+ expires: new Date(Date.now() + EMAIL_OTP_EXPIRY_IN * 1000),+ },+ });++ // Send email with generated OTP+ await sendEmail({+ subject: `${process.env.NEXT_PUBLIC_APP_NAME}: OTP to verify your account`,+ email,+ react: VerifyEmail({+ email,+ code,+ }),+ });++ return { ok: true };+ });diff --git a/apps/web/lib/zod/schemas/auth.ts b/apps/web/lib/zod/schemas/auth.tsindex ec22bf8468..702b05f304 100644--- a/apps/web/lib/zod/schemas/auth.ts+++ b/apps/web/lib/zod/schemas/auth.ts@@ -49,3 +49,7 @@ export const verifyEmailSchema = z.object({email: emailSchema,code: z.string().min(6),});++export const resendOtpSchema = z.object({+ email: emailSchema,+});