el.xwx.moe/pages/api/v1/auth/forgot-password.ts

64 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-05-18 22:57:00 -05:00
import { prisma } from "@/lib/api/db";
import sendPasswordResetRequest from "@/lib/api/sendPasswordResetRequest";
2024-09-14 15:00:19 -05:00
import { ForgotPasswordSchema } from "@/lib/shared/schemaValidation";
2024-05-18 22:57:00 -05:00
import type { NextApiRequest, NextApiResponse } from "next";
export default async function forgotPassword(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === "POST") {
2024-07-18 15:29:59 -05:00
if (process.env.NEXT_PUBLIC_DEMO === "true")
return res.status(400).json({
response:
"This action is disabled because this is a read-only demo of Linkwarden.",
});
2024-09-14 15:00:19 -05:00
const dataValidation = ForgotPasswordSchema.safeParse(req.body);
2024-05-18 22:57:00 -05:00
2024-09-14 15:00:19 -05:00
if (!dataValidation.success) {
2024-05-18 22:57:00 -05:00
return res.status(400).json({
2024-09-14 15:00:19 -05:00
response: `Error: ${
dataValidation.error.issues[0].message
} [${dataValidation.error.issues[0].path.join(", ")}]`,
2024-05-18 22:57:00 -05:00
});
}
2024-09-14 15:00:19 -05:00
const { email } = dataValidation.data;
2024-05-18 22:57:00 -05:00
const recentPasswordRequestsCount = await prisma.passwordResetToken.count({
where: {
identifier: email,
createdAt: {
gt: new Date(new Date().getTime() - 1000 * 60 * 5), // 5 minutes
},
},
});
// Rate limit password reset requests
if (recentPasswordRequestsCount >= 3) {
return res.status(400).json({
response: "Too many requests. Please try again later.",
});
}
const user = await prisma.user.findFirst({
where: {
email,
},
});
if (!user || !user.email) {
return res.status(400).json({
2024-09-14 15:00:19 -05:00
response: "No user found with that email.",
2024-05-18 22:57:00 -05:00
});
}
sendPasswordResetRequest(user.email, user.name || "Linkwarden User");
2024-05-18 22:57:00 -05:00
return res.status(200).json({
response: "Password reset email sent.",
});
}
}