The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
chore: Add password reset functionality
Kiran K1a131f053f22
diff --git a/apps/web/app/api/auth/reset-password/route.ts b/apps/web/app/api/auth/reset-password/route.tsnew file mode 100644index 0000000000..dc090a167a--- /dev/null+++ b/apps/web/app/api/auth/reset-password/route.ts@@ -0,0 +1,73 @@+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";+import { parseRequestBody } from "@/lib/api/utils";+import { hashPassword } from "@/lib/auth/password";+import { prisma } from "@/lib/prisma";+import { resetPasswordSchema } from "@/lib/zod/schemas/password";+import { sendEmail } from "emails";+import PasswordUpdated from "emails/password-updated";+import { NextRequest, NextResponse } from "next/server";++// POST /api/auth/reset-password - reset password using the reset token+export async function POST(req: NextRequest) {+ try {+ const { token, password } = resetPasswordSchema.parse(+ await parseRequestBody(req),+ );++ // Find the token+ const tokenFound = await prisma.verificationToken.findFirst({+ where: {+ token,+ expires: {+ gte: new Date(),+ },+ },+ select: {+ identifier: true,+ },+ });++ if (!tokenFound) {+ throw new DubApiError({+ code: "not_found",+ message:+ "Password reset token not found or expired. Please request a new one.",+ });+ }++ const { identifier } = tokenFound;++ await prisma.$transaction([+ // Delete the token+ prisma.verificationToken.deleteMany({+ where: {+ token,+ },+ }),++ // Update the user's password+ prisma.user.update({+ where: {+ email: identifier,+ },+ data: {+ passwordHash: await hashPassword(password),+ emailVerified: new Date(),+ },+ }),+ ]);++ // Send the email to inform the user that their password has been updated+ await sendEmail({+ subject: `${process.env.NEXT_PUBLIC_APP_NAME}: Your password has been reset`,+ email: identifier,+ react: PasswordUpdated({+ email: identifier,+ }),+ });++ return NextResponse.json({ ok: true });+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/app/api/user/set-password/route.ts b/apps/web/app/api/user/set-password/route.tsindex a33a11f00f..f1b88948ed 100644--- a/apps/web/app/api/user/set-password/route.ts+++ b/apps/web/app/api/user/set-password/route.ts@@ -10,7 +10,7 @@ const PASSWORD_RESET_TOKEN_EXPIRY = 6 * 60 * 60 * 1000; // 6 hours// POST /api/user/set-password - set account password (for users who signed up with a OAuth provider)export const POST = withSession(async ({ session }) => {- const user = await prisma.user.findFirstOrThrow({+ const user = await prisma.user.findFirst({where: {id: session.user.id,isMachine: false,@@ -24,7 +24,8 @@ export const POST = withSession(async ({ session }) => {if (!user) {throw new DubApiError({code: "bad_request",- message: "User already has a password. Request a password reset instead.",+ message:+ "You already have a password set. You can change it in your account settings.",});}@@ -48,5 +49,5 @@ export const POST = withSession(async ({ session }) => {}),});- return NextResponse.json({});+ return NextResponse.json({ ok: true });});diff --git a/apps/web/app/app.dub.co/(auth)/auth/reset-password/[token]/form.tsx b/apps/web/app/app.dub.co/(auth)/auth/reset-password/[token]/form.tsxindex c21ab67f05..fa7657ca98 100644--- a/apps/web/app/app.dub.co/(auth)/auth/reset-password/[token]/form.tsx+++ b/apps/web/app/app.dub.co/(auth)/auth/reset-password/[token]/form.tsx@@ -1,48 +1,112 @@"use client";+import z from "@/lib/zod";+import { resetPasswordSchema } from "@/lib/zod/schemas/password";import { Button } from "@dub/ui";-import { useSearchParams } from "next/navigation";+import { cn } from "@dub/utils";+import { zodResolver } from "@hookform/resolvers/zod";+import { useParams, useRouter } from "next/navigation";import { useForm } from "react-hook-form";--type FormData = {- password: string;- confirmPassword: string;-};+import { toast } from "sonner";export const ResetPasswordForm = () => {- const searchParams = useSearchParams();+ const router = useRouter();+ const { token } = useParams<{ token: string }>();const {register,handleSubmit,formState: { isLoading, disabled, errors },- } = useForm<FormData>();+ } = useForm<z.infer<typeof resetPasswordSchema>>({+ resolver: zodResolver(resetPasswordSchema),+ });++ const onSubmit = handleSubmit(async (data) => {+ try {+ const response = await fetch("/api/auth/reset-password", {+ method: "POST",+ body: JSON.stringify(data),+ headers: {+ "Content-Type": "application/json",+ },+ });- const onSubmit = async (data) => {- console.log(data);- };+ if (response.ok) {+ toast.success(+ "Your password has been reset. You can now log in with your new password.",+ );+ router.replace("/login");+ return;+ }- console.log(errors);+ const { error } = await response.json();+ throw new Error(error.message);+ } catch (error) {+ toast.error(error.message);+ }+ });return (<>- <form- className="flex flex-col space-y-3"- onSubmit={handleSubmit(onSubmit)}- >- <input- placeholder="********"- type="password"- {...register("password", { required: true, minLength: 8 })}- aria-invalid={errors.password ? "true" : "false"}- className="w-full max-w-md rounded-md border border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"- />- <input- placeholder="********"- type="password"- {...register("confirmPassword", { required: true, minLength: 8 })}- className="w-full max-w-md rounded-md border border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"- />+ <form className="flex flex-col space-y-4" onSubmit={onSubmit}>+ <input type="hidden" value={token} {...register("token")} />+ <div>+ <label+ htmlFor="password"+ className="mb-2 block text-sm font-medium text-gray-500"+ >+ Password+ </label>+ <input+ type="password"+ placeholder="********"+ {...register("password")}+ required+ aria-invalid={errors.password ? "true" : "false"}+ className={cn(+ "w-full max-w-md rounded-md border border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm",+ errors.password && "border-red-500",+ )}+ />+ {errors.password && (+ <span+ className="mt-2 block text-sm text-red-500"+ role="alert"+ aria-live="assertive"+ >+ {errors.password.message}+ </span>+ )}+ </div>++ <div>+ <label+ htmlFor="confirmPassword"+ className="mb-2 block text-sm font-medium text-gray-500"+ >+ Confirm Password+ </label>+ <input+ type="password"+ placeholder="********"+ {...register("confirmPassword")}+ required+ className={cn(+ "w-full max-w-md rounded-md border border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm",+ errors.confirmPassword && "border-red-500",+ )}+ />+ {errors.confirmPassword && (+ <span+ className="mt-2 block text-sm text-red-500"+ role="alert"+ aria-live="assertive"+ >+ {errors.confirmPassword.message}+ </span>+ )}+ </div>+<Buttontext="Reset Password"type="submit"@@ -50,25 +114,6 @@ export const ResetPasswordForm = () => {disabled={disabled}/></form>- {/* {noSuchAccount ? (- <p className="text-center text-sm text-red-500">- No such account.{" "}- <Link href="/register" className="font-semibold text-red-600">- Sign up- </Link>{" "}- instead?- </p>- ) : (- <p className="text-center text-sm text-gray-500">- Don't have an account?{" "}- <Link- href="/register"- className="font-semibold text-gray-500 transition-colors hover:text-black"- >- Sign up- </Link>- </p>- )} */}</>);};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 802beaa858..262197e703 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,8 +1,19 @@+import { prisma } from "@/lib/prisma";import { Logo } from "@dub/ui";import { HOME_DOMAIN } from "@dub/utils";import { ResetPasswordForm } from "./form";-export default function ResetPasswordPage() {+export const runtime = "nodejs";++interface Props {+ params: {+ token: string;+ };+}++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">@@ -11,12 +22,36 @@ export default function ResetPasswordPage() {</a><h3 className="text-xl font-semibold">Reset your password</h3><p className="text-sm text-gray-500">- Enter new password for your account.+ {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">- <ResetPasswordForm />+ {validToken ? (+ <ResetPasswordForm />+ ) : (+ <div className="text-center">+ That request is expired or invalid. Please request a new one.+ </div>+ )}</div></div>);}++const isValidToken = async (token: string) => {+ const resetToken = await prisma.verificationToken.findUnique({+ where: {+ token,+ expires: {+ gte: new Date(),+ },+ },+ select: {+ token: true,+ },+ });++ return !!resetToken;+};diff --git a/apps/web/app/app.dub.co/(dashboard)/settings/security/password.tsx b/apps/web/app/app.dub.co/(dashboard)/settings/security/password.tsxindex 0fa26a0ada..33319cc051 100644--- a/apps/web/app/app.dub.co/(dashboard)/settings/security/password.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/settings/security/password.tsx@@ -52,36 +52,4 @@ export const SetPassword = () => {</div></div>);-- // return (- // <Form- // title="Password"- // description="Manage your account password."- // inputAttrs={{- // name: "password",- // defaultValue:- // status === "loading" ? undefined : session?.user?.name || "",- // placeholder: "Steve Jobs",- // maxLength: 32,- // }}- // helpText="Max 32 characters."- // handleSubmit={(data) =>- // fetch("/api/user", {- // method: "PATCH",- // headers: {- // "Content-Type": "application/json",- // },- // body: JSON.stringify(data),- // }).then(async (res) => {- // if (res.status === 200) {- // update();- // toast.success("Successfully updated your name!");- // } else {- // const { error } = await res.json();- // toast.error(error.message);- // }- // })- // }- // />- // );};diff --git a/apps/web/emails/index.ts b/apps/web/emails/index.tsindex 19f0def350..d5d3bc4905 100644--- a/apps/web/emails/index.ts+++ b/apps/web/emails/index.ts@@ -23,6 +23,8 @@ export const sendEmail = async ({react?: ReactElement<any, string | JSXElementConstructor<any>>;marketing?: boolean;}) => {+ return true+if (process.env.NODE_ENV === "development" && !client) {// Set up a fake email client for developmentconsole.info(diff --git a/apps/web/emails/password-updated.tsx b/apps/web/emails/password-updated.tsxnew file mode 100644index 0000000000..837a22cc28--- /dev/null+++ b/apps/web/emails/password-updated.tsx@@ -0,0 +1,55 @@+import { DUB_WORDMARK } from "@dub/utils";+import {+ Body,+ Container,+ Head,+ Heading,+ Html,+ Img,+ Preview,+ Section,+ Tailwind,+ Text,+} from "@react-email/components";+import Footer from "./components/footer";++export default function PasswordUpdated({+ email = "[email protected]",+}: {+ email: string;+}) {+ return (+ <Html>+ <Head />+ <Preview>Your Dub.co Login Link</Preview>+ <Tailwind>+ <Body className="mx-auto my-auto bg-white font-sans">+ <Container className="mx-auto my-10 max-w-[500px] rounded border border-solid border-gray-200 px-10 py-5">+ <Section className="mt-8">+ <Img+ src={DUB_WORDMARK}+ height="40"+ alt="Dub"+ className="mx-auto my-0"+ />+ </Section>+ <Heading className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">+ Your Login Link+ </Heading>+ <Text className="text-sm leading-6 text-black">+ Welcome to Dub.co!+ </Text>+ <Text className="text-sm leading-6 text-black">+ Please click the magic link below to sign in to your account.+ </Text>+ <Section className="my-8 text-center"></Section>+ <Text className="text-sm leading-6 text-black">+ or copy and paste this URL into your browser:+ </Text>+ <Footer email={email} />+ </Container>+ </Body>+ </Tailwind>+ </Html>+ );+}diff --git a/apps/web/lib/auth/password.ts b/apps/web/lib/auth/password.tsnew file mode 100644index 0000000000..4531c68576--- /dev/null+++ b/apps/web/lib/auth/password.ts@@ -0,0 +1,15 @@+import { compare, hash } from "bcryptjs";++export async function hashPassword(password: string) {+ return await hash(password, 12);+}++export async function validatePassword({+ password,+ hashedPassword,+}: {+ password: string;+ hashedPassword: string;+}) {+ return await compare(password, hashedPassword);+}diff --git a/apps/web/lib/middleware/app.ts b/apps/web/lib/middleware/app.tsindex fc599200d7..2016ddfdaa 100644--- a/apps/web/lib/middleware/app.ts+++ b/apps/web/lib/middleware/app.ts@@ -14,7 +14,8 @@ export default async function AppMiddleware(req: NextRequest) {!user &&path !== "/login" &&path !== "/register" &&- path !== "/auth/saml"+ path !== "/auth/saml" &&+ !path.startsWith("/auth/reset-password/")) {return NextResponse.redirect(new URL(diff --git a/apps/web/lib/zod/schemas/password.ts b/apps/web/lib/zod/schemas/password.tsnew file mode 100644index 0000000000..1329420e9f--- /dev/null+++ b/apps/web/lib/zod/schemas/password.ts@@ -0,0 +1,7 @@+import z from "@/lib/zod";++export const resetPasswordSchema = z.object({+ token: z.string().min(1),+ password: z.string().min(8, "Password must be at least 8 characters"),+ confirmPassword: z.string(),+});diff --git a/apps/web/package.json b/apps/web/package.jsonindex df9a0f7c58..5ef9a6887e 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -20,6 +20,7 @@"@dub/tailwind-config": "workspace:*","@dub/ui": "workspace:*","@dub/utils": "workspace:*",+ "@hookform/resolvers": "^3.9.0","@next-auth/prisma-adapter": "^1.0.5","@planetscale/database": "^1.18.0","@prisma/adapter-planetscale": "^5.13.0",@@ -32,6 +33,7 @@"@stripe/stripe-js": "^1.44.1","@tanstack/react-table": "^8.17.3","@team-plain/typescript-sdk": "^4.5.0",+ "@types/bcryptjs": "^2.4.6","@upstash/qstash": "^2.3.0","@upstash/ratelimit": "^1.1.3","@upstash/redis": "^1.25.1",@@ -55,6 +57,7 @@"@visx/tooltip": "^2.16.0","ai": "^3.1.22","aws4fetch": "^1.0.18",+ "bcryptjs": "^2.4.3","bottleneck": "^2.19.5","cmdk": "^0.2.0","cobe": "^0.6.3",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d711f76e1f..e1f9cadde5 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -56,6 +56,9 @@ importers:'@dub/utils':specifier: workspace:*version: link:../../packages/utils+ '@hookform/resolvers':+ specifier: ^3.9.0+ version: 3.9.0([email protected])'@next-auth/prisma-adapter':specifier: ^1.0.5version: 1.0.5(@prisma/[email protected])([email protected])@@ -92,6 +95,9 @@ importers:'@team-plain/typescript-sdk':specifier: ^4.5.0version: 4.5.0+ '@types/bcryptjs':+ specifier: ^2.4.6+ version: 2.4.6'@upstash/qstash':specifier: ^2.3.0version: 2.3.0@@ -161,6 +167,9 @@ importers:aws4fetch:specifier: ^1.0.18version: 1.0.18+ bcryptjs:+ specifier: ^2.4.3+ version: 2.4.3bottleneck:specifier: ^2.19.5version: 2.19.5@@ -3715,6 +3724,14 @@ packages:'@hapi/hoek': 9.3.0dev: false+ /@hookform/[email protected]([email protected]):+ resolution: {integrity: sha512-bU0Gr4EepJ/EQsH/IwEzYLsT/PEj5C0ynLQ4m+GSHS+xKH4TfSelhluTgOaoc4kA5s7eCsQbM4wvZLzELmWzUg==}+ peerDependencies:+ react-hook-form: ^7.0.0+ dependencies:+ react-hook-form: 7.52.1([email protected])+ dev: false+/@humanwhocodes/[email protected]:resolution: {integrity: sha512-N2brEuAadi0CcdeMXUkhbZB84eskAc8MEX1By6qEchoVywSgXPIjou4rYsl0V3Hj0ZnuGycGCjdNgockbzeWNA==}engines: {node: '>=10.10.0'}@@ -7907,6 +7924,10 @@ packages:'@babel/types': 7.23.0dev: true+ /@types/[email protected]:+ resolution: {integrity: sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==}+ dev: false+/@types/[email protected]:resolution: {integrity: sha512-WFHg/KFLCdUQl3m27WSQu0NEaLzoHGmgZHlsSYr0Y0iIvItMcBq7opZc6AGXPXqf+btIM6vTBJyLvuDAihB+zQ==}dev: false@@ -9619,6 +9640,10 @@ packages:engines: {node: ^4.5.0 || >= 5.9}dev: false+ resolution: {integrity: sha512-V/Hy/X9Vt7f3BbPJEi8BdVFMByHi+jNXrYkW3huaybV/kQ0KJg0Y6PkEMbn+zeT+i+SiKZ/HMqJGIIt4LZDqNQ==}+ dev: false+resolution: {integrity: sha512-2/mKyZH9K85bzOEfhXDBFZTGd1CTs+5IHpeFQo9luiBG7hghdC851Pj2WAhb6E3R6b9tZj/XKhbg4fum+Kepug==}dev: false