The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add auth UIs to partners portal
Tim Wilsonf532760c4127
diff --git a/apps/web/app/app.dub.co/(auth)/auth/reset-password/[token]/page.tsx b/apps/web/app/app.dub.co/(auth)/auth/reset-password/[token]/page.tsxindex 028ad0b876..75b43a88e9 100644--- a/apps/web/app/app.dub.co/(auth)/auth/reset-password/[token]/page.tsx+++ b/apps/web/app/app.dub.co/(auth)/auth/reset-password/[token]/page.tsx@@ -1,7 +1,7 @@import { prisma } from "@/lib/prisma";+import { ResetPasswordForm } from "@/ui/auth/reset-password-form";import EmptyState from "@/ui/shared/empty-state";import { InputPassword } from "@dub/ui";-import { ResetPasswordForm } from "./form";export const runtime = "nodejs";@@ -26,14 +26,14 @@ export default async function ResetPasswordPage({ params: { token } }: Props) {return (<div className="relative z-10 my-10 flex min-h-full w-full items-center justify-center">- <div className="w-full overflow-hidden border-y border-gray-200 sm:rounded-2xl sm:border sm:shadow-xl">+ <div className="mx-auto 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"><h3 className="text-xl font-semibold">Reset your password</h3><p className="text-sm text-gray-500">Enter new password for your account.</p></div>- <div className="flex flex-col space-y-3 bg-gray-50 px-4 py-8 sm:px-16">+ <div className="flex flex-col gap-3 bg-gray-50 px-4 py-8 sm:px-16"><ResetPasswordForm /></div></div>diff --git a/apps/web/app/app.dub.co/(auth)/forgot-password/form.tsx b/apps/web/app/app.dub.co/(auth)/forgot-password/form.tsxdeleted file mode 100644index 60744f6052..0000000000--- a/apps/web/app/app.dub.co/(auth)/forgot-password/form.tsx+++ /dev/null@@ -1,77 +0,0 @@-"use client";--import { requestPasswordResetAction } from "@/lib/actions/request-password-reset";-import { Button, Input, useMediaQuery } from "@dub/ui";-import { useAction } from "next-safe-action/hooks";-import Link from "next/link";-import { useRouter, useSearchParams } from "next/navigation";-import { useState } from "react";-import { toast } from "sonner";--export const ForgotPasswordForm = () => {- const router = useRouter();- const { isMobile } = useMediaQuery();- const searchParams = useSearchParams();- const [email, setEmail] = useState(searchParams.get("email") || "");-- const { executeAsync, isExecuting } = useAction(requestPasswordResetAction, {- onSuccess() {- toast.success(- "You will receive an email with instructions to reset your password.",- );- router.push("/login");- },- onError({ error }) {- toast.error(error.serverError?.serverError);- },- });-- 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">Reset your password</h3>- </div>-- <div className="grid gap-3 bg-gray-50 px-4 py-8 sm:px-16">- <form- onSubmit={(e) => {- e.preventDefault();- executeAsync({ email });- }}- >- <div className="flex flex-col gap-8">- <label>- <span className="text-sm font-medium text-gray-700">Email</span>- <Input- type="email"- autoFocus={!isMobile}- value={email}- placeholder="[email protected]"- onChange={(e) => setEmail(e.target.value)}- className="mt-1"- />- </label>- <Button- type="submit"- text={isExecuting ? "Sending..." : "Send reset link"}- loading={isExecuting}- disabled={email.length < 3}- />- </div>- </form>- </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)/forgot-password/page.tsx b/apps/web/app/app.dub.co/(auth)/forgot-password/page.tsxindex 6c0dbfb83f..b152a09e42 100644--- a/apps/web/app/app.dub.co/(auth)/forgot-password/page.tsx+++ b/apps/web/app/app.dub.co/(auth)/forgot-password/page.tsx@@ -1,6 +1,7 @@+import { ForgotPasswordForm } from "@/ui/auth/forgot-password-form";import { AuthLayout } from "@/ui/layout/auth-layout";import { constructMetadata } from "@dub/utils";-import { ForgotPasswordForm } from "./form";+import Link from "next/link";export const metadata = constructMetadata({title: `Forgot Password for ${process.env.NEXT_PUBLIC_APP_NAME}`,@@ -9,7 +10,24 @@ export const metadata = constructMetadata({export default function ForgotPasswordPage() {return (<AuthLayout>- <ForgotPasswordForm />+ <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">Reset your password</h3>+ </div>++ <div className="bg-gray-50 px-4 py-8 sm:px-16">+ <ForgotPasswordForm />+ </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></AuthLayout>);}diff --git a/apps/web/app/app.dub.co/(auth)/login/form.tsx b/apps/web/app/app.dub.co/(auth)/login/form.tsxdeleted file mode 100644index 4d0c8f1f20..0000000000--- a/apps/web/app/app.dub.co/(auth)/login/form.tsx+++ /dev/null@@ -1,495 +0,0 @@-"use client";--import { emailSchema } from "@/lib/zod/schemas/auth";-import {- AnimatedSizeContainer,- Button,- Github,- Google,- InfoTooltip,- Input,- useLocalStorage,- useMediaQuery,-} from "@dub/ui";-import { InputPassword } from "@dub/ui/src/icons";-import { cn } from "@dub/utils";-import { Lock, Mail } from "lucide-react";-import { signIn } from "next-auth/react";-import Link from "next/link";-import { useRouter, useSearchParams } from "next/navigation";-import {- Dispatch,- SetStateAction,- createContext,- useContext,- useEffect,- useRef,- useState,-} from "react";-import { toast } from "sonner";--export const authMethods = [- "google",- "github",- "email",- "saml",- "password",-] as const;--export type AuthMethod = (typeof authMethods)[number];--const errorCodes = {- "no-credentials": "Please provide an email and password.",- "invalid-credentials": "Email or password is incorrect.",- "exceeded-login-attempts":- "Account has been locked due to too many login attempts. Please contact support to unlock your account.",- "too-many-login-attempts": "Too many login attempts. Please try again later.",- "email-not-verified": "Please verify your email address.",- Callback:- "We encountered an issue processing your request. Please try again or contact support if the problem persists.",- OAuthSignin:- "There was an issue signing you in. Please ensure your provider settings are correct.",- OAuthCallback:- "We faced a problem while processing the response from the OAuth provider. Please try again.",-};--const LoginFormContext = createContext<{- authMethod: AuthMethod | undefined;- setAuthMethod: Dispatch<SetStateAction<AuthMethod | undefined>>;- clickedMethod: AuthMethod | undefined;- showPasswordField: boolean;- setShowPasswordField: Dispatch<SetStateAction<boolean>>;- setClickedMethod: Dispatch<SetStateAction<AuthMethod | undefined>>;- setLastUsedAuthMethod: Dispatch<SetStateAction<AuthMethod | undefined>>;- setShowSSOOption: Dispatch<SetStateAction<boolean>>;-}>({- authMethod: undefined,- setAuthMethod: () => {},- clickedMethod: undefined,- showPasswordField: false,- setShowPasswordField: () => {},- setClickedMethod: () => {},- setLastUsedAuthMethod: () => {},- setShowSSOOption: () => {},-});--export default function LoginForm() {- const searchParams = useSearchParams();- const next = searchParams?.get("next");- const [showPasswordField, setShowPasswordField] = useState(false);- const [showSSOOption, setShowSSOOption] = useState(false);- const [clickedMethod, setClickedMethod] = useState<AuthMethod | undefined>(- undefined,- );-- const [lastUsedAuthMethodLive, setLastUsedAuthMethod] = useLocalStorage<- AuthMethod | undefined- >("last-used-auth-method", undefined);- const { current: lastUsedAuthMethod } = useRef<AuthMethod | undefined>(- lastUsedAuthMethodLive,- );-- const [authMethod, setAuthMethod] = useState<AuthMethod | undefined>(- authMethods.find((m) => m === lastUsedAuthMethodLive) ?? "email",- );-- useEffect(() => {- const error = searchParams?.get("error");- if (error) {- toast.error(- errorCodes[error] ||- "An unexpected error occurred. Please try again later.",- );- }- }, [searchParams]);-- const { isMobile } = useMediaQuery();-- useEffect(() => {- // when leave page, reset state- return () => setClickedMethod(undefined);- }, []);-- const GoogleButton = () => {- return (- <Button- text="Continue with Google"- variant="secondary"- onClick={() => {- setClickedMethod("google");- setLastUsedAuthMethod("google");- signIn("google", {- ...(next && next.length > 0 ? { callbackUrl: next } : {}),- });- }}- loading={clickedMethod === "google"}- disabled={clickedMethod && clickedMethod !== "google"}- icon={<Google className="size-4" />}- />- );- };-- const GitHubButton = () => {- return (- <Button- text="Continue with Github"- variant="secondary"- onClick={() => {- setClickedMethod("github");- setLastUsedAuthMethod("github");- signIn("github", {- ...(next && next.length > 0 ? { callbackUrl: next } : {}),- });- }}- loading={clickedMethod === "github"}- disabled={clickedMethod && clickedMethod !== "github"}- icon={<Github className="size-4 text-black" />}- />- );- };-- const SignInWithSSO = () => {- return (- <form- onSubmit={async (e) => {- e.preventDefault();- setClickedMethod("saml");- fetch("/api/auth/saml/verify", {- method: "POST",- body: JSON.stringify({ slug: e.currentTarget.slug.value }),- }).then(async (res) => {- const { data, error } = await res.json();- if (error) {- toast.error(error);- setClickedMethod(undefined);- return;- }- setLastUsedAuthMethod("saml");- await signIn("saml", undefined, {- tenant: data.workspaceId,- product: "Dub",- });- });- }}- className="flex flex-col space-y-3"- >- {showSSOOption && (- <div>- <div className="mb-4 mt-1 border-t border-gray-300" />- <div className="flex items-center space-x-2">- <h2 className="text-sm font-medium text-gray-900">- Workspace Slug- </h2>- <InfoTooltip- content={`This is your workspace's unique identifier on ${process.env.NEXT_PUBLIC_APP_NAME}. E.g. app.dub.co/acme is "acme".`}- />- </div>- <input- id="slug"- name="slug"- autoFocus={!isMobile}- type="text"- placeholder="my-team"- autoComplete="off"- required- className="mt-1 block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-black focus:outline-none focus:ring-black sm:text-sm"- />- </div>- )}-- <Button- text="Continue with SAML SSO"- variant="secondary"- icon={<Lock className="size-4" />}- {...(!showSSOOption && {- type: "button",- onClick: (e) => {- e.preventDefault();- setShowSSOOption(true);- },- })}- loading={clickedMethod === "saml"}- disabled={clickedMethod && clickedMethod !== "saml"}- />- </form>- );- };-- const authProviders = [- {- method: "google",- component: <GoogleButton />,- },- {- method: "github",- component: <GitHubButton />,- },- {- method: "email",- component: <SignInWithEmail />,- },- {- method: "saml",- component: <SignInWithSSO />,- },- ];-- const authMethodComponent = authProviders.find(- (provider) => provider.method === authMethod,- )?.component;-- const showEmailPasswordOnly = authMethod === "email" && showPasswordField;-- return (- <LoginFormContext.Provider- value={{- authMethod,- setAuthMethod,- clickedMethod,- showPasswordField,- setShowPasswordField,- setClickedMethod,- setLastUsedAuthMethod,- setShowSSOOption,- }}- >- <div className="w-full max-w-md overflow-hidden border-y border-gray-200 sm:rounded-2xl sm:border sm:shadow-sm">- <div className="border-b border-gray-200 bg-white pb-6 pt-8 text-center">- <h3 className="text-lg font-semibold">Sign in to your Dub account</h3>- </div>- <div className="grid gap-3 bg-gray-50 px-4 py-8 sm:px-16">- <AnimatedSizeContainer height>- <div className="grid gap-3 p-1">- {authMethod && (- <div className="flex flex-col gap-2">- {authMethodComponent}-- {!showEmailPasswordOnly &&- authMethod === lastUsedAuthMethod && (- <div className="text-center text-xs">- <span className="text-gray-500">- You signed in with{" "}- {lastUsedAuthMethod.charAt(0).toUpperCase() +- lastUsedAuthMethod.slice(1)}{" "}- last time- </span>- </div>- )}- <div className="my-2 flex flex-shrink items-center justify-center gap-2">- <div className="grow basis-0 border-b border-gray-300" />- <span className="text-xs font-normal uppercase leading-none text-gray-500">- or- </span>- <div className="grow basis-0 border-b border-gray-300" />- </div>- </div>- )}-- {showEmailPasswordOnly ? (- <div className="mt-2 text-center text-sm text-gray-500">- <button- type="button"- onClick={() => setShowPasswordField(false)}- className="font-semibold text-gray-500 transition-colors hover:text-black"- >- Continue with another method- </button>- </div>- ) : (- authProviders- .filter((provider) => provider.method !== authMethod)- .map((provider) => (- <div key={provider.method}>{provider.component}</div>- ))- )}- </div>- </AnimatedSizeContainer>- </div>- </div>-- <p className="mt-4 text-center text-sm text-gray-500">- Don't have an account? - <Link- href="register"- className="font-semibold text-gray-500 underline underline-offset-2 transition-colors hover:text-black"- >- Sign up- </Link>- </p>- </LoginFormContext.Provider>- );-}--const SignInWithEmail = () => {- const router = useRouter();- const searchParams = useSearchParams();- const next = searchParams?.get("next");- const { isMobile } = useMediaQuery();-- const [email, setEmail] = useState("");- const [password, setPassword] = useState("");- const [checkingEmailPassword, setCheckingEmailPassword] = useState(false);-- const {- showPasswordField,- setShowPasswordField,- setClickedMethod,- authMethod,- setAuthMethod,- clickedMethod,- setLastUsedAuthMethod,- setShowSSOOption,- } = useContext(LoginFormContext);-- return (- <>- <form- onSubmit={async (e) => {- e.preventDefault();-- // Check if the user can enter a password, and if so display the field- if (!showPasswordField) {- const { success } = emailSchema.safeParse(email);-- if (success) {- try {- setCheckingEmailPassword(true);- const res = await fetch("/api/auth/account-exists", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ email }),- });- setCheckingEmailPassword(false);-- const { accountExists, hasPassword } = await res.json();- if (accountExists && hasPassword) {- setShowPasswordField(true);- return;- }- } catch (e) {- console.error("Failed to determine if user has password", e);- }- }- }-- setClickedMethod("email");-- fetch("/api/auth/account-exists", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ email }),- }).then(async (res) => {- if (!res.ok) {- const error = await res.text();- toast.error(error);- setClickedMethod(undefined);- return;- }- const { accountExists, hasPassword } = await res.json();- if (accountExists) {- const provider =- hasPassword && password ? "credentials" : "email";-- signIn(provider, {- email,- redirect: false,- ...(password && { password }),- ...(next ? { callbackUrl: next } : {}),- }).then((res) => {- if (!res) return;-- // Handle errors- if (!res.ok && res.error) {- if (errorCodes[res.error]) {- toast.error(errorCodes[res.error]);- } else {- toast.error(res.error);- }-- setClickedMethod(undefined);- return;- }-- // Handle success- setLastUsedAuthMethod("email");- if (provider === "email") {- toast.success("Email sent - check your inbox!");- setEmail("");- setClickedMethod(undefined);- } else if (provider === "credentials") {- router.push(next ?? "/");- }- });- } else {- setClickedMethod(undefined);- toast.error("No account found with that email address.");- }- });- }}- className="flex flex-col gap-y-3"- >- {authMethod === "email" && (- <input- id="email"- name="email"- autoFocus={!isMobile && !showPasswordField}- type="email"- placeholder="[email protected]"- autoComplete="email"- required- value={email}- onChange={(e) => setEmail(e.target.value)}- className={cn(- "block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-black focus:outline-none focus:ring-black sm:text-sm",- {- "pr-10": checkingEmailPassword,- },- )}- />- )}-- {showPasswordField && (- <div>- <Input- type="password"- autoFocus={!isMobile}- value={password}- placeholder="Password (optional)"- onChange={(e) => setPassword(e.target.value)}- />- </div>- )}-- <Button- text={`Continue with ${password ? "Password" : "Email"}`}- variant="secondary"- icon={- password ? (- <InputPassword className="size-4 text-gray-600" />- ) : (- <Mail className="size-4 text-gray-600" />- )- }- {...(authMethod !== "email" && {- type: "button",- onClick: (e) => {- e.preventDefault();- setShowSSOOption(false);- setAuthMethod("email");- },- })}- loading={checkingEmailPassword || clickedMethod === "email"}- disabled={clickedMethod && clickedMethod !== "email"}- />- </form>- {showPasswordField && (- <Link- href={`/forgot-password?email=${encodeURIComponent(email)}`}- className="text-center text-xs text-gray-500 transition-colors hover:text-black"- >- Forgot password?- </Link>- )}- </>- );-};diff --git a/apps/web/app/app.dub.co/(auth)/login/page.tsx b/apps/web/app/app.dub.co/(auth)/login/page.tsxindex 59cbab8dd8..755c7e3afa 100644--- a/apps/web/app/app.dub.co/(auth)/login/page.tsx+++ b/apps/web/app/app.dub.co/(auth)/login/page.tsx@@ -1,6 +1,7 @@+import LoginForm from "@/ui/auth/login/login-form";import { AuthLayout } from "@/ui/layout/auth-layout";import { constructMetadata } from "@dub/utils";-import LoginForm from "./form";+import Link from "next/link";export const metadata = constructMetadata({title: `Sign in to ${process.env.NEXT_PUBLIC_APP_NAME}`,@@ -9,7 +10,23 @@ export const metadata = constructMetadata({export default function LoginPage() {return (<AuthLayout>- <LoginForm />+ <div className="w-full max-w-md overflow-hidden border-y border-gray-200 sm:rounded-2xl sm:border sm:shadow-sm">+ <div className="border-b border-gray-200 bg-white pb-6 pt-8 text-center">+ <h3 className="text-lg font-semibold">Sign in to your Dub account</h3>+ </div>+ <div className="bg-gray-50 px-4 py-8 sm:px-16">+ <LoginForm />+ </div>+ </div>+ <p className="mt-4 text-center text-sm text-gray-500">+ Don't have an account? + <Link+ href="register"+ className="font-semibold text-gray-500 underline underline-offset-2 transition-colors hover:text-black"+ >+ Sign up+ </Link>+ </p></AuthLayout>);}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.tsxindex a9ea473348..4586bbc1b4 100644--- a/apps/web/app/app.dub.co/(auth)/register/page-client.tsx+++ b/apps/web/app/app.dub.co/(auth)/register/page-client.tsx@@ -1,8 +1,13 @@"use client";-import { RegisterProvider, useRegisterContext } from "./context";-import { SignUpForm } from "./signup-form";-import { VerifyEmailForm } from "./verify-email-form";+import {+ RegisterProvider,+ useRegisterContext,+} from "@/ui/auth/register/context";+import { SignUpForm } from "@/ui/auth/register/signup-form";+import { VerifyEmailForm } from "@/ui/auth/register/verify-email-form";+import { truncate } from "@dub/utils";+import Link from "next/link";export default function RegisterPageClient() {return (@@ -12,14 +17,65 @@ export default function RegisterPageClient() {);}+function SignUp() {+ 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="border-b border-gray-200 bg-white pb-6 pt-8 text-center">+ <h3 className="text-lg font-semibold">Get started with Dub</h3>+ </div>+ <div className="bg-gray-50 px-4 py-8 sm:px-16">+ <SignUpForm />+ </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>+ </>+ );+}++function Verify() {+ const { email } = useRegisterContext();++ 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 gap-3 border-b border-gray-200 bg-white px-4 pb-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="bg-gray-50 px-4 py-8 sm:px-16">+ <VerifyEmailForm />+ </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>+ </>+ );+}+const RegisterFlow = () => {const { step } = useRegisterContext();- if (step === "signup") {- return <SignUpForm />;- }-- if (step === "verify") {- return <VerifyEmailForm />;- }+ if (step === "signup") return <SignUp />;+ if (step === "verify") return <Verify />;};diff --git a/apps/web/app/app.dub.co/(auth)/register/signup-form.tsx b/apps/web/app/app.dub.co/(auth)/register/signup-form.tsxdeleted file mode 100644index 87805191ab..0000000000--- a/apps/web/app/app.dub.co/(auth)/register/signup-form.tsx+++ /dev/null@@ -1,39 +0,0 @@-"use client";--import Link from "next/link";-import { SignUpEmail } from "./signup-email";-import { SignUpOAuth } from "./signup-oauth";--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">- <div className="border-b border-gray-200 bg-white pb-6 pt-8 text-center">- <h3 className="text-lg font-semibold">Get started with Dub</h3>- </div>-- <div className="grid gap-3 bg-gray-50 px-4 py-8 sm:px-16">- <SignUpEmail />- <div className="my-2 flex flex-shrink items-center justify-center gap-2">- <div className="grow basis-0 border-b border-gray-300" />- <span className="text-xs font-normal uppercase leading-none text-gray-500">- or- </span>- <div className="grow basis-0 border-b border-gray-300" />- </div>- <SignUpOAuth />- </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/signup-oauth.tsx b/apps/web/app/app.dub.co/(auth)/register/signup-oauth.tsxdeleted file mode 100644index 1d4f0785fe..0000000000--- a/apps/web/app/app.dub.co/(auth)/register/signup-oauth.tsx+++ /dev/null@@ -1,50 +0,0 @@-"use client";--import { Button, Github, Google } from "@dub/ui";-import { signIn } from "next-auth/react";-import { useSearchParams } from "next/navigation";-import { useEffect, useState } from "react";--export const SignUpOAuth = () => {- const searchParams = useSearchParams();- const next = searchParams?.get("next");- const [clickedGoogle, setClickedGoogle] = useState(false);- const [clickedGithub, setClickedGithub] = useState(false);-- useEffect(() => {- // when leave page, reset state- return () => {- setClickedGoogle(false);- setClickedGithub(false);- };- }, []);-- return (- <>- <Button- variant="secondary"- text="Continue with Google"- onClick={() => {- setClickedGoogle(true);- signIn("google", {- ...(next && next.length > 0 ? { callbackUrl: next } : {}),- });- }}- loading={clickedGoogle}- icon={<Google className="h-4 w-4" />}- />- <Button- variant="secondary"- text="Continue with GitHub"- onClick={() => {- setClickedGithub(true);- signIn("github", {- ...(next && next.length > 0 ? { callbackUrl: next } : {}),- });- }}- loading={clickedGithub}- icon={<Github className="h-4 w-4" />}- />- </>- );-};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 ebeed75a13..0000000000--- a/apps/web/app/app.dub.co/(auth)/register/verify-email-form.tsx+++ /dev/null@@ -1,144 +0,0 @@-"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 { signIn } from "next-auth/react";-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";-import { ResendOtp } from "./resend-otp";--export const VerifyEmailForm = () => {- const router = useRouter();- const { isMobile } = useMediaQuery();- const [code, setCode] = useState("");- const { email, password } = useRegisterContext();- const [isInvalidCode, setIsInvalidCode] = useState(false);- const [isRedirecting, setIsRedirecting] = useState(false);-- const { executeAsync, isExecuting } = useAction(createUserAccountAction, {- async onSuccess() {- toast.success("Account created! Redirecting to dashboard...");- setIsRedirecting(true);-- const response = await signIn("credentials", {- email,- password,- redirect: false,- });-- if (response?.ok) {- router.push("/onboarding");- } else {- toast.error("Failed to redirect to dashboard.");- }- },- onError({ error }) {- toast.error(error.serverError?.serverError);- setCode("");- setIsInvalidCode(true);- },- });-- 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>- <OTPInput- maxLength={6}- value={code}- onChange={(code) => {- setIsInvalidCode(false);- setCode(code);- }}- 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-2 ring-gray-200",- isInvalidCode && "border-red-500 ring-red-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>- )}- onComplete={() => {- executeAsync({ email, password, code });- }}- />- {isInvalidCode && (- <p className="mt-2 text-center text-sm text-red-500">- Invalid code. Please try again.- </p>- )}-- <Button- className="mt-8"- text={isExecuting ? "Verifying..." : "Continue"}- type="submit"- loading={isExecuting || isRedirecting}- disabled={!code || code.length < 6}- />- </div>- </form>-- <ResendOtp email={email} />- </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/partners.dub.co/(onboarding)/(auth)/auth/reset-password/[token]/page.tsx b/apps/web/app/partners.dub.co/(onboarding)/(auth)/auth/reset-password/[token]/page.tsxnew file mode 100644index 0000000000..cc2a96031d--- /dev/null+++ b/apps/web/app/partners.dub.co/(onboarding)/(auth)/auth/reset-password/[token]/page.tsx@@ -0,0 +1,60 @@+import { prisma } from "@/lib/prisma";+import { ResetPasswordForm } from "@/ui/auth/reset-password-form";+import EmptyState from "@/ui/shared/empty-state";+import { InputPassword } from "@dub/ui";++export const runtime = "nodejs";++interface Props {+ params: {+ token: string;+ };+}++export default async function ResetPasswordPage({ params: { token } }: Props) {+ const validToken = await isValidToken(token);++ if (!validToken) {+ return (+ <div className="my-10 md:mt-16 lg:mt-20">+ <EmptyState+ icon={InputPassword}+ title="Invalid Reset Token"+ description="The password reset token is invalid or expired. Please request a new one."+ />+ </div>+ );+ }++ return (+ <div className="mx-auto my-10 w-full max-w-md md:mt-16 lg:mt-20">+ <div className="rounded-lg border border-neutral-200 bg-white p-8 pb-10">+ <h1 className="text-lg font-medium text-neutral-800">+ Reset your password+ </h1>+ <p className="mt-3 text-sm text-gray-500">+ Enter a new password for your account.+ </p>+ <div className="mt-8 text-left">+ <ResetPasswordForm />+ </div>+ </div>+ </div>+ );+}++const isValidToken = async (token: string) => {+ const resetToken = await prisma.passwordResetToken.findUnique({+ where: {+ token,+ expires: {+ gte: new Date(),+ },+ },+ select: {+ token: true,+ },+ });++ return !!resetToken;+};diff --git a/apps/web/app/partners.dub.co/(onboarding)/(auth)/forgot-password/page.tsx b/apps/web/app/partners.dub.co/(onboarding)/(auth)/forgot-password/page.tsxnew file mode 100644index 0000000000..3283a9d8a7--- /dev/null+++ b/apps/web/app/partners.dub.co/(onboarding)/(auth)/forgot-password/page.tsx@@ -0,0 +1,26 @@+import { ForgotPasswordForm } from "@/ui/auth/forgot-password-form";+import Link from "next/link";++export default function ForgotPasswordPage() {+ return (+ <div className="mx-auto my-10 w-full max-w-md md:mt-16 lg:mt-20">+ <div className="rounded-lg border border-neutral-200 bg-white p-8 pb-10">+ <h1 className="text-lg font-medium text-neutral-800">+ Reset your password+ </h1>+ <div className="mt-8">+ <ForgotPasswordForm />+ </div>+ </div>+ <p className="mt-4 text-center text-sm text-gray-500">+ Don't have an account? + <Link+ href="register"+ className="font-semibold text-gray-500 underline underline-offset-2 transition-colors hover:text-black"+ >+ Sign up+ </Link>+ </p>+ </div>+ );+}diff --git a/apps/web/app/partners.dub.co/(onboarding)/(auth)/login/page.tsx b/apps/web/app/partners.dub.co/(onboarding)/(auth)/login/page.tsxnew file mode 100644index 0000000000..b43e6c03bb--- /dev/null+++ b/apps/web/app/partners.dub.co/(onboarding)/(auth)/login/page.tsx@@ -0,0 +1,29 @@+import LoginForm from "@/ui/auth/login/login-form";+import { ClientOnly } from "@dub/ui";+import Link from "next/link";++export default function LoginPage() {+ return (+ <div className="mx-auto my-10 w-full max-w-md md:mt-16 lg:mt-20">+ <div className="rounded-lg border border-neutral-200 bg-white p-8 pb-10">+ <h1 className="text-lg font-medium text-neutral-800">+ Sign in to your Dub Partner account+ </h1>+ <div className="mt-8">+ <ClientOnly>+ <LoginForm methods={["email", "password", "google"]} />+ </ClientOnly>+ </div>+ </div>+ <p className="mt-4 text-center text-sm text-gray-500">+ Don't have an account? + <Link+ href="register"+ className="font-semibold text-gray-500 underline underline-offset-2 transition-colors hover:text-black"+ >+ Sign up+ </Link>+ </p>+ </div>+ );+}diff --git a/apps/web/app/partners.dub.co/(onboarding)/(auth)/register/page-client.tsx b/apps/web/app/partners.dub.co/(onboarding)/(auth)/register/page-client.tsxnew file mode 100644index 0000000000..20666966b3--- /dev/null+++ b/apps/web/app/partners.dub.co/(onboarding)/(auth)/register/page-client.tsx@@ -0,0 +1,83 @@+"use client";++import {+ RegisterProvider,+ useRegisterContext,+} from "@/ui/auth/register/context";+import { SignUpForm } from "@/ui/auth/register/signup-form";+import { VerifyEmailForm } from "@/ui/auth/register/verify-email-form";+import { truncate } from "@dub/utils";+import Link from "next/link";++export default function RegisterPageClient() {+ return (+ <RegisterProvider>+ <div className="mx-auto my-10 w-full max-w-md md:mt-16 lg:mt-20">+ <RegisterFlow />+ </div>+ </RegisterProvider>+ );+}++function SignUp() {+ return (+ <>+ <div className="rounded-lg border border-neutral-200 bg-white p-8 pb-10">+ <h1 className="text-lg font-medium text-neutral-800">+ Create a Dub Partner account+ </h1>+ <div className="mt-8">+ <SignUpForm methods={["email", "google"]} />+ </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>+ </>+ );+}++function Verify() {+ const { email } = useRegisterContext();++ return (+ <>+ <div className="rounded-lg border border-neutral-200 bg-white p-8 pb-10">+ <h1 className="text-lg font-medium text-neutral-800">+ Verify your email address+ </h1>+ <p className="mt-3 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 className="mt-8">+ <VerifyEmailForm />+ </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>+ </>+ );+}++const RegisterFlow = () => {+ const { step } = useRegisterContext();++ if (step === "signup") return <SignUp />;+ if (step === "verify") return <Verify />;+};diff --git a/apps/web/app/partners.dub.co/(onboarding)/(auth)/register/page.tsx b/apps/web/app/partners.dub.co/(onboarding)/(auth)/register/page.tsxnew file mode 100644index 0000000000..43ccaf4156--- /dev/null+++ b/apps/web/app/partners.dub.co/(onboarding)/(auth)/register/page.tsx@@ -0,0 +1,5 @@+import RegisterPageClient from "./page-client";++export default function RegisterPage() {+ return <RegisterPageClient />;+}diff --git a/apps/web/app/partners.dub.co/(onboarding)/layout.tsx b/apps/web/app/partners.dub.co/(onboarding)/layout.tsxindex 9615b603ef..3e8178a596 100644--- a/apps/web/app/partners.dub.co/(onboarding)/layout.tsx+++ b/apps/web/app/partners.dub.co/(onboarding)/layout.tsx@@ -12,7 +12,7 @@ export default function AdminAuthLayout({<div className="absolute inset-0 -translate-y-1/2 -scale-x-100 bg-[conic-gradient(from_-32deg,#f00_0deg,#EAB308_99deg,#5CFF80_162deg,#00FFF9_216deg,#3A8BFD_288deg,#855AFC_360deg)] opacity-25 blur-[200px]" /></div><div className="relative z-10 flex flex-col items-center justify-center">- <div className="relative mx-auto mt-10 flex w-full max-w-sm flex-col items-center px-3 text-center md:px-8">+ <div className="relative mt-10 flex w-full flex-col items-center px-3 text-center md:px-8"><div className="animate-slide-up-fade relative flex w-auto flex-col items-center [--offset:10px] [animation-duration:1.3s] [animation-fill-mode:both]"><Wordmark className="relative h-10" /><span className="text-sm font-medium text-neutral-700">diff --git a/apps/web/app/partners.dub.co/(onboarding)/login/page.tsx b/apps/web/app/partners.dub.co/(onboarding)/login/page.tsxdeleted file mode 100644index c0eb8d2dcb..0000000000--- a/apps/web/app/partners.dub.co/(onboarding)/login/page.tsx+++ /dev/null@@ -1,3 +0,0 @@-export default function PartnersLogin() {- return <div>PartnersLogin</div>;-}diff --git a/apps/web/app/partners.dub.co/(onboarding)/onboarding/page.tsx b/apps/web/app/partners.dub.co/(onboarding)/onboarding/page.tsxindex 680ccc897b..38aea95cfe 100644--- a/apps/web/app/partners.dub.co/(onboarding)/onboarding/page.tsx+++ b/apps/web/app/partners.dub.co/(onboarding)/onboarding/page.tsx@@ -3,7 +3,7 @@ import { OnboardingForm } from "./onboarding-form";export default function Onboarding() {return (- <div className="my-10 flex w-full flex-col items-center md:mt-16 lg:mt-20">+ <div className="mx-auto my-10 flex w-full max-w-sm flex-col items-center md:mt-16 lg:mt-20"><div className="animate-slide-up-fade flex size-10 items-center justify-center rounded-full border border-neutral-200 bg-white backdrop-blur-sm [--offset:8px] [animation-delay:250ms] [animation-duration:1s] [animation-fill-mode:both]"><ConnectedDots4 className="size-5 text-neutral-900" /></div>diff --git a/apps/web/app/partners.dub.co/(onboarding)/page-client.tsx b/apps/web/app/partners.dub.co/(onboarding)/page-client.tsxnew file mode 100644index 0000000000..09e519a750--- /dev/null+++ b/apps/web/app/partners.dub.co/(onboarding)/page-client.tsx@@ -0,0 +1,52 @@+"use client";++import { buttonVariants } from "@dub/ui";+import { LinkedIn, Twitter } from "@dub/ui/src/icons";+import { cn } from "@dub/utils";+import Link from "next/link";++export function PartnersPageClient() {+ return (+ <div className="mx-auto my-10 w-full max-w-md md:mt-16 lg:mt-20">+ <div className="rounded-lg border border-neutral-200 bg-white p-8 pb-10">+ <h1 className="text-lg font-medium text-neutral-800">+ You're on the waitlist+ </h1>+ <p className="mt-0.5 text-sm text-neutral-500">+ We'll be in touch once we're ready.+ </p>+ <div className="my-8 h-px w-full bg-neutral-300" />+ <h2 className="text-sm font-medium text-neutral-800">+ Subscribe to Dub news+ </h2>+ <p className="mt-0.5 text-sm text-neutral-500">+ Stay up to date with everything important.+ </p>+ <div className="mt-8 grid grid-cols-2 gap-4">+ <Link+ href="https://x.com/dubdotco"+ target="_blank"+ className={cn(+ buttonVariants({ variant: "secondary" }),+ "flex h-9 items-center justify-center rounded-md border px-4 text-center text-sm",+ )}+ >+ <Twitter className="mr-2 size-4" />+ @dubdotco+ </Link>+ <Link+ href="https://www.linkedin.com/company/dubinc"+ target="_blank"+ className={cn(+ buttonVariants({ variant: "secondary" }),+ "flex h-9 items-center justify-center rounded-md border px-4 text-center text-sm",+ )}+ >+ <LinkedIn className="mr-2 size-4 text-current" />+ dubinc+ </Link>+ </div>+ </div>+ </div>+ );+}diff --git a/apps/web/app/partners.dub.co/(onboarding)/page.tsx b/apps/web/app/partners.dub.co/(onboarding)/page.tsxindex 389505860b..4f052d5cee 100644--- a/apps/web/app/partners.dub.co/(onboarding)/page.tsx+++ b/apps/web/app/partners.dub.co/(onboarding)/page.tsx@@ -1,18 +1,10 @@import { constructMetadata } from "@dub/utils";+import { PartnersPageClient } from "./page-client";export const metadata = constructMetadata({noIndex: true,});export default function Partners() {- return (- <div>- <h1 className="animate-slide-up-fade mt-10 text-2xl font-medium [--offset:10px] [animation-delay:250ms] [animation-duration:1s] [animation-fill-mode:both]">- Dub Partner Portal- </h1>- <p className="animate-slide-up-fade mt-2 text-gray-500 [--offset:10px] [animation-delay:500ms] [animation-duration:1s] [animation-fill-mode:both]">- Coming soon- </p>- </div>- );+ return <PartnersPageClient />;}diff --git a/apps/web/lib/middleware/partners.ts b/apps/web/lib/middleware/partners.tsindex 70aeab00cf..13a007fd4e 100644--- a/apps/web/lib/middleware/partners.ts+++ b/apps/web/lib/middleware/partners.ts@@ -4,14 +4,23 @@ import { userIsInBeta } from "../edge-config";import { getDefaultPartner } from "./utils/get-default-partner";import { getUserViaToken } from "./utils/get-user-via-token";-const UNAUTHENTICATED_PATHS = ["/", "/login", "/register"];+const UNAUTHENTICATED_PATHS = [+ "/login",+ "/register",+ "/forgot-password",+ "/auth/reset-password",+];export default async function PartnersMiddleware(req: NextRequest) {const { path } = parse(req);+ const isUnauthenticatedPath = UNAUTHENTICATED_PATHS.some((p) =>+ path.startsWith(p),+ );+const user = await getUserViaToken(req);- if (!user && path !== "/login")+ if (!user && !isUnauthenticatedPath)return NextResponse.redirect(new URL("/login", req.url)); // Redirect unauthenticated users to loginelse if (user && path === "/login")return NextResponse.redirect(new URL("/", req.url)); // Redirect authenticated users to dashboard@@ -29,7 +38,7 @@ export default async function PartnersMiddleware(req: NextRequest) {}// Redirect to home if partner flag is off- if (!partnersEnabled && !UNAUTHENTICATED_PATHS.includes(path))+ if (user && !partnersEnabled && !isUnauthenticatedPath && path !== "/")return NextResponse.redirect(new URL("/", req.url));return NextResponse.rewrite(diff --git a/apps/web/ui/auth/forgot-password-form.tsx b/apps/web/ui/auth/forgot-password-form.tsxnew file mode 100644index 0000000000..53bc34cac9--- /dev/null+++ b/apps/web/ui/auth/forgot-password-form.tsx@@ -0,0 +1,58 @@+"use client";++import { requestPasswordResetAction } from "@/lib/actions/request-password-reset";+import { Button, Input, useMediaQuery } 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 const ForgotPasswordForm = () => {+ const router = useRouter();+ const { isMobile } = useMediaQuery();+ const searchParams = useSearchParams();+ const [email, setEmail] = useState(searchParams.get("email") || "");++ const { executeAsync, isExecuting } = useAction(requestPasswordResetAction, {+ onSuccess() {+ toast.success(+ "You will receive an email with instructions to reset your password.",+ );+ router.push("/login");+ },+ onError({ error }) {+ toast.error(error.serverError?.serverError);+ },+ });++ return (+ <div className="flex flex-col gap-3">+ <form+ onSubmit={(e) => {+ e.preventDefault();+ executeAsync({ email });+ }}+ >+ <div className="flex flex-col gap-8">+ <label>+ <span className="text-sm font-medium text-gray-700">Email</span>+ <Input+ type="email"+ autoFocus={!isMobile}+ value={email}+ placeholder="[email protected]"+ onChange={(e) => setEmail(e.target.value)}+ className="mt-1"+ />+ </label>+ <Button+ type="submit"+ text={isExecuting ? "Sending..." : "Send reset link"}+ loading={isExecuting}+ disabled={email.length < 3}+ />+ </div>+ </form>+ </div>+ );+};diff --git a/apps/web/ui/auth/login/email-sign-in.tsx b/apps/web/ui/auth/login/email-sign-in.tsxnew file mode 100644index 0000000000..3648c4acfa--- /dev/null+++ b/apps/web/ui/auth/login/email-sign-in.tsx@@ -0,0 +1,182 @@+import { emailSchema } from "@/lib/zod/schemas/auth";+import { Button, Input, useMediaQuery } from "@dub/ui";+import { InputPassword } from "@dub/ui/src/icons";+import { cn } from "@dub/utils";+import { Mail } from "lucide-react";+import { signIn } from "next-auth/react";+import Link from "next/link";+import { useRouter, useSearchParams } from "next/navigation";+import { useContext, useState } from "react";+import { toast } from "sonner";+import { errorCodes, LoginFormContext } from "./login-form";++export const EmailSignIn = () => {+ const router = useRouter();+ const searchParams = useSearchParams();+ const next = searchParams?.get("next");+ const { isMobile } = useMediaQuery();++ const [email, setEmail] = useState("");+ const [password, setPassword] = useState("");+ const [checkingEmailPassword, setCheckingEmailPassword] = useState(false);++ const {+ showPasswordField,+ setShowPasswordField,+ setClickedMethod,+ authMethod,+ setAuthMethod,+ clickedMethod,+ setLastUsedAuthMethod,+ setShowSSOOption,+ } = useContext(LoginFormContext);++ return (+ <>+ <form+ onSubmit={async (e) => {+ e.preventDefault();++ // Check if the user can enter a password, and if so display the field+ if (!showPasswordField) {+ const { success } = emailSchema.safeParse(email);++ if (success) {+ try {+ setCheckingEmailPassword(true);+ const res = await fetch("/api/auth/account-exists", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ email }),+ });+ setCheckingEmailPassword(false);++ const { accountExists, hasPassword } = await res.json();+ if (accountExists && hasPassword) {+ setShowPasswordField(true);+ return;+ }+ } catch (e) {+ console.error("Failed to determine if user has password", e);+ }+ }+ }++ setClickedMethod("email");++ fetch("/api/auth/account-exists", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ email }),+ }).then(async (res) => {+ if (!res.ok) {+ const error = await res.text();+ toast.error(error);+ setClickedMethod(undefined);+ return;+ }++ const { accountExists, hasPassword } = await res.json();+ if (accountExists) {+ const provider =+ hasPassword && password ? "credentials" : "email";++ signIn(provider, {+ email,+ redirect: false,+ ...(password && { password }),+ ...(next ? { callbackUrl: next } : {}),+ }).then((res) => {+ if (!res) return;++ // Handle errors+ if (!res.ok && res.error) {+ if (errorCodes[res.error]) toast.error(errorCodes[res.error]);+ else toast.error(res.error);++ setClickedMethod(undefined);+ return;+ }++ // Handle success+ setLastUsedAuthMethod("email");+ if (provider === "email") {+ toast.success("Email sent - check your inbox!");+ setEmail("");+ setClickedMethod(undefined);+ } else if (provider === "credentials") router.push(next ?? "/");+ });+ } else {+ setClickedMethod(undefined);+ toast.error("No account found with that email address.");+ }+ });+ }}+ className="flex flex-col gap-y-3"+ >+ {authMethod === "email" && (+ <input+ id="email"+ name="email"+ autoFocus={!isMobile && !showPasswordField}+ type="email"+ placeholder="[email protected]"+ autoComplete="email"+ required+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ size={1}+ className={cn(+ "block w-full min-w-0 appearance-none rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-black focus:outline-none focus:ring-black sm:text-sm",+ {+ "pr-10": checkingEmailPassword,+ },+ )}+ />+ )}++ {showPasswordField && (+ <div>+ <Input+ type="password"+ autoFocus={!isMobile}+ value={password}+ placeholder="Password (optional)"+ onChange={(e) => setPassword(e.target.value)}+ />+ </div>+ )}++ <Button+ text={`Continue with ${password ? "Password" : "Email"}`}+ variant="secondary"+ icon={+ password ? (+ <InputPassword className="size-4 text-gray-600" />+ ) : (+ <Mail className="size-4 text-gray-600" />+ )+ }+ {...(authMethod !== "email" && {+ type: "button",+ onClick: (e) => {+ e.preventDefault();+ setShowSSOOption(false);+ setAuthMethod("email");+ },+ })}+ loading={checkingEmailPassword || clickedMethod === "email"}+ disabled={clickedMethod && clickedMethod !== "email"}+ />+ </form>+ {showPasswordField && (+ <Link+ href={`/forgot-password?email=${encodeURIComponent(email)}`}+ className="text-center text-xs text-gray-500 transition-colors hover:text-black"+ >+ Forgot password?+ </Link>+ )}+ </>+ );+};diff --git a/apps/web/ui/auth/login/github-button.tsx b/apps/web/ui/auth/login/github-button.tsxnew file mode 100644index 0000000000..2d1186e5cd--- /dev/null+++ b/apps/web/ui/auth/login/github-button.tsx@@ -0,0 +1,30 @@+import { Button, Github } from "@dub/ui";+import { signIn } from "next-auth/react";+import { useSearchParams } from "next/navigation";+import { useContext } from "react";+import { LoginFormContext } from "./login-form";++export const GitHubButton = () => {+ const searchParams = useSearchParams();+ const next = searchParams?.get("next");++ const { setClickedMethod, clickedMethod, setLastUsedAuthMethod } =+ useContext(LoginFormContext);++ return (+ <Button+ text="Continue with Github"+ variant="secondary"+ onClick={() => {+ setClickedMethod("github");+ setLastUsedAuthMethod("github");+ signIn("github", {+ ...(next && next.length > 0 ? { callbackUrl: next } : {}),+ });+ }}+ loading={clickedMethod === "github"}+ disabled={clickedMethod && clickedMethod !== "github"}+ icon={<Github className="size-4 text-black" />}+ />+ );+};diff --git a/apps/web/ui/auth/login/google-button.tsx b/apps/web/ui/auth/login/google-button.tsxnew file mode 100644index 0000000000..cedd04caa9--- /dev/null+++ b/apps/web/ui/auth/login/google-button.tsx@@ -0,0 +1,31 @@+import { Button } from "@dub/ui";+import { Google } from "@dub/ui/src/icons";+import { signIn } from "next-auth/react";+import { useSearchParams } from "next/navigation";+import { useContext } from "react";+import { LoginFormContext } from "./login-form";++export function GoogleButton() {+ const searchParams = useSearchParams();+ const next = searchParams?.get("next");++ const { setClickedMethod, clickedMethod, setLastUsedAuthMethod } =+ useContext(LoginFormContext);++ return (+ <Button+ text="Continue with Google"+ variant="secondary"+ onClick={() => {+ setClickedMethod("google");+ setLastUsedAuthMethod("google");+ signIn("google", {+ ...(next && next.length > 0 ? { callbackUrl: next } : {}),+ });+ }}+ loading={clickedMethod === "google"}+ disabled={clickedMethod && clickedMethod !== "google"}+ icon={<Google className="size-4" />}+ />+ );+}diff --git a/apps/web/ui/auth/login/login-form.tsx b/apps/web/ui/auth/login/login-form.tsxnew file mode 100644index 0000000000..aa665732bc--- /dev/null+++ b/apps/web/ui/auth/login/login-form.tsx@@ -0,0 +1,198 @@+"use client";++import { AnimatedSizeContainer, useLocalStorage } from "@dub/ui";+import { useSearchParams } from "next/navigation";+import {+ ComponentType,+ Dispatch,+ SetStateAction,+ createContext,+ useEffect,+ useRef,+ useState,+} from "react";+import { toast } from "sonner";+import { EmailSignIn } from "./email-sign-in";+import { GitHubButton } from "./github-button";+import { GoogleButton } from "./google-button";+import { SSOSignIn } from "./sso-sign-in";++export const authMethods = [+ "google",+ "github",+ "email",+ "saml",+ "password",+] as const;++export type AuthMethod = (typeof authMethods)[number];++export const errorCodes = {+ "no-credentials": "Please provide an email and password.",+ "invalid-credentials": "Email or password is incorrect.",+ "exceeded-login-attempts":+ "Account has been locked due to too many login attempts. Please contact support to unlock your account.",+ "too-many-login-attempts": "Too many login attempts. Please try again later.",+ "email-not-verified": "Please verify your email address.",+ Callback:+ "We encountered an issue processing your request. Please try again or contact support if the problem persists.",+ OAuthSignin:+ "There was an issue signing you in. Please ensure your provider settings are correct.",+ OAuthCallback:+ "We faced a problem while processing the response from the OAuth provider. Please try again.",+};++export const LoginFormContext = createContext<{+ authMethod: AuthMethod | undefined;+ setAuthMethod: Dispatch<SetStateAction<AuthMethod | undefined>>;+ clickedMethod: AuthMethod | undefined;+ showPasswordField: boolean;+ showSSOOption: boolean;+ setShowPasswordField: Dispatch<SetStateAction<boolean>>;+ setClickedMethod: Dispatch<SetStateAction<AuthMethod | undefined>>;+ setLastUsedAuthMethod: Dispatch<SetStateAction<AuthMethod | undefined>>;+ setShowSSOOption: Dispatch<SetStateAction<boolean>>;+}>({+ authMethod: undefined,+ setAuthMethod: () => {},+ clickedMethod: undefined,+ showPasswordField: false,+ showSSOOption: false,+ setShowPasswordField: () => {},+ setClickedMethod: () => {},+ setLastUsedAuthMethod: () => {},+ setShowSSOOption: () => {},+});++export default function LoginForm({+ methods = [...authMethods],+}: {+ methods?: AuthMethod[];+}) {+ const searchParams = useSearchParams();+ const [showPasswordField, setShowPasswordField] = useState(false);+ const [showSSOOption, setShowSSOOption] = useState(false);+ const [clickedMethod, setClickedMethod] = useState<AuthMethod | undefined>(+ undefined,+ );++ const [lastUsedAuthMethodLive, setLastUsedAuthMethod] = useLocalStorage<+ AuthMethod | undefined+ >("last-used-auth-method", undefined);+ const { current: lastUsedAuthMethod } = useRef<AuthMethod | undefined>(+ lastUsedAuthMethodLive,+ );++ const [authMethod, setAuthMethod] = useState<AuthMethod | undefined>(+ authMethods.find((m) => m === lastUsedAuthMethodLive) ?? "email",+ );++ useEffect(() => {+ const error = searchParams?.get("error");+ if (error) {+ toast.error(+ errorCodes[error] ||+ "An unexpected error occurred. Please try again later.",+ );+ }+ }, [searchParams]);++ // Reset the state when leaving the page+ useEffect(() => () => setClickedMethod(undefined), []);++ const authProviders: { method: AuthMethod; component: ComponentType }[] = [+ {+ method: "google",+ component: GoogleButton,+ },+ {+ method: "github",+ component: GitHubButton,+ },+ {+ method: "email",+ component: EmailSignIn,+ },+ {+ method: "saml",+ component: SSOSignIn,+ },+ ];++ const AuthMethodComponent = authProviders.find(+ (provider) => provider.method === authMethod,+ )?.component;++ const showEmailPasswordOnly = authMethod === "email" && showPasswordField;++ return (+ <LoginFormContext.Provider+ value={{+ authMethod,+ setAuthMethod,+ clickedMethod,+ showPasswordField,+ showSSOOption,+ setShowPasswordField,+ setClickedMethod,+ setLastUsedAuthMethod,+ setShowSSOOption,+ }}+ >+ <div className="flex flex-col gap-3">+ <AnimatedSizeContainer height>+ <div className="flex flex-col gap-3 p-1">+ {authMethod && (+ <div className="flex flex-col gap-2">+ {AuthMethodComponent && <AuthMethodComponent />}++ {!showEmailPasswordOnly &&+ authMethod === lastUsedAuthMethod && (+ <div className="text-center text-xs">+ <span className="text-gray-500">+ You signed in with{" "}+ {lastUsedAuthMethod.charAt(0).toUpperCase() ++ lastUsedAuthMethod.slice(1)}{" "}+ last time+ </span>+ </div>+ )}+ <div className="my-2 flex flex-shrink items-center justify-center gap-2">+ <div className="grow basis-0 border-b border-gray-300" />+ <span className="text-xs font-normal uppercase leading-none text-gray-500">+ or+ </span>+ <div className="grow basis-0 border-b border-gray-300" />+ </div>+ </div>+ )}++ {showEmailPasswordOnly ? (+ <div className="mt-2 text-center text-sm text-gray-500">+ <button+ type="button"+ onClick={() => setShowPasswordField(false)}+ className="font-semibold text-gray-500 transition-colors hover:text-black"+ >+ Continue with another method+ </button>+ </div>+ ) : (+ authProviders+ .filter(+ (provider) =>+ provider.method !== authMethod &&+ methods.includes(provider.method),+ )+ .map((provider) => (+ <div key={provider.method}>+ <provider.component />+ </div>+ ))+ )}+ </div>+ </AnimatedSizeContainer>+ </div>+ </LoginFormContext.Provider>+ );+}diff --git a/apps/web/ui/auth/login/sso-sign-in.tsx b/apps/web/ui/auth/login/sso-sign-in.tsxnew file mode 100644index 0000000000..e483a17942--- /dev/null+++ b/apps/web/ui/auth/login/sso-sign-in.tsx@@ -0,0 +1,85 @@+"use client";++import { Button, InfoTooltip, useMediaQuery } from "@dub/ui";+import { Lock } from "lucide-react";+import { signIn } from "next-auth/react";+import { useContext } from "react";+import { toast } from "sonner";+import { LoginFormContext } from "./login-form";++export const SSOSignIn = () => {+ const { isMobile } = useMediaQuery();++ const {+ setClickedMethod,+ clickedMethod,+ setLastUsedAuthMethod,+ setShowSSOOption,+ showSSOOption,+ } = useContext(LoginFormContext);++ return (+ <form+ onSubmit={async (e) => {+ e.preventDefault();+ setClickedMethod("saml");+ fetch("/api/auth/saml/verify", {+ method: "POST",+ body: JSON.stringify({ slug: e.currentTarget.slug.value }),+ }).then(async (res) => {+ const { data, error } = await res.json();+ if (error) {+ toast.error(error);+ setClickedMethod(undefined);+ return;+ }+ setLastUsedAuthMethod("saml");+ await signIn("saml", undefined, {+ tenant: data.workspaceId,+ product: "Dub",+ });+ });+ }}+ className="flex flex-col space-y-3"+ >+ {showSSOOption && (+ <div>+ <div className="mb-4 mt-1 border-t border-gray-300" />+ <div className="flex items-center space-x-2">+ <h2 className="text-sm font-medium text-gray-900">+ Workspace Slug+ </h2>+ <InfoTooltip+ content={`This is your workspace's unique identifier on ${process.env.NEXT_PUBLIC_APP_NAME}. E.g. app.dub.co/acme is "acme".`}+ />+ </div>+ <input+ id="slug"+ name="slug"+ autoFocus={!isMobile}+ type="text"+ placeholder="my-team"+ autoComplete="off"+ required+ className="mt-1 block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-black focus:outline-none focus:ring-black sm:text-sm"+ />+ </div>+ )}++ <Button+ text="Continue with SAML SSO"+ variant="secondary"+ icon={<Lock className="size-4" />}+ {...(!showSSOOption && {+ type: "button",+ onClick: (e) => {+ e.preventDefault();+ setShowSSOOption(true);+ },+ })}+ loading={clickedMethod === "saml"}+ disabled={clickedMethod && clickedMethod !== "saml"}+ />+ </form>+ );+};diff --git a/apps/web/app/app.dub.co/(auth)/register/context.tsx b/apps/web/ui/auth/register/context.tsxsimilarity index 100%rename from apps/web/app/app.dub.co/(auth)/register/context.tsxrename to apps/web/ui/auth/register/context.tsxdiff --git a/apps/web/app/app.dub.co/(auth)/register/resend-otp.tsx b/apps/web/ui/auth/register/resend-otp.tsxsimilarity index 100%rename from apps/web/app/app.dub.co/(auth)/register/resend-otp.tsxrename to apps/web/ui/auth/register/resend-otp.tsxdiff --git a/apps/web/app/app.dub.co/(auth)/register/signup-email.tsx b/apps/web/ui/auth/register/signup-email.tsxsimilarity index 100%rename from apps/web/app/app.dub.co/(auth)/register/signup-email.tsxrename to apps/web/ui/auth/register/signup-email.tsxdiff --git a/apps/web/ui/auth/register/signup-form.tsx b/apps/web/ui/auth/register/signup-form.tsxnew file mode 100644index 0000000000..2c88160a1f--- /dev/null+++ b/apps/web/ui/auth/register/signup-form.tsx@@ -0,0 +1,26 @@+"use client";++import { SignUpEmail } from "./signup-email";+import { SignUpOAuth } from "./signup-oauth";++export const SignUpForm = ({+ methods = ["email", "google", "github"],+}: {+ methods?: ("email" | "google" | "github")[];+}) => {+ return (+ <div className="flex flex-col gap-3">+ {methods.includes("email") && <SignUpEmail />}+ {methods.length && (+ <div className="my-2 flex flex-shrink items-center justify-center gap-2">+ <div className="grow basis-0 border-b border-gray-300" />+ <span className="text-xs font-normal uppercase leading-none text-gray-500">+ or+ </span>+ <div className="grow basis-0 border-b border-gray-300" />+ </div>+ )}+ <SignUpOAuth methods={methods} />+ </div>+ );+};diff --git a/apps/web/ui/auth/register/signup-oauth.tsx b/apps/web/ui/auth/register/signup-oauth.tsxnew file mode 100644index 0000000000..727c3b5f6a--- /dev/null+++ b/apps/web/ui/auth/register/signup-oauth.tsx@@ -0,0 +1,58 @@+"use client";++import { Button, Github, Google } from "@dub/ui";+import { signIn } from "next-auth/react";+import { useSearchParams } from "next/navigation";+import { useEffect, useState } from "react";++export const SignUpOAuth = ({+ methods,+}: {+ methods: ("email" | "google" | "github")[];+}) => {+ const searchParams = useSearchParams();+ const next = searchParams?.get("next");+ const [clickedGoogle, setClickedGoogle] = useState(false);+ const [clickedGithub, setClickedGithub] = useState(false);++ useEffect(() => {+ // when leave page, reset state+ return () => {+ setClickedGoogle(false);+ setClickedGithub(false);+ };+ }, []);++ return (+ <>+ {methods.includes("google") && (+ <Button+ variant="secondary"+ text="Continue with Google"+ onClick={() => {+ setClickedGoogle(true);+ signIn("google", {+ ...(next && next.length > 0 ? { callbackUrl: next } : {}),+ });+ }}+ loading={clickedGoogle}+ icon={<Google className="h-4 w-4" />}+ />+ )}+ {methods.includes("github") && (+ <Button+ variant="secondary"+ text="Continue with GitHub"+ onClick={() => {+ setClickedGithub(true);+ signIn("github", {+ ...(next && next.length > 0 ? { callbackUrl: next } : {}),+ });+ }}+ loading={clickedGithub}+ icon={<Github className="h-4 w-4" />}+ />+ )}+ </>+ );+};diff --git a/apps/web/ui/auth/register/verify-email-form.tsx b/apps/web/ui/auth/register/verify-email-form.tsxnew file mode 100644index 0000000000..d715194bb8--- /dev/null+++ b/apps/web/ui/auth/register/verify-email-form.tsx@@ -0,0 +1,119 @@+"use client";++import { createUserAccountAction } from "@/lib/actions/create-user-account";+import { AnimatedSizeContainer, Button, useMediaQuery } from "@dub/ui";+import { cn } from "@dub/utils";+import { OTPInput } from "input-otp";+import { signIn } from "next-auth/react";+import { useAction } from "next-safe-action/hooks";+import { useRouter } from "next/navigation";+import { useState } from "react";+import { toast } from "sonner";+import { useRegisterContext } from "./context";+import { ResendOtp } from "./resend-otp";++export const VerifyEmailForm = () => {+ const router = useRouter();+ const { isMobile } = useMediaQuery();+ const [code, setCode] = useState("");+ const { email, password } = useRegisterContext();+ const [isInvalidCode, setIsInvalidCode] = useState(false);+ const [isRedirecting, setIsRedirecting] = useState(false);++ const { executeAsync, isExecuting } = useAction(createUserAccountAction, {+ async onSuccess() {+ toast.success("Account created! Redirecting to dashboard...");+ setIsRedirecting(true);++ const response = await signIn("credentials", {+ email,+ password,+ redirect: false,+ });++ if (response?.ok) {+ router.push("/onboarding");+ } else {+ toast.error("Failed to redirect to dashboard.");+ }+ },+ onError({ error }) {+ toast.error(error.serverError?.serverError);+ setCode("");+ setIsInvalidCode(true);+ },+ });++ if (!email || !password) {+ router.push("/register");+ return;+ }++ return (+ <div className="flex flex-col gap-3">+ <AnimatedSizeContainer height>+ <form+ onSubmit={(e) => {+ e.preventDefault();+ executeAsync({ email, password, code });+ }}+ >+ <div>+ <OTPInput+ maxLength={6}+ value={code}+ onChange={(code) => {+ setIsInvalidCode(false);+ setCode(code);+ }}+ 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-2 ring-gray-200",+ isInvalidCode && "border-red-500 ring-red-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>+ )}+ onComplete={() => {+ executeAsync({ email, password, code });+ }}+ />+ {isInvalidCode && (+ <p className="mt-2 text-center text-sm text-red-500">+ Invalid code. Please try again.+ </p>+ )}++ <Button+ className="mt-8"+ text={isExecuting ? "Verifying..." : "Continue"}+ type="submit"+ loading={isExecuting || isRedirecting}+ disabled={!code || code.length < 6}+ />+ </div>+ </form>++ <ResendOtp email={email} />+ </AnimatedSizeContainer>+ </div>+ );+};diff --git a/apps/web/app/app.dub.co/(auth)/auth/reset-password/[token]/form.tsx b/apps/web/ui/auth/reset-password-form.tsxsimilarity index 97%rename from apps/web/app/app.dub.co/(auth)/auth/reset-password/[token]/form.tsxrename to apps/web/ui/auth/reset-password-form.tsxindex 71ab0a3bf7..ad9de2a756 100644--- a/apps/web/app/app.dub.co/(auth)/auth/reset-password/[token]/form.tsx+++ b/apps/web/ui/auth/reset-password-form.tsx@@ -46,7 +46,7 @@ export const ResetPasswordForm = () => {return (<>- <form className="flex flex-col space-y-5" onSubmit={onSubmit}>+ <form className="flex flex-col gap-5" onSubmit={onSubmit}><input type="hidden" value={token} {...register("token")} /><div className="grid w-full max-w-sm items-center gap-2">