2021-06-24 15:59:11 +00:00
|
|
|
import { User, ResetPasswordRequest } from "@prisma/client";
|
2021-09-22 19:52:38 +00:00
|
|
|
import dayjs from "dayjs";
|
2021-06-24 15:59:11 +00:00
|
|
|
import timezone from "dayjs/plugin/timezone";
|
|
|
|
import utc from "dayjs/plugin/utc";
|
2021-09-22 19:52:38 +00:00
|
|
|
import { NextApiRequest, NextApiResponse } from "next";
|
|
|
|
|
|
|
|
import sendEmail from "../../../lib/emails/sendMail";
|
|
|
|
import { buildForgotPasswordMessage } from "../../../lib/forgot-password/messaging/forgot-password";
|
|
|
|
import prisma from "../../../lib/prisma";
|
|
|
|
|
2021-06-24 15:59:11 +00:00
|
|
|
dayjs.extend(utc);
|
|
|
|
dayjs.extend(timezone);
|
|
|
|
|
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
|
|
if (req.method !== "POST") {
|
2021-06-25 14:17:39 +00:00
|
|
|
return res.status(405).json({ message: "" });
|
2021-06-24 15:59:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
const rawEmail = req.body?.email;
|
|
|
|
|
|
|
|
const maybeUser: User = await prisma.user.findUnique({
|
|
|
|
where: {
|
|
|
|
email: rawEmail,
|
|
|
|
},
|
|
|
|
select: {
|
|
|
|
name: 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,
|
|
|
|
expires: {
|
|
|
|
gt: now,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
let passwordRequest: ResetPasswordRequest;
|
|
|
|
|
|
|
|
if (maybePreviousRequest && maybePreviousRequest?.length >= 1) {
|
|
|
|
passwordRequest = maybePreviousRequest[0];
|
|
|
|
} else {
|
2021-06-25 14:23:32 +00:00
|
|
|
const expiry = dayjs().add(6, "hours").toDate();
|
2021-06-24 15:59:11 +00:00
|
|
|
const createdResetPasswordRequest = await prisma.resetPasswordRequest.create({
|
|
|
|
data: {
|
|
|
|
email: rawEmail,
|
|
|
|
expires: expiry,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
passwordRequest = createdResetPasswordRequest;
|
|
|
|
}
|
|
|
|
|
2021-06-25 14:16:24 +00:00
|
|
|
const passwordResetLink = `${process.env.BASE_URL}/auth/forgot-password/${passwordRequest.id}`;
|
2021-06-24 15:59:11 +00:00
|
|
|
const { subject, message } = buildForgotPasswordMessage({
|
|
|
|
user: {
|
|
|
|
name: maybeUser.name,
|
|
|
|
},
|
|
|
|
link: passwordResetLink,
|
|
|
|
});
|
|
|
|
|
|
|
|
await sendEmail({
|
|
|
|
to: rawEmail,
|
|
|
|
subject: subject,
|
|
|
|
text: message,
|
|
|
|
});
|
|
|
|
|
2021-09-19 14:31:45 +00:00
|
|
|
return res.status(201).json({ message: "Reset Requested" });
|
2021-06-24 15:59:11 +00:00
|
|
|
} catch (reason) {
|
|
|
|
console.error(reason);
|
|
|
|
return res.status(500).json({ message: "Unable to create password reset request" });
|
|
|
|
}
|
|
|
|
}
|