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.

Add "Forgot password?" flow

Tim Wilson4ae6356ed5e9
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.tsx
index 14747b3495..32414b446f 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,6 +1,5 @@
import { prisma } from "@/lib/prisma";
-import { Logo } from "@dub/ui";
-import { HOME_DOMAIN } from "@dub/utils";
+import { Wordmark } from "@dub/ui";
import { ResetPasswordForm } from "./form";
export const runtime = "nodejs";
@@ -16,26 +15,26 @@ 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 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="flex w-full max-w-md flex-col items-center">
+ <Wordmark className="mb-8 h-12" />
+ <div className="w-full 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">
+ {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>
</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.tsx
index ec0f992982..1e8f6b1dfb 100644
--- a/apps/web/app/app.dub.co/(auth)/forgot-password/form.tsx
+++ b/apps/web/app/app.dub.co/(auth)/forgot-password/form.tsx
@@ -1,6 +1,6 @@
"use client";
-import { verifyEmailAction } from "@/lib/actions/verify-email";
+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";
@@ -15,10 +15,10 @@ export function ForgotPasswordForm() {
const [email, setEmail] = useState(searchParams.get("email") || "");
const { executeAsync, result, status, isExecuting } = useAction(
- verifyEmailAction,
+ requestPasswordResetAction,
{
onSuccess() {
- toast.success("Email verified! Redirecting to login...");
+ toast.success("Reset instructions sent! Redirecting to login...");
router.push("/login");
},
},
@@ -43,17 +43,23 @@ export function ForgotPasswordForm() {
<form
onSubmit={async (e) => {
e.preventDefault();
- //await executeAsync({ email, code });
+ await executeAsync({ email });
}}
>
<div className="flex flex-col gap-8">
- <Input
- type="email"
- autoFocus={!isMobile}
- value={email}
- placeholder="[email protected]"
- onChange={(e) => setEmail(e.target.value)}
- />
+ <label>
+ <span className="text-sm font-medium text-gray-700">
+ Email Address
+ </span>
+ <Input
+ type="email"
+ autoFocus={!isMobile}
+ value={email}
+ placeholder="[email protected]"
+ onChange={(e) => setEmail(e.target.value)}
+ className="mt-1"
+ />
+ </label>
<Button
text={status === "executing" ? "Sending..." : "Send Reset Link"}
type="submit"
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 b97de3b701..17a10ef2da 100644
--- a/apps/web/app/app.dub.co/(auth)/login/form.tsx
+++ b/apps/web/app/app.dub.co/(auth)/login/form.tsx
@@ -256,14 +256,6 @@ export default function LoginForm() {
</span>
</div>
)}
- {showPasswordField && (
- <Link
- href="/forgot-password"
- className="text-center text-xs text-gray-500 transition-colors hover:text-black"
- >
- Forgot password?
- </Link>
- )}
<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">
@@ -318,143 +310,154 @@ const SignInWithEmail = () => {
} = 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);
+ <>
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
- const { accountExists, hasPassword } = await res.json();
- if (accountExists && hasPassword) {
- setShowPasswordField(true);
- return;
+ // 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);
}
- } 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("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;
}
- 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,
+ },
+ )}
+ />
+ )}
- // 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.");
+ {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" />
+ )
}
- });
- }}
- 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,
+ {...(authMethod !== "email" && {
+ type: "button",
+ onClick: (e) => {
+ e.preventDefault();
+ setShowSSOOption(false);
+ setAuthMethod("email");
},
- )}
+ })}
+ loading={checkingEmailPassword || clickedMethod === "email"}
+ disabled={clickedMethod && clickedMethod !== "email"}
/>
- )}
-
+ </form>
{showPasswordField && (
- <div>
- <Input
- type="password"
- autoFocus={!isMobile}
- value={password}
- placeholder="Password (optional)"
- onChange={(e) => setPassword(e.target.value)}
- />
- </div>
+ <Link
+ href={`/forgot-password?email=${encodeURIComponent(email)}`}
+ className="text-center text-xs text-gray-500 transition-colors hover:text-black"
+ >
+ Forgot password?
+ </Link>
)}
-
- <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>
+ </>
);
};
diff --git a/apps/web/lib/actions/request-password-reset.ts b/apps/web/lib/actions/request-password-reset.ts
new file mode 100644
index 0000000000..b697ae775c
--- /dev/null
+++ b/apps/web/lib/actions/request-password-reset.ts
@@ -0,0 +1,61 @@
+"use server";
+
+import { prisma } from "@/lib/prisma";
+import { ratelimit } from "@/lib/upstash";
+import { randomBytes } from "crypto";
+import { sendEmail } from "emails";
+import ResetPasswordLink from "emails/reset-password-link";
+import { flattenValidationErrors } from "next-safe-action";
+import { PASSWORD_RESET_TOKEN_EXPIRY } from "../auth/constants";
+import { requestPasswordResetSchema } from "../zod/schemas/auth";
+import { throwIfAuthenticated } from "./middlewares/throw-if-authenticated";
+import { actionClient } from "./safe-action";
+
+// Request a password reset email
+export const requestPasswordResetAction = actionClient
+ .schema(requestPasswordResetSchema, {
+ handleValidationErrorsShape: (ve) =>
+ flattenValidationErrors(ve).fieldErrors,
+ })
+ .use(throwIfAuthenticated)
+ .action(async ({ parsedInput }) => {
+ const { email } = parsedInput;
+
+ const { success } = await ratelimit(2, "1 m").limit(
+ `request-password-reset:${email.toLowerCase()}`,
+ );
+
+ if (!success) {
+ throw new Error("Too many requests. Please try again later.");
+ }
+
+ // Check user with email exists
+ const user = await prisma.user.findUnique({
+ where: {
+ email,
+ },
+ });
+
+ if (!user) {
+ throw new Error("An user with this email does not exist.");
+ }
+
+ const { token } = await prisma.verificationToken.create({
+ data: {
+ identifier: email,
+ token: randomBytes(32).toString("hex"),
+ expires: new Date(Date.now() + PASSWORD_RESET_TOKEN_EXPIRY * 1000),
+ },
+ });
+
+ await sendEmail({
+ subject: `${process.env.NEXT_PUBLIC_APP_NAME}: Password reset instructions`,
+ email,
+ react: ResetPasswordLink({
+ email,
+ url: `${process.env.NEXTAUTH_URL}/auth/reset-password/${token}`,
+ }),
+ });
+
+ return { ok: true };
+ });
diff --git a/apps/web/lib/zod/schemas/auth.ts b/apps/web/lib/zod/schemas/auth.ts
index 51f31f35a7..a6d8957c0d 100644
--- a/apps/web/lib/zod/schemas/auth.ts
+++ b/apps/web/lib/zod/schemas/auth.ts
@@ -53,3 +53,7 @@ export const verifyEmailSchema = z.object({
export const resendOtpSchema = z.object({
email: emailSchema,
});
+
+export const requestPasswordResetSchema = z.object({
+ email: emailSchema,
+});