Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

reveal an additional password field under email

Kiran Ke18a25091785
diff --git a/apps/web/app/app.dub.co/(auth)/login/form.tsx b/apps/web/app/app.dub.co/(auth)/login/form.tsx
index 6772148e76..adccb88b17 100644
--- a/apps/web/app/app.dub.co/(auth)/login/form.tsx
+++ b/apps/web/app/app.dub.co/(auth)/login/form.tsx
@@ -6,6 +6,7 @@ import {
LastUsedAuthMethodTooltip,
setLastUsedAuthMethod,
} from "@/lib/auth/last-used-method";
+import { emailSchema } from "@/lib/zod/schemas/auth";
import {
Button,
Github,
@@ -17,13 +18,22 @@ import {
import { Lock, Mail } from "lucide-react";
import { signIn } from "next-auth/react";
import Link from "next/link";
-import { useSearchParams } from "next/navigation";
+import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
+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.",
+};
+
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);
@@ -34,6 +44,7 @@ export default function LoginForm() {
const [clickedGithub, setClickedGithub] = useState(false);
const [clickedEmail, setClickedEmail] = useState(false);
const [clickedSSO, setClickedSSO] = useState(false);
+ const [loading, setLoading] = useState(false);
const [authMethod, setAuthMethod] = useState<AuthMethod | undefined>(
undefined,
@@ -105,25 +116,51 @@ export default function LoginForm() {
e.preventDefault();
setClickedEmail(true);
setLastUsedAuthMethod("email");
+
+ if (!password) {
+ setShowPasswordField(false);
+ }
+
fetch("/api/auth/account-exists", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email }),
})
.then(async (res) => {
- const { exists } = await res.json();
- if (exists) {
- signIn("email", {
+ const { accountExists, hasPassword } = await res.json();
+ if (accountExists) {
+ const provider =
+ hasPassword && password ? "credentials" : "email";
+
+ signIn(provider, {
email,
+ ...(password && { password }),
redirect: false,
...(next && next.length > 0 ? { callbackUrl: next } : {}),
}).then((res) => {
setClickedEmail(false);
- if (res?.ok && !res?.error) {
+
+ if (!res) {
+ return;
+ }
+
+ // Handle errors
+ if (!res.ok && res.error) {
+ if (provider === "email") {
+ toast.error("Error sending email - try again?");
+ } else if (provider === "credentials") {
+ toast.error(errorCodes[res?.error]);
+ }
+
+ return;
+ }
+
+ // Handle success
+ if (provider === "email") {
setEmail("");
toast.success("Email sent - check your inbox!");
- } else {
- toast.error("Error sending email - try again?");
+ } else if (provider === "credentials") {
+ router.replace(res.url ?? "/");
}
});
} else {
@@ -154,6 +191,23 @@ export default function LoginForm() {
onChange={(e) => {
setNoSuchAccount(false);
setEmail(e.target.value);
+
+ const { success } = emailSchema.safeParse(e.target.value);
+
+ if (success) {
+ setLoading(true);
+ fetch("/api/auth/account-exists", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ email: e.target.value }),
+ }).then(async (res) => {
+ setLoading(false);
+ const { accountExists, hasPassword } = await res.json();
+ if (accountExists && hasPassword) {
+ setShowPasswordField(true);
+ }
+ });
+ }
}}
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"
/>
@@ -162,7 +216,12 @@ export default function LoginForm() {
{showPasswordField && (
<div>
- <Input type="password" placeholder="Password" value={password} />
+ <Input
+ type="password"
+ value={password}
+ placeholder="Password (optional)"
+ onChange={(e) => setPassword(e.target.value)}
+ />
</div>
)}
@@ -180,7 +239,7 @@ export default function LoginForm() {
setShowEmailOption(true);
},
})}
- loading={clickedEmail}
+ loading={clickedEmail || loading}
disabled={clickedGoogle || clickedSSO}
/>
{authMethod === "email" && <LastUsedAuthMethodTooltip />}
diff --git a/apps/web/app/app.dub.co/(auth)/login/signin-email-password.tsx b/apps/web/app/app.dub.co/(auth)/login/signin-email-password.tsx
deleted file mode 100644
index ecd543e8b9..0000000000
--- a/apps/web/app/app.dub.co/(auth)/login/signin-email-password.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-"use client";
-
-import {
- AuthMethod,
- getLastUsedAuthMethod,
- LastUsedAuthMethodTooltip,
- setLastUsedAuthMethod,
-} from "@/lib/auth/last-used-method";
-import z from "@/lib/zod";
-import { signInSchema } from "@/lib/zod/schemas/auth";
-import { Button, Input } from "@dub/ui";
-import { signIn } from "next-auth/react";
-import { useRouter, useSearchParams } from "next/navigation";
-import { useEffect, useState } from "react";
-import { useForm } from "react-hook-form";
-
-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.",
-};
-
-export const SignInWithEmailPassword = () => {
- const router = useRouter();
- const searchParams = useSearchParams();
- const [error, setError] = useState<string | null>(null);
-
- const [authMethod, setAuthMethod] = useState<AuthMethod | undefined>(
- undefined,
- );
-
- useEffect(() => {
- setAuthMethod(getLastUsedAuthMethod());
- }, []);
-
- const {
- register,
- resetField,
- handleSubmit,
- formState: { isSubmitting, disabled },
- } = useForm<z.infer<typeof signInSchema>>();
-
- const onSubmit = handleSubmit(async (data) => {
- try {
- const response = await signIn("credentials", {
- ...data,
- redirect: false,
- callbackUrl: searchParams.get("next") || "/",
- });
-
- if (!response) {
- return;
- }
-
- if (!response.ok && response.error) {
- resetField("password");
- throw new Error(errorCodes[response.error]);
- }
-
- if (response.url) {
- setLastUsedAuthMethod("password");
- router.replace(response.url);
- return;
- }
- } catch (error) {
- setError(error.message);
- }
- });
-
- return (
- <>
- {error && (
- <div className="mb-4 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">
- {errorCodes[error] || error}
- </h3>
- </div>
- </div>
- </div>
- </div>
- )}
-
- <form onSubmit={onSubmit}>
- <div className="flex flex-col space-y-4">
- <Input
- type="email"
- placeholder="Email address"
- autoComplete="email"
- required
- {...register("email")}
- />
- <Input
- type="password"
- placeholder="Password"
- required
- {...register("password")}
- />
-
- <div className="relative">
- <Button
- text="Sign in"
- type="submit"
- loading={isSubmitting}
- disabled={disabled}
- />
- {authMethod === "password" && <LastUsedAuthMethodTooltip />}
- </div>
- </div>
- </form>
- </>
- );
-};
diff --git a/apps/web/lib/zod/schemas/auth.ts b/apps/web/lib/zod/schemas/auth.ts
index 989e4e5673..c993049684 100644
--- a/apps/web/lib/zod/schemas/auth.ts
+++ b/apps/web/lib/zod/schemas/auth.ts
@@ -8,6 +8,8 @@ export const passwordSchema = z
"Password must contain at least one number, one uppercase, and one lowercase letter",
);
+export const emailSchema = z.string().email().min(1);
+
export const resetPasswordSchema = z
.object({
token: z.string().min(1),
@@ -30,6 +32,6 @@ export const updatePasswordSchema = z
});
export const signInSchema = z.object({
- email: z.string().email().min(1),
+ email: emailSchema,
password: z.string().min(1),
});