el.xwx.moe/lib/api/sendVerificationRequest.ts

53 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-05-16 14:02:22 -05:00
import { readFileSync } from "fs";
import path from "path";
import Handlebars from "handlebars";
import transporter from "./transporter";
2023-07-12 13:26:34 -05:00
type Params = {
identifier: string;
url: string;
from: string;
token: string;
};
export default async function sendVerificationRequest({
identifier,
url,
from,
token,
}: Params) {
2024-05-16 14:02:22 -05:00
const emailsDir = path.resolve(process.cwd(), "templates");
const templateFile = readFileSync(
path.join(emailsDir, "verifyEmail.html"),
"utf8"
);
const emailTemplate = Handlebars.compile(templateFile);
2023-07-12 13:26:34 -05:00
const { host } = new URL(url);
2024-05-16 14:02:22 -05:00
const result = await transporter.sendMail({
2023-07-12 13:26:34 -05:00
to: identifier,
2024-05-17 02:15:18 -05:00
from: {
name: "Linkwarden",
address: from as string,
2024-05-17 02:15:18 -05:00
},
2024-05-16 14:02:22 -05:00
subject: `Please verify your email address`,
2023-07-12 13:26:34 -05:00
text: text({ url, host }),
2024-05-16 14:02:22 -05:00
html: emailTemplate({
url: `${
process.env.NEXTAUTH_URL
}/callback/email?token=${token}&email=${encodeURIComponent(identifier)}`,
}),
2023-07-12 13:26:34 -05:00
});
const failed = result.rejected.concat(result.pending).filter(Boolean);
if (failed.length) {
throw new Error(`Email (${failed.join(", ")}) could not be sent`);
}
}
/** Email Text body (fallback for email clients that don't render HTML, e.g. feature phones) */
function text({ url, host }: { url: string; host: string }) {
return `Sign in to ${host}\n${url}\n\n`;
}