The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
create account only after email verified
Kiran K8829f6330160
diff --git a/apps/web/app/app.dub.co/(auth)/register/context.tsx b/apps/web/app/app.dub.co/(auth)/register/context.tsxnew file mode 100644index 0000000000..0347a99653--- /dev/null+++ b/apps/web/app/app.dub.co/(auth)/register/context.tsx@@ -0,0 +1,44 @@+"use client";++import React, { createContext, useContext, useState } from "react";++interface RegisterContextType {+ email: string;+ password: string;+ step: "signup" | "verify";+ setEmail: (email: string) => void;+ setPassword: (password: string) => void;+ setStep: (step: "signup" | "verify") => void;+}++const RegisterContext = createContext<RegisterContextType | undefined>(+ undefined,+);++export const RegisterProvider: React.FC<{ children: React.ReactNode }> = ({+ children,+}) => {+ const [email, setEmail] = useState("");+ const [password, setPassword] = useState("");+ const [step, setStep] = useState<"signup" | "verify">("signup");++ return (+ <RegisterContext.Provider+ value={{ email, password, step, setEmail, setPassword, setStep }}+ >+ {children}+ </RegisterContext.Provider>+ );+};++export const useRegisterContext = () => {+ const context = useContext(RegisterContext);++ if (context === undefined) {+ throw new Error(+ "useRegisterContext must be used within a RegisterProvider",+ );+ }++ return context;+};diff --git a/apps/web/app/app.dub.co/(auth)/register/page-client.tsx b/apps/web/app/app.dub.co/(auth)/register/page-client.tsxnew file mode 100644index 0000000000..223e246bce--- /dev/null+++ b/apps/web/app/app.dub.co/(auth)/register/page-client.tsx@@ -0,0 +1,27 @@+"use client";++import { AuthLayout } from "@/ui/layout/auth-layout";+import { RegisterProvider, useRegisterContext } from "./context";+import { SignUpForm } from "./signup-form";+import { VerifyEmailForm } from "./verify-email-form";++export default function RegisterPageClient() {+ return (+ <AuthLayout>+ <RegisterProvider>+ <RegisterFlow />+ </RegisterProvider>+ </AuthLayout>+ );+}++const RegisterFlow = () => {+ const { step } = useRegisterContext();++ return (+ <>+ {step === "signup" && <SignUpForm />}+ {step === "verify" && <VerifyEmailForm />}+ </>+ );+};diff --git a/apps/web/app/app.dub.co/(auth)/register/page.tsx b/apps/web/app/app.dub.co/(auth)/register/page.tsxindex d580140295..151110ea72 100644--- a/apps/web/app/app.dub.co/(auth)/register/page.tsx+++ b/apps/web/app/app.dub.co/(auth)/register/page.tsx@@ -1,15 +1,10 @@-import { AuthLayout } from "@/ui/layout/auth-layout";import { constructMetadata } from "@dub/utils";-import { RegisterForm } from "./form";+import RegisterPageClient from "./page-client";export const metadata = constructMetadata({title: `Create your ${process.env.NEXT_PUBLIC_APP_NAME} account`,});export default function RegisterPage() {- return (- <AuthLayout>- <RegisterForm />- </AuthLayout>- );+ return <RegisterPageClient />;}diff --git a/apps/web/app/app.dub.co/(auth)/register/signup-email.tsx b/apps/web/app/app.dub.co/(auth)/register/signup-email.tsxindex 4fc722976f..ff857b0773 100644--- a/apps/web/app/app.dub.co/(auth)/register/signup-email.tsx+++ b/apps/web/app/app.dub.co/(auth)/register/signup-email.tsx@@ -1,67 +1,44 @@"use client";-import { createUserAccountAction } from "@/lib/actions/create-user-account";+import { sendOtpAction } from "@/lib/actions/send-otp";import z from "@/lib/zod";import { signUpSchema } from "@/lib/zod/schemas/auth";import { Button, Input } from "@dub/ui";import { zodResolver } from "@hookform/resolvers/zod";import { useAction } from "next-safe-action/hooks";-import { useRouter } from "next/navigation";import { useForm } from "react-hook-form";import { toast } from "sonner";+import { useRegisterContext } from "./context";++type SignUpProps = z.infer<typeof signUpSchema>;export const SignUpEmail = () => {- const router = useRouter();+ const { setStep, setEmail, setPassword } = useRegisterContext();const {register,handleSubmit,+ formState: { errors },getValues,- formState: { errors, isDirty },- } = useForm<z.infer<typeof signUpSchema>>({+ } = useForm<SignUpProps>({resolver: zodResolver(signUpSchema),- defaultValues: {- email: "[email protected]",- password: "12345678Ab@",- },});- const { executeAsync, result, status, isExecuting } = useAction(- createUserAccountAction,- {- onSuccess: () => {- toast.success(- "Account created successfully. Please verify your email to login.",- );- router.push(- `/register/verify-email?email=${encodeURIComponent(- getValues("email"),- )}`,- );- },+ const { executeAsync, isExecuting } = useAction(sendOtpAction, {+ onSuccess: () => {+ setEmail(getValues("email"));+ setPassword(getValues("password"));+ setStep("verify");},- );+ onError: ({ error }) => {+ toast.error(error.serverError?.serverError);+ },+ });return (<>- {result.serverError && (- <div className="rounded-md bg-red-100 p-3 text-red-900 dark:bg-red-900 dark:text-red-200">- <div className="relative flex md:flex-row">- <div className="flex flex-grow flex-col sm:flex-row">- <div className="ltr:ml-3 rtl:mr-3">- <h3 className="text-sm font-medium">- {result.serverError.serverError}- </h3>- </div>- </div>- </div>- </div>- )}-<form- onSubmit={handleSubmit(async (data) => {- await executeAsync(data);- })}+ onSubmit={handleSubmit((data) => executeAsync({ email: data.email }))}><div className="flex flex-col space-y-4"><Input@@ -80,10 +57,10 @@ export const SignUpEmail = () => {error={errors.password?.message}/><Button- text={status === "executing" ? "Signing Up..." : "Sign Up"}type="submit"+ text={isExecuting ? "Submitting..." : "Sign Up"}+ disabled={isExecuting}loading={isExecuting}- disabled={!isDirty}/></div></form>diff --git a/apps/web/app/app.dub.co/(auth)/register/form.tsx b/apps/web/app/app.dub.co/(auth)/register/signup-form.tsxsimilarity index 97%rename from apps/web/app/app.dub.co/(auth)/register/form.tsxrename to apps/web/app/app.dub.co/(auth)/register/signup-form.tsxindex 2db421706e..f405937526 100644--- a/apps/web/app/app.dub.co/(auth)/register/form.tsx+++ b/apps/web/app/app.dub.co/(auth)/register/signup-form.tsx@@ -4,7 +4,7 @@ import Link from "next/link";import { SignUpEmail } from "./signup-email";import { SignUpOAuth } from "./signup-oauth";-export const RegisterForm = () => {+export const SignUpForm = () => {return (<><div className="w-full max-w-md overflow-hidden border-y border-gray-200 sm:rounded-2xl sm:border sm:shadow-sm">diff --git a/apps/web/app/app.dub.co/(auth)/register/verify-email-form.tsx b/apps/web/app/app.dub.co/(auth)/register/verify-email-form.tsxnew file mode 100644index 0000000000..72d39d97cb--- /dev/null+++ b/apps/web/app/app.dub.co/(auth)/register/verify-email-form.tsx@@ -0,0 +1,111 @@+"use client";++import { createUserAccountAction } from "@/lib/actions/create-user-account";+import { AnimatedSizeContainer, Button, useMediaQuery } from "@dub/ui";+import { cn, truncate } from "@dub/utils";+import { OTPInput } from "input-otp";+import { useAction } from "next-safe-action/hooks";+import Link from "next/link";+import { useRouter } from "next/navigation";+import { useState } from "react";+import { toast } from "sonner";+import { useRegisterContext } from "./context";++export const VerifyEmailForm = () => {+ const router = useRouter();+ const { isMobile } = useMediaQuery();+ const [code, setCode] = useState("");+ const { email, password } = useRegisterContext();++ const { executeAsync, isExecuting } = useAction(createUserAccountAction, {+ onSuccess() {+ toast.success("Email verified! Redirecting to login...");+ router.push("/login");+ },+ onError({ error }) {+ toast.error(error.serverError?.serverError);+ },+ });++ if (!email || !password) {+ router.push("/register");+ return;+ }++ return (+ <>+ <div className="w-full max-w-md overflow-hidden border-y border-gray-200 sm:rounded-2xl sm:border sm:shadow-sm">+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 bg-white px-4 py-6 pt-8 text-center sm:px-16">+ <h3 className="text-xl font-semibold">Verify your email address</h3>+ <p className="text-sm text-gray-500">+ Enter the six digit verification code sent to{" "}+ <strong className="font-medium text-gray-600" title={email}>+ {truncate(email, 30)}+ </strong>+ </p>+ </div>++ <div className="grid gap-3 bg-gray-50 px-4 py-8 sm:px-16">+ <AnimatedSizeContainer height>+ <form+ onSubmit={(e) => {+ e.preventDefault();+ executeAsync({ email, password, code });+ }}+ >+ <div className="flex flex-col gap-8">+ <OTPInput+ maxLength={6}+ value={code}+ onChange={setCode}+ autoFocus={!isMobile}+ containerClassName="group flex items-center justify-center"+ render={({ slots }) => (+ <div className="flex items-center">+ {slots.map(({ char, isActive, hasFakeCaret }, idx) => (+ <div+ key={idx}+ className={cn(+ "relative flex h-14 w-10 items-center justify-center text-xl",+ "border-y border-r border-gray-200 bg-white first:rounded-l-lg first:border-l last:rounded-r-lg",+ "ring-0 transition-all",+ isActive &&+ "z-10 border border-gray-500 ring-4 ring-gray-200",+ )}+ >+ {char}+ {hasFakeCaret && (+ <div className="animate-caret-blink pointer-events-none absolute inset-0 flex items-center justify-center">+ <div className="h-5 w-px bg-black" />+ </div>+ )}+ </div>+ ))}+ </div>+ )}+ />++ <Button+ text={isExecuting ? "Verifying..." : "Continue"}+ type="submit"+ loading={isExecuting}+ disabled={!code || code.length < 6}+ />+ </div>+ </form>+ </AnimatedSizeContainer>+ </div>+ </div>++ <p className="mt-4 text-center text-sm text-gray-500">+ Already have an account? + <Link+ href="/login"+ className="font-semibold text-gray-500 underline underline-offset-2 transition-colors hover:text-black"+ >+ Sign in+ </Link>+ </p>+ </>+ );+};diff --git a/apps/web/app/app.dub.co/(auth)/register/verify-email/form.tsx b/apps/web/app/app.dub.co/(auth)/register/verify-email/form.tsxdeleted file mode 100644index 230be4b10f..0000000000--- a/apps/web/app/app.dub.co/(auth)/register/verify-email/form.tsx+++ /dev/null@@ -1,99 +0,0 @@-"use client";--import { verifyEmailAction } from "@/lib/actions/verify-email";-import { Button, useMediaQuery } from "@dub/ui";-import { cn } from "@dub/utils";-import { OTPInput } from "input-otp";-import { useAction } from "next-safe-action/hooks";-import { useRouter, useSearchParams } from "next/navigation";-import { useState } from "react";-import { toast } from "sonner";--export default function VerifyEmailForm() {- const router = useRouter();- const { isMobile } = useMediaQuery();- const [code, setCode] = useState("");- const searchParams = useSearchParams();-- const { executeAsync, result, status, isExecuting } = useAction(- verifyEmailAction,- {- onSuccess() {- toast.success("Email verified! Redirecting to login...");- router.push("/login");- },- },- );-- const email = searchParams.get("email");-- if (!email) {- router.push("/register");- return;- }-- return (- <>- {result.serverError && (- <div className="rounded-md bg-red-100 p-3 text-red-900 dark:bg-red-900 dark:text-red-200">- <div className="relative flex md:flex-row">- <div className="flex flex-grow flex-col sm:flex-row">- <div className="ltr:ml-3 rtl:mr-3">- <h3 className="text-sm font-medium">- {result.serverError.serverError}- </h3>- </div>- </div>- </div>- </div>- )}-- <form- onSubmit={async (e) => {- e.preventDefault();- await executeAsync({ email, code });- }}- >- <div className="flex flex-col gap-8">- <OTPInput- maxLength={6}- value={code}- onChange={setCode}- autoFocus={!isMobile}- containerClassName="group flex items-center justify-center"- render={({ slots }) => (- <div className="flex items-center">- {slots.map(({ char, isActive, hasFakeCaret }, idx) => (- <div- key={idx}- className={cn(- "relative flex h-14 w-10 items-center justify-center text-xl",- "border-y border-r border-gray-200 bg-white first:rounded-l-lg first:border-l last:rounded-r-lg",- "ring ring-0 transition-all",- isActive &&- "z-10 border border-gray-500 ring-4 ring-gray-200",- )}- >- {char}- {hasFakeCaret && (- <div className="animate-caret-blink pointer-events-none absolute inset-0 flex items-center justify-center">- <div className="h-5 w-px bg-black" />- </div>- )}- </div>- ))}- </div>- )}- />- <input type="hidden" value={email} />- <Button- text={status === "executing" ? "Verifying..." : "Continue"}- type="submit"- loading={isExecuting}- disabled={!code || code.length < 6}- />- </div>- </form>- </>- );-}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 43e8b56f4e..546da9d8b5 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@@ -1,7 +1,7 @@import { BlurImage, Button, Wordmark } from "@dub/ui";import { constructMetadata, truncate } from "@dub/utils";import { Suspense } from "react";-import VerifyEmailForm from "./form";+// import VerifyEmailForm from "./form";import { ResendCode } from "./resend-code";export const metadata = constructMetadata({@@ -58,7 +58,7 @@ export default function VerifyEmailPage({</>}>- <VerifyEmailForm />+ {/* <VerifyEmailForm /> */}</Suspense></div></div>diff --git a/apps/web/lib/actions/create-user-account.ts b/apps/web/lib/actions/create-user-account.tsindex a1804bd71c..75bec00851 100644--- a/apps/web/lib/actions/create-user-account.ts+++ b/apps/web/lib/actions/create-user-account.ts@@ -2,26 +2,29 @@import { prisma } from "@/lib/prisma";import { ratelimit, redis } 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 { hashPassword } from "../auth/password";+import z from "../zod";import { signUpSchema } from "../zod/schemas/auth";import { throwIfAuthenticated } from "./middlewares/throw-if-authenticated";import { actionClient } from "./safe-action";+const schema = signUpSchema.extend({+ code: z.string().min(6, "OTP must be 6 characters long."),+});+// Sign up a new user using email and passwordexport const createUserAccountAction = actionClient- .schema(signUpSchema, {+ .schema(schema, {handleValidationErrorsShape: (ve) =>flattenValidationErrors(ve).fieldErrors,}).use(throwIfAuthenticated)- .action(async ({ parsedInput, ctx }) => {- const { email, password } = parsedInput;+ .action(async ({ parsedInput }) => {+ const { email, password, code } = parsedInput;++ console.log("createUserAccountAction", { email, password, code });const { success } = await ratelimit(2, "1 m").limit(`signup:${getIP()}`);@@ -29,55 +32,52 @@ export const createUserAccountAction = actionClientthrow 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 already exists.");- }+ const disposableEmailDomains = await redis.smembers(+ "disposableEmailDomains",+ );- if (await redis.sismember("disposableEmailDomains", email.split("@")[1])) {+ if (disposableEmailDomains.includes(email.split("@")[1])) {throw new Error("Disposable email addresses are not allowed. If you think this is a mistake, please contact us at [email protected]",);}- // Create an account- const newUser = await prisma.user.create({- data: {- email,- passwordHash: await hashPassword(password),+ const verificationToken = await prisma.emailVerificationToken.findUnique({+ where: {+ identifier: email,+ token: code,+ expires: {+ gte: new Date(),+ },},});- if (!newUser) {- throw new Error("Failed to create an account. Please try again.");+ if (!verificationToken) {+ throw new Error("Invalid verification code entered.");}- // Generate the OTP- const code = generateOTP();-- await prisma.emailVerificationToken.create({- data: {+ await prisma.emailVerificationToken.delete({+ where: {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({+ const user = await prisma.user.findUnique({+ where: {email,- code,- }),+ },});+ if (!user) {+ await prisma.user.create({+ data: {+ email,+ passwordHash: await hashPassword(password),+ emailVerified: new Date(),+ },+ });+ }+return { ok: true };});diff --git a/apps/web/lib/actions/resend-otp.ts b/apps/web/lib/actions/send-otp.tssimilarity index 72%rename from apps/web/lib/actions/resend-otp.tsrename to apps/web/lib/actions/send-otp.tsindex a6c5f6c042..b5e5fa207a 100644--- a/apps/web/lib/actions/resend-otp.ts+++ b/apps/web/lib/actions/send-otp.ts@@ -8,13 +8,18 @@ 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 z from "../zod";+import { emailSchema } 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, {+const schema = z.object({+ email: emailSchema,+});++// Send OTP to email to verify account+export const sendOtpAction = actionClient+ .schema(schema, {handleValidationErrorsShape: (ve) =>flattenValidationErrors(ve).fieldErrors,})@@ -22,25 +27,12 @@ export const resendOtpAction = actionClient.action(async ({ parsedInput }) => {const { email } = parsedInput;- const { success } = await ratelimit(2, "1 m").limit(- `resend-otp:${getIP()}`,- );+ const { success } = await ratelimit(2, "1 m").limit(`send-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.");- }-const code = generateOTP();await Promise.all([@@ -59,7 +51,6 @@ export const resendOtpAction = actionClient}),]);- // Send email with generated OTPawait sendEmail({subject: `${process.env.NEXT_PUBLIC_APP_NAME}: OTP to verify your account`,email,diff --git a/apps/web/lib/actions/verify-email.ts b/apps/web/lib/actions/verify-email.tsdeleted file mode 100644index 2030d4711b..0000000000--- a/apps/web/lib/actions/verify-email.ts+++ /dev/null@@ -1,66 +0,0 @@-"use server";--import { prisma } from "@/lib/prisma";-import { ratelimit } from "@/lib/upstash";-import { flattenValidationErrors } from "next-safe-action";-import { getIP } from "../api/utils";-import { verifyEmailSchema } from "../zod/schemas/auth";-import { throwIfAuthenticated } from "./middlewares/throw-if-authenticated";-import { actionClient } from "./safe-action";--// Verify email using OTP-export const verifyEmailAction = actionClient- .schema(verifyEmailSchema, {- handleValidationErrorsShape: (ve) =>- flattenValidationErrors(ve).fieldErrors,- })- .use(throwIfAuthenticated)- .action(async ({ parsedInput }) => {- const { email, code } = parsedInput;-- const { success, reset } = await ratelimit(3, "1 m").limit(- `verifyEmail:${getIP()}`,- );-- if (!success) {- const millis = reset - Date.now();- const timeToWait = Math.floor(millis / 1000);-- throw new Error(- `You have been rate limited. Please try again in ${timeToWait} seconds.`,- );- }-- const verificationToken = await prisma.emailVerificationToken.findUnique({- where: {- identifier: email,- token: code,- expires: {- gte: new Date(),- },- },- });-- if (!verificationToken) {- throw new Error("Invalid verification code entered.");- }-- await Promise.all([- prisma.emailVerificationToken.delete({- where: {- token: code,- },- }),-- prisma.user.update({- where: {- email,- },- data: {- emailVerified: new Date(),- },- }),- ]);-- return { ok: true };- });diff --git a/apps/web/lib/zod/schemas/auth.ts b/apps/web/lib/zod/schemas/auth.tsindex a6d8957c0d..d01ba8f0e1 100644--- a/apps/web/lib/zod/schemas/auth.ts+++ b/apps/web/lib/zod/schemas/auth.ts@@ -50,10 +50,6 @@ export const verifyEmailSchema = z.object({code: z.string().min(6),});-export const resendOtpSchema = z.object({- email: emailSchema,-});-export const requestPasswordResetSchema = z.object({email: emailSchema,});