The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
import { getIP } from "@/lib/api/utils/get-ip";
import { hashPassword, validatePassword } from "@/lib/auth/password";
import { prisma } from "@/lib/prisma";
import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { resetPasswordSchema } from "@/lib/zod/schemas/auth";
import { sendEmail } from "@dub/email";
import PasswordUpdated from "@dub/email/templates/password-updated";
import { waitUntil } from "@vercel/functions";
import { NextRequest, NextResponse } from "next/server";
// POST /api/auth/reset-password - reset password using the reset token
export async function POST(req: NextRequest) {
try {
await assertRateLimit({
policy: RATELIMIT_POLICIES.passwordReset,
identifier: await getIP(),
});
const { token, password } = resetPasswordSchema.parse(
await parseRequestBody(req),
);
// Find the token
const tokenFound = await prisma.passwordResetToken.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;
const user = await prisma.user.findUniqueOrThrow({
where: {
email: identifier,
},
select: {
emailVerified: true,
passwordHash: true,
},
});
// Check if the new password is the same as the current password
if (user.passwordHash) {
const isSamePassword = await validatePassword({
password,
passwordHash: user.passwordHash,
});
if (isSamePassword) {
throw new DubApiError({
code: "unprocessable_entity",
message:
"Your new password cannot be the same as your current password.",
});
}
}
await prisma.$transaction([
// Delete the token
prisma.passwordResetToken.deleteMany({
where: {
token,
},
}),
// Update the user's password
prisma.user.update({
where: {
email: identifier,
},
data: {
passwordHash: await hashPassword(password),
lockedAt: null, // Unlock the account after a successful password reset
...(!user.emailVerified && { emailVerified: new Date() }), // Mark the email as verified
},
}),
]);
// Send the email to inform the user that their password has been reset
waitUntil(
sendEmail({
subject: "Your Dub account password has been reset",
to: identifier,
react: PasswordUpdated({
email: identifier,
verb: "reset",
}),
}),
);
return NextResponse.json({ ok: true });
} catch (error) {
return handleAndReturnErrorResponse(error);
}
}