From 9d7dc09974d9f9b73925f588e31bbb8aaf81d6e3 Mon Sep 17 00:00:00 2001 From: Alex van Andel Date: Tue, 21 Dec 2021 18:31:32 +0100 Subject: [PATCH] Use the matched user email to send the password reset to (#1366) --- pages/api/auth/forgot-password.ts | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/pages/api/auth/forgot-password.ts b/pages/api/auth/forgot-password.ts index 08246446b5fc80..5831ed88875d98 100644 --- a/pages/api/auth/forgot-password.ts +++ b/pages/api/auth/forgot-password.ts @@ -1,7 +1,5 @@ import { ResetPasswordRequest } from "@prisma/client"; import dayjs from "dayjs"; -import timezone from "dayjs/plugin/timezone"; -import utc from "dayjs/plugin/utc"; import { NextApiRequest, NextApiResponse } from "next"; import { sendPasswordResetEmail } from "@lib/emails/email-manager"; @@ -10,25 +8,21 @@ import prisma from "@lib/prisma"; import { getTranslation } from "@server/lib/i18n"; -dayjs.extend(utc); -dayjs.extend(timezone); - export default async function handler(req: NextApiRequest, res: NextApiResponse) { const t = await getTranslation(req.body.language ?? "en", "common"); if (req.method !== "POST") { - return res.status(405).json({ message: "" }); + return res.status(405).end(); } try { - const rawEmail = req.body?.email; - const maybeUser = await prisma.user.findUnique({ where: { - email: rawEmail, + email: req.body?.email?.toLowerCase(), }, select: { name: true, + email: true, }, }); @@ -36,12 +30,11 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) return res.status(400).json({ message: "Couldn't find an account for this email" }); } - const now = dayjs().toDate(); const maybePreviousRequest = await prisma.resetPasswordRequest.findMany({ where: { - email: rawEmail, + email: maybeUser.email, expires: { - gt: now, + gt: new Date(), }, }, }); @@ -54,7 +47,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const expiry = dayjs().add(PASSWORD_RESET_EXPIRY_HOURS, "hours").toDate(); const createdResetPasswordRequest = await prisma.resetPasswordRequest.create({ data: { - email: rawEmail, + email: maybeUser.email, expires: expiry, }, }); @@ -63,10 +56,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const passwordEmail: PasswordReset = { language: t, - user: { - name: maybeUser.name, - email: rawEmail, - }, + user: maybeUser, resetLink: `${process.env.BASE_URL}/auth/forgot-password/${passwordRequest.id}`, }; @@ -74,7 +64,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) return res.status(201).json({ message: "Reset Requested" }); } catch (reason) { - console.error(reason); + // console.error(reason); return res.status(500).json({ message: "Unable to create password reset request" }); } }