The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
signin and verify email address
Kiran Kd613d3e60556
diff --git a/apps/web/app/app.dub.co/(auth)/register/otp/form.tsx b/apps/web/app/app.dub.co/(auth)/register/otp/form.tsxdeleted file mode 100644index 32367753af..0000000000--- a/apps/web/app/app.dub.co/(auth)/register/otp/form.tsx+++ /dev/null@@ -1,75 +0,0 @@-"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 default function VerifyOTPForm() {- 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/app/app.dub.co/(auth)/register/page.tsx b/apps/web/app/app.dub.co/(auth)/register/page.tsxindex b63ffb7b59..3e15e3cae8 100644--- a/apps/web/app/app.dub.co/(auth)/register/page.tsx+++ b/apps/web/app/app.dub.co/(auth)/register/page.tsx@@ -22,6 +22,8 @@ const logos = ["cal",];+export const runtime = "nodejs";+export default function RegisterPage() {return (<div className="grid w-full grid-cols-1 md:grid-cols-5">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 b36381087c..554911c1d3 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,6 +1,6 @@"use client";-import { createNewAccount } from "@/lib/actions/create-new-account";+import { createNewAccountAction } from "@/lib/actions/create-new-account";import z from "@/lib/zod";import { signUpSchema } from "@/lib/zod/schemas/auth";import { Button, Input } from "@dub/ui";@@ -8,32 +8,39 @@ 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";export default function SignUpEmail() {const router = useRouter();- const { executeAsync, result, status, isExecuting } =- useAction(createNewAccount);const {- reset,register,handleSubmit,+ getValues,formState: { errors, isDirty },} = useForm<z.infer<typeof signUpSchema>>({resolver: zodResolver(signUpSchema),defaultValues: {- email: "[email protected]",+ email: "[email protected]",password: "12345678aB#",},});- const onSubmit = handleSubmit(async (data) => {- await executeAsync(data);-- if (status === "hasSucceeded") {- reset();- }- });+ const { executeAsync, result, status, isExecuting } = useAction(+ createNewAccountAction,+ {+ onSuccess: () => {+ toast.success(+ "Account created successfully. Please verify your email to login.",+ );+ router.push(+ `/register/verify-email?email=${encodeURIComponent(+ getValues("email"),+ )}`,+ );+ },+ },+ );return (<>@@ -51,7 +58,11 @@ export default function SignUpEmail() {</div>)}- <form onSubmit={onSubmit}>+ <form+ onSubmit={handleSubmit(async (data) => {+ await executeAsync(data);+ })}+ ><div className="flex flex-col space-y-4"><Inputtype="email"@@ -59,16 +70,14 @@ export default function SignUpEmail() {autoComplete="email"required{...register("email")}- error={result.validationErrors?.email?.[0] || errors.email?.message}+ error={errors.email?.message}/><Inputtype="password"placeholder="Password"required{...register("password")}- error={- result.validationErrors?.password?.[0] || errors.password?.message- }+ error={errors.password?.message}/><Buttontext={status === "executing" ? "Signing Up..." : "Sign Up"}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..646bf93bcd--- /dev/null+++ b/apps/web/app/app.dub.co/(auth)/register/verify-email/form.tsx@@ -0,0 +1,74 @@+"use client";++import { verifyEmailAction } from "@/lib/actions/verify-email";+import { Button, Input } from "@dub/ui";+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 [code, setCode] = useState("");+ const searchParams = useSearchParams();++ const { executeAsync, result, status, isExecuting } = useAction(+ verifyEmailAction,+ {+ onSuccess() {+ toast.success("Success.");+ 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 space-y-4">+ <Input+ type="text"+ placeholder="Enter OTP"+ required+ value={code}+ onChange={(e) => setCode(e.target.value)}+ maxLength={6}+ />+ <input type="hidden" value={email} />+ <Button+ text={status === "executing" ? "Verifying..." : "Continue"}+ type="submit"+ loading={isExecuting}+ disabled={!code}+ />+ </div>+ </form>+ </>+ );+}diff --git a/apps/web/app/app.dub.co/(auth)/register/otp/page.tsx b/apps/web/app/app.dub.co/(auth)/register/verify-email/page.tsxsimilarity index 76%rename from apps/web/app/app.dub.co/(auth)/register/otp/page.tsxrename to apps/web/app/app.dub.co/(auth)/register/verify-email/page.tsxindex 561fc4cc34..1b3e3794af 100644--- a/apps/web/app/app.dub.co/(auth)/register/otp/page.tsx+++ b/apps/web/app/app.dub.co/(auth)/register/verify-email/page.tsx@@ -1,14 +1,12 @@-import { constructMetadata, HOME_DOMAIN } from "@dub/utils";-import VerifyOTPForm from "./form";import { BlurImage, Button, Logo } from "@dub/ui";+import { constructMetadata, HOME_DOMAIN } from "@dub/utils";import { Suspense } from "react";+import VerifyEmailForm from "./form";export const metadata = constructMetadata({title: `Create your ${process.env.NEXT_PUBLIC_APP_NAME} account`,});--const logos = ["vercel","perplexity",@@ -24,7 +22,9 @@ const logos = ["cal",];-export default function VerifyOTPPage() {+export const runtime = "nodejs";++export default function VerifyEmailPage() {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">@@ -33,26 +33,9 @@ export default function VerifyOTPPage() {<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>+ <h3 className="text-xl font-semibold">Verify your email</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>+ Enter the 6 digits verification code sent to your email address.</p></div><div className="flex flex-col space-y-3 bg-gray-50 px-4 py-8 sm:px-16">@@ -64,7 +47,7 @@ export default function VerifyOTPPage() {</>}>- <VerifyOTPForm />+ <VerifyEmailForm /></Suspense></div></div>diff --git a/apps/web/lib/actions/create-new-account.ts b/apps/web/lib/actions/create-new-account.tsindex dd8a844234..323df9b2ec 100644--- a/apps/web/lib/actions/create-new-account.ts+++ b/apps/web/lib/actions/create-new-account.ts@@ -12,7 +12,7 @@ import { throwIfAuthenticated } from "./middlewares/throw-if-authenticated";import { actionClient } from "./safe-action";// Sign up a new user using email and password-export const createNewAccount = actionClient+export const createNewAccountAction = actionClient.schema(signUpSchema, {handleValidationErrorsShape: (ve) =>flattenValidationErrors(ve).fieldErrors,diff --git a/apps/web/lib/actions/verify-email.ts b/apps/web/lib/actions/verify-email.tsnew file mode 100644index 0000000000..8565a9d116--- /dev/null+++ b/apps/web/lib/actions/verify-email.ts@@ -0,0 +1,53 @@+"use server";++import { prisma } from "@/lib/prisma";+import { flattenValidationErrors } from "next-safe-action";+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 verificationToken = await prisma.verificationToken.findUnique({+ where: {+ identifier: email,+ token: code,+ expires: {+ gte: new Date(),+ },+ },+ });++ if (!verificationToken) {+ throw new Error("Incorrect code.");+ }++ await Promise.all([+ prisma.verificationToken.delete({+ where: {+ token: code,+ },+ }),++ prisma.user.update({+ where: {+ email,+ },+ data: {+ emailVerified: new Date(),+ },+ }),+ ]);++ return {+ status: "ok",+ };+ });diff --git a/apps/web/lib/middleware/app.ts b/apps/web/lib/middleware/app.tsindex 398075e5bd..57041a3ea5 100644--- a/apps/web/lib/middleware/app.ts+++ b/apps/web/lib/middleware/app.ts@@ -14,6 +14,7 @@ export default async function AppMiddleware(req: NextRequest) {!user &&path !== "/login" &&path !== "/register" &&+ path !== "/register/verify-email" &&path !== "/auth/saml" &&!path.startsWith("/auth/reset-password/")) {diff --git a/apps/web/lib/zod/schemas/auth.ts b/apps/web/lib/zod/schemas/auth.tsindex 6fe48e2fe6..0aaacf9022 100644--- a/apps/web/lib/zod/schemas/auth.ts+++ b/apps/web/lib/zod/schemas/auth.ts@@ -38,3 +38,8 @@ export const signUpSchema = z.object({email: z.string().email(),password: passwordSchema,});++export const verifyEmailSchema = z.object({+ email: z.string().email().min(1),+ code: z.string().min(6),+});