The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Refactor login form and update a bunch of logic/styles
Tim Wilson1fe24dc5eea1
diff --git a/apps/web/app/api/user/set-password/route.ts b/apps/web/app/api/user/set-password/route.tsindex df75591280..a3d5744056 100644--- a/apps/web/app/api/user/set-password/route.ts+++ b/apps/web/app/api/user/set-password/route.ts@@ -46,5 +46,12 @@ export const POST = withSession(async ({ session }) => {}),});+ if (process.env.NODE_ENV === "development") {+ console.info(+ "Password reset URL:",+ `${process.env.NEXTAUTH_URL}/auth/reset-password/${token}`,+ );+ }+return NextResponse.json({ ok: true });});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 262197e703..14747b3495 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@@ -15,26 +15,28 @@ export default async function ResetPasswordPage({ params: { token } }: Props) {const validToken = await isValidToken(token);return (- <div className="relative z-10 mt-[calc(30vh)] h-fit 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">Reset your password</h3>- <p className="text-sm text-gray-500">- {validToken- ? "Enter new password for your account."- : "The request is invalid or expired."}- </p>- </div>- <div className="flex flex-col space-y-3 bg-gray-50 px-4 py-8 sm:px-16">- {validToken ? (- <ResetPasswordForm />- ) : (- <div className="text-center">- That request is expired or invalid. Please request a new one.- </div>- )}+ <div className="relative z-10 my-10 flex min-h-full w-full items-center justify-center">+ <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">Reset your password</h3>+ <p className="text-sm text-gray-500">+ {validToken+ ? "Enter new password for your account."+ : "The request is invalid or expired."}+ </p>+ </div>+ <div className="flex flex-col space-y-3 bg-gray-50 px-4 py-8 sm:px-16">+ {validToken ? (+ <ResetPasswordForm />+ ) : (+ <div className="text-center">+ That request is expired or invalid. Please request a new one.+ </div>+ )}+ </div></div></div>);diff --git a/apps/web/app/app.dub.co/(auth)/layout.tsx b/apps/web/app/app.dub.co/(auth)/layout.tsxindex d925165339..cb0aa97519 100644--- a/apps/web/app/app.dub.co/(auth)/layout.tsx+++ b/apps/web/app/app.dub.co/(auth)/layout.tsx@@ -10,7 +10,7 @@ export default function AuthLayout({ children }: { children: ReactNode }) {<Providers><HelpPortal /><Background />- <div className="relative z-10 flex h-screen w-screen justify-center">+ <div className="relative z-10 flex min-h-screen w-screen justify-center">{children}</div></Providers>diff --git a/apps/web/app/app.dub.co/(auth)/login/form.tsx b/apps/web/app/app.dub.co/(auth)/login/form.tsxindex 4018a3f1aa..2239a386f8 100644--- a/apps/web/app/app.dub.co/(auth)/login/form.tsx+++ b/apps/web/app/app.dub.co/(auth)/login/form.tsx@@ -1,11 +1,5 @@"use client";-import {- AuthMethod,- getLastUsedAuthMethod,- LastUsedAuthMethodTooltip,- setLastUsedAuthMethod,-} from "@/lib/auth/last-used-method";import { emailSchema } from "@/lib/zod/schemas/auth";import {Button,@@ -13,6 +7,7 @@ import {Google,InfoTooltip,Input,+ useLocalStorage,useMediaQuery,} from "@dub/ui";import { InputPassword, LoadingSpinner } from "@dub/ui/src/icons";@@ -21,9 +16,18 @@ import { Lock, Mail } from "lucide-react";import { signIn } from "next-auth/react";import Link from "next/link";import { useRouter, useSearchParams } from "next/navigation";-import { useEffect, useState } from "react";+import { 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.",@@ -36,24 +40,25 @@ export default function LoginForm() {const searchParams = useSearchParams();const next = searchParams?.get("next");const router = useRouter();- const [showEmailOption, setShowEmailOption] = useState(false);const [showPasswordField, setShowPasswordField] = useState(false);const [showSSOOption, setShowSSOOption] = useState(false);const [noSuchAccount, setNoSuchAccount] = useState(false);const [email, setEmail] = useState("");const [password, setPassword] = useState("");- const [clickedGoogle, setClickedGoogle] = useState(false);- const [clickedGithub, setClickedGithub] = useState(false);- const [clickedEmail, setClickedEmail] = useState(false);- const [clickedSSO, setClickedSSO] = useState(false);- const [checkingEmailPassword, setCheckingEmailPassword] = useState(false);- const [authMethod, setAuthMethod] = useState<AuthMethod | undefined>(+ const [clickedMethod, setClickedMethod] = useState<AuthMethod | undefined>(undefined,);+ const [checkingEmailPassword, setCheckingEmailPassword] = useState(false);+ const [lastUsedAuthMethodLive, setLastUsedAuthMethod] = useLocalStorage<+ AuthMethod | undefined+ >("last-used-auth-method", undefined);+ const { current: lastUsedAuthMethod } = useRef<AuthMethod | undefined>(+ lastUsedAuthMethodLive,+ );- useEffect(() => {- setAuthMethod(getLastUsedAuthMethod());- }, []);+ const [authMethod, setAuthMethod] = useState<AuthMethod | undefined>(+ authMethods.find((m) => m === lastUsedAuthMethodLive) ?? "email",+ );useEffect(() => {const error = searchParams?.get("error");@@ -64,12 +69,7 @@ export default function LoginForm() {useEffect(() => {// when leave page, reset state- return () => {- setClickedGoogle(false);- setClickedGithub(false);- setClickedEmail(false);- setClickedSSO(false);- };+ return () => setClickedMethod(undefined);}, []);const GoogleButton = () => {@@ -78,14 +78,14 @@ export default function LoginForm() {text="Continue with Google"variant="secondary"onClick={() => {- setClickedGoogle(true);+ setClickedMethod("google");setLastUsedAuthMethod("google");signIn("google", {...(next && next.length > 0 ? { callbackUrl: next } : {}),});}}- loading={clickedGoogle}- disabled={clickedEmail || clickedSSO}+ loading={clickedMethod === "google"}+ disabled={clickedMethod && clickedMethod !== "google"}icon={<Google className="h-5 w-5" />}/>);@@ -97,14 +97,14 @@ export default function LoginForm() {text="Continue with Github"variant="secondary"onClick={() => {- setClickedGithub(true);+ setClickedMethod("github");setLastUsedAuthMethod("github");signIn("github", {...(next && next.length > 0 ? { callbackUrl: next } : {}),});}}- loading={clickedGithub}- disabled={clickedEmail || clickedSSO}+ loading={clickedMethod === "github"}+ disabled={clickedMethod && clickedMethod !== "github"}icon={<Github className="h-5 w-5 text-black" />}/>);@@ -115,8 +115,7 @@ export default function LoginForm() {<formonSubmit={async (e) => {e.preventDefault();- setClickedEmail(true);- setLastUsedAuthMethod("email");+ setClickedMethod("email");if (!password) {setShowPasswordField(false);@@ -139,7 +138,7 @@ export default function LoginForm() {redirect: false,...(next && next.length > 0 ? { callbackUrl: next } : {}),}).then((res) => {- setClickedEmail(false);+ setClickedMethod(undefined);if (!res) {return;@@ -157,6 +156,7 @@ export default function LoginForm() {}// Handle success+ setLastUsedAuthMethod("email");if (provider === "email") {setEmail("");toast.success("Email sent - check your inbox!");@@ -167,17 +167,17 @@ export default function LoginForm() {} else {toast.error("No account found with that email address.");setNoSuchAccount(true);- setClickedEmail(false);+ setClickedMethod(undefined);}}).catch(() => {- setClickedEmail(false);+ setClickedMethod(undefined);toast.error("Error sending email - try again?");});}}className="flex flex-col space-y-3">- {showEmailOption && (+ {authMethod === "email" && (<div className="relative"><inputid="email"@@ -244,17 +244,16 @@ export default function LoginForm() {<Mail className="size-4" />)}- {...(!showEmailOption && {+ {...(authMethod !== "email" && {type: "button",onClick: (e) => {e.preventDefault();- setLastUsedAuthMethod("email");setShowSSOOption(false);- setShowEmailOption(true);+ setAuthMethod("email");},})}- loading={clickedEmail}- disabled={clickedGoogle || clickedSSO}+ loading={clickedMethod === "email"}+ disabled={clickedMethod && clickedMethod !== "email"}/></form>);@@ -265,8 +264,7 @@ export default function LoginForm() {<formonSubmit={async (e) => {e.preventDefault();- setClickedSSO(true);- setLastUsedAuthMethod("saml");+ setClickedMethod("saml");fetch("/api/auth/saml/verify", {method: "POST",body: JSON.stringify({ slug: e.currentTarget.slug.value }),@@ -274,9 +272,10 @@ export default function LoginForm() {const { data, error } = await res.json();if (error) {toast.error(error);- setClickedSSO(false);+ setClickedMethod(undefined);return;}+ setLastUsedAuthMethod("saml");await signIn("saml", undefined, {tenant: data.workspaceId,product: "Dub",@@ -317,12 +316,11 @@ export default function LoginForm() {type: "button",onClick: (e) => {e.preventDefault();- setShowEmailOption(false);setShowSSOOption(true);},})}- loading={clickedSSO}- disabled={clickedGoogle || clickedEmail}+ loading={clickedMethod === "saml"}+ disabled={clickedMethod && clickedMethod !== "saml"}/></form>);@@ -347,24 +345,58 @@ export default function LoginForm() {},];- if (authMethod === undefined) {- return null;- }-- const lastUsedAuthMethodComponent = authProviders.find(+ const authMethodComponent = authProviders.find((provider) => provider.method === authMethod,)?.component;+ const showEmailPasswordOnly = authMethod === "email" && showPasswordField;+return (<><div className="flex flex-col gap-3">- {lastUsedAuthMethodComponent}- <LastUsedAuthMethodTooltip />- {authProviders- .filter((provider) => provider.method !== authMethod)- .map((provider) => (- <div key={provider.method}>{provider.component}</div>- ))}+ {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 ? (+ <p className="text-center text-sm text-gray-500">+ <button+ type="button"+ onClick={() => {+ setEmail("");+ setShowPasswordField(false);+ }}+ className="font-semibold text-gray-500 transition-colors hover:text-black"+ >+ Continue with another method+ </button>+ </p>+ ) : (+ authProviders+ .filter((provider) => provider.method !== authMethod)+ .map((provider) => (+ <div key={provider.method}>{provider.component}</div>+ ))+ )}</div>{noSuchAccount ? (diff --git a/apps/web/app/app.dub.co/(auth)/login/page.tsx b/apps/web/app/app.dub.co/(auth)/login/page.tsxindex b5fe7ff17f..b7820b01a8 100644--- a/apps/web/app/app.dub.co/(auth)/login/page.tsx+++ b/apps/web/app/app.dub.co/(auth)/login/page.tsx@@ -1,4 +1,4 @@-import { Button, Logo } from "@dub/ui";+import { Button, ClientOnly, Wordmark } from "@dub/ui";import { HOME_DOMAIN, constructMetadata } from "@dub/utils";import { Suspense } from "react";import LoginForm from "./form";@@ -8,35 +8,33 @@ export const metadata = constructMetadata({});export default function LoginPage() {+ // Use ClientOnly because the login form relies on local storage for its initial renderreturn (- <div className="relative z-10 mt-[calc(30vh)] h-fit 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">- Sign in to {process.env.NEXT_PUBLIC_APP_NAME}- </h3>- <p className="text-sm text-gray-500">- Start creating short links with superpowers- </p>- </div>- <div className="flex flex-col bg-gray-50 px-4 py-8 sm:px-16">- <div className="space-y-3">- <Suspense- fallback={- <>- <Button disabled={true} variant="secondary" />- <Button disabled={true} variant="secondary" />- <Button disabled={true} variant="secondary" />- <div className="mx-auto h-5 w-3/4 rounded-lg bg-gray-100" />- </>- }- >- <LoginForm />- </Suspense>+ <ClientOnly className="relative z-10 my-10 flex min-h-full w-full flex-col items-center justify-center">+ <a href={HOME_DOMAIN}>+ <Wordmark className="h-10" />+ </a>+ <div className="mt-5 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 gap-4 border-b border-gray-200 bg-white px-4 py-6 pt-8 text-center sm:px-16">+ <h3 className="text-lg font-semibold">Sign in to your Dub account</h3>+ </div>+ <div className="flex flex-col bg-gray-50 px-4 py-8 sm:px-16">+ <div className="space-y-3">+ <Suspense+ fallback={+ <>+ <Button disabled={true} variant="secondary" />+ <Button disabled={true} variant="secondary" />+ <Button disabled={true} variant="secondary" />+ <div className="mx-auto h-5 w-3/4 rounded-lg bg-gray-100" />+ </>+ }+ >+ <LoginForm />+ </Suspense>+ </div></div></div>- </div>+ </ClientOnly>);}diff --git a/apps/web/app/app.dub.co/(dashboard)/account/settings/security/update-password.tsx b/apps/web/app/app.dub.co/(dashboard)/account/settings/security/update-password.tsxindex a64a614345..0c718b33f5 100644--- a/apps/web/app/app.dub.co/(dashboard)/account/settings/security/update-password.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/account/settings/security/update-password.tsx@@ -14,7 +14,7 @@ export const UpdatePassword = () => {register,handleSubmit,setError,- formState: { isSubmitting, disabled, errors },+ formState: { isSubmitting, isDirty, errors },reset,} = useForm<z.infer<typeof updatePasswordSchema>>({resolver: zodResolver(updatePasswordSchema),@@ -55,20 +55,13 @@ export const UpdatePassword = () => {Manage your account password on {process.env.NEXT_PUBLIC_APP_NAME}.</p></div>- <div className="flex flex-wrap justify-between gap-y-4 p-5 sm:gap-x-4 sm:gap-y-0 sm:p-10">+ <div className="flex flex-wrap justify-between gap-4 p-5 sm:p-10"><div className="grid w-full max-w-sm items-center gap-2"><Label htmlFor="currentPassword">Current Password</Label>- <Input type="password" {...register("currentPassword")} required />- </div>-- <div className="grid w-full max-w-sm items-center gap-2">- <Label htmlFor="newPassword">New Password</Label>- <Input type="password" {...register("newPassword")} required />- </div>- </div>-- <div className="flex flex-wrap justify-between">- <div className="grid w-full max-w-sm items-center gap-2">+ <Input+ type="password"+ {...register("currentPassword", { required: true })}+ /><spanclassName="block text-sm text-red-500"role="alert"@@ -79,6 +72,11 @@ export const UpdatePassword = () => {</div><div className="grid w-full max-w-sm items-center gap-2">+ <Label htmlFor="newPassword">New Password</Label>+ <Input+ type="password"+ {...register("newPassword", { required: true })}+ /><spanclassName="block text-sm text-red-500"role="alert"@@ -100,7 +98,7 @@ export const UpdatePassword = () => {<Buttontext="Update Password"loading={isSubmitting}- disabled={disabled}+ disabled={!isDirty}type="submit"/></div>diff --git a/apps/web/lib/auth/last-used-method.tsx b/apps/web/lib/auth/last-used-method.tsxdeleted file mode 100644index d945ff9bd4..0000000000--- a/apps/web/lib/auth/last-used-method.tsx+++ /dev/null@@ -1,47 +0,0 @@-import { memo, useEffect, useState } from "react";--// Store the last used auth method in localStorage-const LAST_USED_AUTH_METHOD = "lastUsedAuthMethod";--export type AuthMethod = "google" | "github" | "email" | "saml" | "password";--export const setLastUsedAuthMethod = (method: AuthMethod) => {- if (typeof window === "undefined") return;-- localStorage.setItem(LAST_USED_AUTH_METHOD, method);-};--export const getLastUsedAuthMethod = () => {- if (typeof window === "undefined") return;-- return localStorage.getItem(LAST_USED_AUTH_METHOD) as AuthMethod | undefined;-};--export const LastUsedAuthMethodTooltip = memo(() => {- const [lastUsed, setLastUsed] = useState<AuthMethod | undefined>(undefined);-- useEffect(() => {- setLastUsed(getLastUsedAuthMethod());- }, []);-- if (!lastUsed) {- return null;- }-- const lastUsedText = lastUsed.charAt(0).toUpperCase() + lastUsed.slice(1);-- return (- <div className="flex flex-col gap-3 py-2 text-center text-sm">- <span className="text-gray-500">- You signed in with {lastUsedText} last time.- </span>- <div className="relative flex items-center justify-center">- <div className="border-subtle flex-grow border-t" />- <span className="text-subtle mx-2 flex-shrink text-sm font-normal leading-none">- Or continue with- </span>- <div className="border-subtle flex-grow border-t" />- </div>- </div>- );-});diff --git a/packages/ui/src/client-only.tsx b/packages/ui/src/client-only.tsxindex 68e3f8fa5b..cd4256791b 100644--- a/packages/ui/src/client-only.tsx+++ b/packages/ui/src/client-only.tsx@@ -5,10 +5,12 @@ export const ClientOnly = ({children,fallback,fadeInDuration = 0.5,+ className,}: {children: ReactNode;fallback?: ReactNode;fadeInDuration?: number;+ className?: string;}) => {const [clientReady, setClientReady] = useState<boolean>(false);@@ -29,6 +31,7 @@ export const ClientOnly = ({transition: { duration: fadeInDuration },}: {})}+ className={className}>{children}</Comp>