The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
add signup form and server action
Kiran K15e4f39e8d3b
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..3b68d21e70--- /dev/null+++ b/apps/web/app/app.dub.co/(auth)/register/page-client.tsx@@ -0,0 +1,66 @@+"use client";++import { BlurImage } from "@dub/ui";+import { useState } from "react";+import SignUpForm from "./signup";+import { VerifyOTP } from "./verify-otp";++const logos = [+ "vercel",+ "perplexity",+ "prisma",+ "tinybird",+ "hashnode",+ "cal",+ "vercel",+ "perplexity",+ "prisma",+ "tinybird",+ "hashnode",+ "cal",+];++export default function RegisterPageClient() {+ const [authView, setAuthView] = useState<"signup" | "otp">("signup");++ console.log({ authView });++ return (+ <div className="grid w-full grid-cols-1 md:grid-cols-5">+ {authView === "signup" && <SignUpForm setAuthView={setAuthView} />}+ {authView === "otp" && <VerifyOTP />}++ <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">+ <a+ href="https://dub.co/features/analytics"+ target="_blank"+ className="ml-12 h-1/2 w-[112%] rounded-xl border border-gray-200 p-2 shadow-xl"+ >+ <BlurImage+ alt="Dub.co Analytics"+ src="https://assets.dub.co/features/analytics.png"+ width={1735}+ height={990}+ className="h-full rounded-lg border border-gray-200 object-cover"+ />+ </a>+ <a+ href="https://dub.co/customers"+ target="_blank"+ className="animate-infinite-scroll flex items-center space-x-4"+ >+ {logos.map((logo, idx) => (+ <BlurImage+ alt={`${logo} logo`}+ key={idx}+ src={`https://dub.co/_static/clients/${logo}.svg`}+ width={520}+ height={182}+ className="h-12 grayscale transition-all hover:grayscale-0"+ />+ ))}+ </a>+ </div>+ </div>+ );+}diff --git a/apps/web/app/app.dub.co/(auth)/register/page.tsx b/apps/web/app/app.dub.co/(auth)/register/page.tsxindex 4354d6f38d..cb7630f2b7 100644--- a/apps/web/app/app.dub.co/(auth)/register/page.tsx+++ b/apps/web/app/app.dub.co/(auth)/register/page.tsx@@ -1,118 +1,12 @@-import { BlurImage, Button, Logo } from "@dub/ui";-import { HOME_DOMAIN, constructMetadata } from "@dub/utils";-import { Suspense } from "react";-import RegisterForm from "./form";-import { SignUpWithEmailPassword } from "./signup-email-password";+import { constructMetadata } from "@dub/utils";+import RegisterPageClient from "./page-client";export const metadata = constructMetadata({title: `Create your ${process.env.NEXT_PUBLIC_APP_NAME} account`,});-const logos = [- "vercel",- "perplexity",- "prisma",- "tinybird",- "hashnode",- "cal",- "vercel",- "perplexity",- "prisma",- "tinybird",- "hashnode",- "cal",-];-export const runtime = "nodejs";export default function RegisterPage() {- return (- <div className="grid w-full grid-cols-1 md:grid-cols-5">- <div className="col-span-1 flex items-center justify-center md:col-span-3">- <div className="w-full max-w-md overflow-hidden border-y border-gray-200 sm:rounded-2xl sm:border sm:shadow-xl">- <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">- <a href={HOME_DOMAIN}>- <Logo className="h-10 w-10" />- </a>- <h3 className="text-xl font-semibold">- Create your {process.env.NEXT_PUBLIC_APP_NAME} account- </h3>- <p className="text-sm text-gray-500">- By signing up, you agree to our <br />- <a- href="https://dub.co/terms"- target="_blank"- className="font-medium underline underline-offset-4 hover:text-gray-700"- >- Terms of Service- </a>{" "}- and{" "}- <a- href="https://dub.co/privacy"- target="_blank"- className="font-medium underline underline-offset-4 hover:text-gray-700"- >- Privacy Policy- </a>- </p>- </div>- <div className="flex flex-col gap-5 bg-gray-50 px-4 py-8 sm:px-16">- <SignUpWithEmailPassword />-- <div className="relative flex items-center">- <div className="border-subtle flex-grow border-t" />- <span className="text-subtle leadning-none mx-2 flex-shrink text-sm font-normal text-gray-700">- Or continue with- </span>- <div className="border-subtle flex-grow border-t" />- </div>-- <div className="space-y-3">- <Suspense- fallback={- <>- <Button disabled={true} text="" variant="secondary" />- <div className="mx-auto h-5 w-3/4 rounded-lg bg-gray-100" />- </>- }- >- <RegisterForm />- </Suspense>- </div>- </div>- </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">- <a- href="https://dub.co/features/analytics"- target="_blank"- className="ml-12 h-1/2 w-[112%] rounded-xl border border-gray-200 p-2 shadow-xl"- >- <BlurImage- alt="Dub.co Analytics"- src="https://assets.dub.co/features/analytics.png"- width={1735}- height={990}- className="h-full rounded-lg border border-gray-200 object-cover"- />- </a>- <a- href="https://dub.co/customers"- target="_blank"- className="animate-infinite-scroll flex items-center space-x-4"- >- {logos.map((logo, idx) => (- <BlurImage- alt={`${logo} logo`}- key={idx}- src={`https://dub.co/_static/clients/${logo}.svg`}- width={520}- height={182}- className="h-12 grayscale transition-all hover:grayscale-0"- />- ))}- </a>- </div>- </div>- );+ return <RegisterPageClient />;}diff --git a/apps/web/app/app.dub.co/(auth)/register/signup-email-password.tsx b/apps/web/app/app.dub.co/(auth)/register/signup-email.tsxsimilarity index 87%rename from apps/web/app/app.dub.co/(auth)/register/signup-email-password.tsxrename to apps/web/app/app.dub.co/(auth)/register/signup-email.tsxindex e121b05b2b..1f71bd475c 100644--- a/apps/web/app/app.dub.co/(auth)/register/signup-email-password.tsx+++ b/apps/web/app/app.dub.co/(auth)/register/signup-email.tsx@@ -7,32 +7,41 @@ 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 { useEffect } from "react";import { useForm } from "react-hook-form";-import { toast } from "sonner";-export const SignUpWithEmailPassword = () => {+export default function SignUpEmail({+ setAuthView,+}: {+ setAuthView: (view: "signup" | "otp") => void;+}) {const router = useRouter();const { executeAsync, result, status, isExecuting } =useAction(createNewAccount);const {+ reset,register,handleSubmit,- reset,formState: { errors, isDirty },} = useForm<z.infer<typeof signUpSchema>>({- // resolver: zodResolver(signUpSchema),+ resolver: zodResolver(signUpSchema),defaultValues: {email: "[email protected]",- password: "1234aB#",+ password: "12345678aB#",},});+ useEffect(() => {+ if (status === "hasSucceeded") {+ setAuthView("otp");+ }+ }, [status]);+const onSubmit = handleSubmit(async (data) => {await executeAsync(data);if (status === "hasSucceeded") {- toast.success("account created");reset();}});@@ -82,4 +91,4 @@ export const SignUpWithEmailPassword = () => {</form></>);-};+}diff --git a/apps/web/app/app.dub.co/(auth)/register/form.tsx b/apps/web/app/app.dub.co/(auth)/register/signup-oauth.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-oauth.tsxindex 22bffa4d31..91743d9db9 100644--- a/apps/web/app/app.dub.co/(auth)/register/form.tsx+++ b/apps/web/app/app.dub.co/(auth)/register/signup-oauth.tsx@@ -6,7 +6,7 @@ import Link from "next/link";import { useSearchParams } from "next/navigation";import { useEffect, useState } from "react";-export default function RegisterForm() {+export default function SignupOAuth() {const searchParams = useSearchParams();const next = searchParams?.get("next");const [clickedGoogle, setClickedGoogle] = useState(false);diff --git a/apps/web/app/app.dub.co/(auth)/register/signup.tsx b/apps/web/app/app.dub.co/(auth)/register/signup.tsxnew file mode 100644index 0000000000..de6fb1a8c5--- /dev/null+++ b/apps/web/app/app.dub.co/(auth)/register/signup.tsx@@ -0,0 +1,70 @@+"use client";++import { Button, Logo } from "@dub/ui";+import { HOME_DOMAIN } from "@dub/utils";+import { Suspense } from "react";+import SignUpEmail from "./signup-email";+import SignupOAuth from "./signup-oauth";++export default function SignUpForm({+ setAuthView,+}: {+ setAuthView: (view: "signup" | "otp") => void;+}) {+ return (+ <div className="col-span-1 flex items-center justify-center md:col-span-3">+ <div className="w-full max-w-md overflow-hidden border-y border-gray-200 sm:rounded-2xl sm:border sm:shadow-xl">+ <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">+ <a href={HOME_DOMAIN}>+ <Logo className="h-10 w-10" />+ </a>+ <h3 className="text-xl font-semibold">+ Create your {process.env.NEXT_PUBLIC_APP_NAME} account+ </h3>+ <p className="text-sm text-gray-500">+ By signing up, you agree to our <br />+ <a+ href="https://dub.co/terms"+ target="_blank"+ className="font-medium underline underline-offset-4 hover:text-gray-700"+ >+ Terms of Service+ </a>{" "}+ and{" "}+ <a+ href="https://dub.co/privacy"+ target="_blank"+ className="font-medium underline underline-offset-4 hover:text-gray-700"+ >+ Privacy Policy+ </a>+ </p>+ </div>+ <div className="flex flex-col gap-5 bg-gray-50 px-4 py-8 sm:px-16">+ <SignUpEmail setAuthView={setAuthView} />++ <div className="relative flex items-center">+ <div className="border-subtle flex-grow border-t" />+ <span className="text-subtle leadning-none mx-2 flex-shrink text-sm font-normal text-gray-700">+ Or continue with+ </span>+ <div className="border-subtle flex-grow border-t" />+ </div>++ <div className="space-y-3">+ <Suspense+ fallback={+ <>+ <Button disabled={true} text="" variant="secondary" />+ <div className="mx-auto h-5 w-3/4 rounded-lg bg-gray-100" />+ </>+ }+ >+ <SignupOAuth />+ </Suspense>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/apps/web/app/app.dub.co/(auth)/register/verify-otp.tsx b/apps/web/app/app.dub.co/(auth)/register/verify-otp.tsxnew file mode 100644index 0000000000..f24aaf4fc2--- /dev/null+++ b/apps/web/app/app.dub.co/(auth)/register/verify-otp.tsx@@ -0,0 +1,75 @@+"use client";++import { createNewAccount } from "@/lib/actions/create-new-account";+import { Button, Input, Logo } from "@dub/ui";+import { HOME_DOMAIN } from "@dub/utils";+import { useAction } from "next-safe-action/hooks";+import { useRouter } from "next/navigation";+import { useState } from "react";++export const VerifyOTP = () => {+ const router = useRouter();+ const [code, setCode] = useState("");+ const { executeAsync, result, status, isExecuting } =+ useAction(createNewAccount);++ const onSubmit = async () => {+ // await executeAsync(data);+ // if (status === "hasSucceeded") {+ // toast.success("account created");+ // reset();+ // }+ };++ return (+ <div className="col-span-1 flex items-center justify-center md:col-span-3">+ <div className="w-full max-w-md overflow-hidden border-y border-gray-200 sm:rounded-2xl sm:border sm:shadow-xl">+ <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">+ <a href={HOME_DOMAIN}>+ <Logo className="h-10 w-10" />+ </a>+ <h3 className="text-xl font-semibold">Verification code sent</h3>+ <p className="text-sm text-gray-500">+ Please enter the 6 digits verification code sent to your email+ address.+ </p>+ </div>+ <div className="flex flex-col gap-5 bg-gray-50 px-4 py-8 sm:px-16">+ <>+ {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={onSubmit}>+ <div className="flex flex-col space-y-4">+ <Input+ required+ type="text"+ placeholder="Enter OTP"+ value={code}+ onChange={(e) => setCode(e.target.value)}+ />+ <Button+ text={status === "executing" ? "Verifying..." : "Continue"}+ type="submit"+ loading={isExecuting}+ disabled={!code}+ />+ </div>+ </form>+ </>+ </div>+ </div>+ </div>+ );+};diff --git a/apps/web/emails/verify-email.tsx b/apps/web/emails/verify-email.tsxnew file mode 100644index 0000000000..3594ba7310--- /dev/null+++ b/apps/web/emails/verify-email.tsx@@ -0,0 +1,58 @@+import { DUB_WORDMARK } from "@dub/utils";+import {+ Body,+ Container,+ Head,+ Heading,+ Html,+ Img,+ Preview,+ Section,+ Tailwind,+ Text,+} from "@react-email/components";+import Footer from "./components/footer";++export default function VerifyEmail({+ email = "[email protected]",+ code = "123456",+}: {+ email: string;+ code: string;+}) {+ return (+ <Html>+ <Head />+ <Preview>Your Dub.co Verification Code</Preview>+ <Tailwind>+ <Body className="mx-auto my-auto bg-white font-sans">+ <Container className="mx-auto my-10 max-w-[500px] rounded border border-solid border-gray-200 px-10 py-5">+ <Section className="mt-8">+ <Img+ src={DUB_WORDMARK}+ height="40"+ alt="Dub"+ className="mx-auto my-0"+ />+ </Section>+ <Heading className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">+ Please confirm your email address+ </Heading>+ <Text className="mx-auto text-sm leading-6">+ Enter this code on the Dub verify page to complete your sign up:+ </Text>+ <Section className="my-8">+ <div className="mx-auto w-20 rounded-xl bg-gray-800 px-6 py-3 text-center text-[20px] font-semibold tracking-widest text-white">+ {code}+ </div>+ </Section>+ <Text className="text-sm leading-6 text-black">+ This code expires in 10 minutes.+ </Text>+ <Footer email={email} />+ </Container>+ </Body>+ </Tailwind>+ </Html>+ );+}diff --git a/apps/web/lib/actions/create-new-account.ts b/apps/web/lib/actions/create-new-account.tsindex 44be346bd7..dd8a844234 100644--- a/apps/web/lib/actions/create-new-account.ts+++ b/apps/web/lib/actions/create-new-account.ts@@ -1,9 +1,14 @@"use server";import { prisma } from "@/lib/prisma";+import { sendEmail } from "emails";+import VerifyEmail from "emails/verify-email";import { flattenValidationErrors } from "next-safe-action";+import { generateOTP } from "../auth";+import { EMAIL_OTP_EXPIRY_IN } from "../auth/constants";import { hashPassword } from "../auth/password";import { signUpSchema } 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@@ -12,6 +17,7 @@ export const createNewAccount = actionClienthandleValidationErrorsShape: (ve) =>flattenValidationErrors(ve).fieldErrors,})+ .use(throwIfAuthenticated).action(async ({ parsedInput }) => {const { email, password } = parsedInput;@@ -38,8 +44,26 @@ export const createNewAccount = actionClientthrow new Error("Failed to create an account. Please try again.");}- // TODO:- // Send verification email+ // 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 {user: {diff --git a/apps/web/lib/actions/middlewares/throw-if-authenticated.ts b/apps/web/lib/actions/middlewares/throw-if-authenticated.tsnew file mode 100644index 0000000000..6a53e251a9--- /dev/null+++ b/apps/web/lib/actions/middlewares/throw-if-authenticated.ts@@ -0,0 +1,11 @@+import { getSession } from "@/lib/auth";++export const throwIfAuthenticated = async ({ next, ctx }) => {+ const session = await getSession();++ if (session) {+ throw new Error("You are already logged in.");+ }++ return next({ ctx });+};diff --git a/apps/web/lib/actions/safe-action.ts b/apps/web/lib/actions/safe-action.tsindex 07fd3f490e..09b81e4445 100644--- a/apps/web/lib/actions/safe-action.ts+++ b/apps/web/lib/actions/safe-action.ts@@ -14,6 +14,10 @@ export const actionClient = createSafeActionClient({serverError: "An unknown error occurred.",};},++ handleServerErrorLog(originalError) {+ console.error("Action error:", originalError.message);+ },});export const authActionClient = actionClient.use(diff --git a/apps/web/lib/auth/constants.ts b/apps/web/lib/auth/constants.tsindex f1f3bdeeeb..b429c98704 100644--- a/apps/web/lib/auth/constants.ts+++ b/apps/web/lib/auth/constants.ts@@ -1,3 +1,5 @@export const PASSWORD_RESET_TOKEN_EXPIRY = 1 * 60 * 60; // 1 hourexport const MAX_LOGIN_ATTEMPTS = 10;++export const EMAIL_OTP_EXPIRY_IN = 10 * 60; // 10 minutesdiff --git a/apps/web/lib/auth/utils.ts b/apps/web/lib/auth/utils.tsindex 79bbcd08a5..7787777866 100644--- a/apps/web/lib/auth/utils.ts+++ b/apps/web/lib/auth/utils.ts@@ -33,3 +33,13 @@ export const getAuthTokenOrThrow = (return authorizationHeader.replace(`${type} `, "");};++export function generateOTP() {+ // Generate a random number between 0 and 999999+ 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;+}