2023-02-16 22:39:57 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
2023-03-20 11:20:29 +00:00
|
|
|
import { z } from "zod";
|
2021-09-22 19:52:38 +00:00
|
|
|
|
2023-08-04 00:26:40 +00:00
|
|
|
import { passwordResetRequest } from "@calcom/features/auth/lib/passwordResetRequest";
|
2023-06-26 19:44:58 +00:00
|
|
|
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
|
2023-05-30 19:26:29 +00:00
|
|
|
import { defaultHandler } from "@calcom/lib/server";
|
2022-06-28 20:40:58 +00:00
|
|
|
import prisma from "@calcom/prisma";
|
2021-10-25 13:05:21 +00:00
|
|
|
|
2023-05-30 19:26:29 +00:00
|
|
|
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
2023-03-20 11:20:29 +00:00
|
|
|
const email = z
|
|
|
|
.string()
|
|
|
|
.email()
|
|
|
|
.transform((val) => val.toLowerCase())
|
2023-05-30 19:26:29 +00:00
|
|
|
.safeParse(req.body?.email);
|
2023-03-20 11:20:29 +00:00
|
|
|
|
2023-05-30 19:26:29 +00:00
|
|
|
if (!email.success) {
|
|
|
|
return res.status(400).json({ message: "email is required" });
|
|
|
|
}
|
2023-03-20 11:20:29 +00:00
|
|
|
|
2023-05-30 19:26:29 +00:00
|
|
|
// fallback to email if ip is not present
|
|
|
|
let ip = (req.headers["x-real-ip"] as string) ?? email.data;
|
|
|
|
|
|
|
|
const forwardedFor = req.headers["x-forwarded-for"] as string;
|
|
|
|
if (!ip && forwardedFor) {
|
|
|
|
ip = forwardedFor?.split(",").at(0) ?? email.data;
|
2023-03-20 11:20:29 +00:00
|
|
|
}
|
2021-10-25 13:05:21 +00:00
|
|
|
|
2023-05-30 19:26:29 +00:00
|
|
|
// 10 requests per minute
|
|
|
|
|
2023-06-26 19:44:58 +00:00
|
|
|
await checkRateLimitAndThrowError({
|
|
|
|
rateLimitingType: "core",
|
2023-06-19 10:01:06 +00:00
|
|
|
identifier: ip,
|
|
|
|
});
|
|
|
|
|
2021-06-24 15:59:11 +00:00
|
|
|
try {
|
2023-08-04 00:26:40 +00:00
|
|
|
const user = await prisma.user.findUnique({
|
|
|
|
where: { email: email.data },
|
|
|
|
select: { name: true, email: true, locale: true },
|
2021-06-24 15:59:11 +00:00
|
|
|
});
|
2023-08-04 00:26:40 +00:00
|
|
|
// Don't leak info about whether the user exists
|
|
|
|
if (!user) return res.status(201).json({ message: "password_reset_email_sent" });
|
|
|
|
await passwordResetRequest(user);
|
|
|
|
return res.status(201).json({ message: "password_reset_email_sent" });
|
2021-06-24 15:59:11 +00:00
|
|
|
} catch (reason) {
|
2023-08-04 00:26:40 +00:00
|
|
|
console.error(reason);
|
2021-06-24 15:59:11 +00:00
|
|
|
return res.status(500).json({ message: "Unable to create password reset request" });
|
|
|
|
}
|
|
|
|
}
|
2023-05-30 19:26:29 +00:00
|
|
|
|
|
|
|
export default defaultHandler({
|
|
|
|
POST: Promise.resolve({ default: handler }),
|
|
|
|
});
|