The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
import { DubApiError } from "@/lib/api/errors";
import { withSession } from "@/lib/auth";
import { PASSWORD_RESET_TOKEN_EXPIRY } from "@/lib/auth/constants";
import { prisma } from "@/lib/prisma";
import { sendEmail } from "@dub/email";
import ResetPasswordLink from "@dub/email/templates/reset-password-link";
import { APP_DOMAIN } from "@dub/utils";
import { randomBytes } from "crypto";
import { NextResponse } from "next/server";
// 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.findFirst({
where: {
id: session.user.id,
isMachine: false,
passwordHash: null,
},
select: {
id: true,
},
});
if (!user) {
throw new DubApiError({
code: "bad_request",
message:
"You already have a password set. You can change it in your account settings.",
});
}
const { token } = await prisma.passwordResetToken.create({
data: {
identifier: session.user.email,
token: randomBytes(32).toString("hex"),
expires: new Date(Date.now() + PASSWORD_RESET_TOKEN_EXPIRY * 1000),
},
});
// Send email with password reset link
await sendEmail({
subject: "Dub: Password reset instructions",
to: session.user.email,
react: ResetPasswordLink({
email: session.user.email,
url: `${APP_DOMAIN}/auth/reset-password/${token}`,
}),
});
if (process.env.NODE_ENV === "development") {
console.info(
"Password reset URL:",
`${APP_DOMAIN}/auth/reset-password/${token}`,
);
}
return NextResponse.json({ ok: true });
});