Skip to content

Commit

Permalink
Use the matched user email to send the password reset to (#1366)
Browse files Browse the repository at this point in the history
  • Loading branch information
emrysal committed Dec 21, 2021
1 parent bab72f1 commit 9d7dc09
Showing 1 changed file with 8 additions and 18 deletions.
26 changes: 8 additions & 18 deletions pages/api/auth/forgot-password.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -10,38 +8,33 @@ 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,
},
});

if (!maybeUser) {
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(),
},
},
});
Expand All @@ -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,
},
});
Expand All @@ -63,18 +56,15 @@ 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}`,
};

await sendPasswordResetEmail(passwordEmail);

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" });
}
}

0 comments on commit 9d7dc09

Please sign in to comment.