Files
sign/apps/web/pages/api/auth/forgot-password.ts

64 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-06-05 13:05:25 +00:00
import { NextApiRequest, NextApiResponse } from "next";
import { sendResetPassword } from "@documenso/lib/mail";
2023-06-05 13:05:25 +00:00
import { defaultHandler, defaultResponder } from "@documenso/lib/server";
import prisma from "@documenso/prisma";
import crypto from "crypto";
async function postHandler(req: NextApiRequest, res: NextApiResponse) {
const { email } = req.body;
const cleanEmail = email.toLowerCase();
2023-06-07 10:44:07 +00:00
if (!cleanEmail || !/.+@.+/.test(cleanEmail)) {
res.status(400).json({ message: "Invalid email" });
2023-06-05 13:05:25 +00:00
return;
}
const user = await prisma.user.findFirst({
where: {
email: cleanEmail,
},
});
if (!user) {
return res.status(200).json({ message: "A password reset email has been sent." });
2023-06-05 13:05:25 +00:00
}
const existingToken = await prisma.passwordResetToken.findFirst({
where: {
userId: user.id,
createdAt: {
gte: new Date(Date.now() - 1000 * 60 * 60),
},
},
});
if (existingToken) {
return res.status(200).json({ message: "A password reset email has been sent." });
}
2023-06-05 13:05:25 +00:00
const token = crypto.randomBytes(64).toString("hex");
2023-06-05 16:54:12 +00:00
const expiry = new Date();
2023-06-07 11:02:50 +00:00
expiry.setHours(expiry.getHours() + 24); // Set expiry to one hour from now
2023-06-05 15:52:00 +00:00
let passwordResetToken;
try {
passwordResetToken = await prisma.passwordResetToken.create({
data: {
token,
2023-06-05 16:54:12 +00:00
expiry,
2023-06-05 15:52:00 +00:00
userId: user.id,
},
});
} catch (error) {
2023-06-05 16:54:12 +00:00
return res.status(500).json({ message: "Something went wrong" });
2023-06-05 15:52:00 +00:00
}
2023-06-05 13:05:25 +00:00
2023-06-05 13:44:22 +00:00
await sendResetPassword(user, passwordResetToken.token);
2023-06-05 13:05:25 +00:00
return res.status(200).json({ message: "A password reset email has been sent." });
2023-06-05 13:05:25 +00:00
}
export default defaultHandler({
POST: Promise.resolve({ default: defaultResponder(postHandler) }),
});