summaryrefslogtreecommitdiff
path: root/src/routes/magicLink.ts
diff options
context:
space:
mode:
authorRaphael Kabo <raphaelkabo@hey.com>2024-02-25 17:56:25 +0000
committerRaphael Kabo <raphaelkabo@hey.com>2024-02-25 17:56:25 +0000
commitcd0f291eb1a608589fcc2c1875fa7099ed8e2c51 (patch)
tree05b1d8b1d63baed174883cc96807051e530969a2 /src/routes/magicLink.ts
parentb17238eb2840553c69fc2dae168be557afbcee9c (diff)
feat: optionally restrict event creation to specific emails
Diffstat (limited to 'src/routes/magicLink.ts')
-rw-r--r--src/routes/magicLink.ts70
1 files changed, 70 insertions, 0 deletions
diff --git a/src/routes/magicLink.ts b/src/routes/magicLink.ts
new file mode 100644
index 0000000..24f0667
--- /dev/null
+++ b/src/routes/magicLink.ts
@@ -0,0 +1,70 @@
+import { Router, Request, Response } from "express";
+import getConfig, { frontendConfig } from "../lib/config.js";
+import { sendEmailFromTemplate } from "../lib/email.js";
+import { generateMagicLinkToken } from "../util/generator.js";
+import MagicLink from "../models/MagicLink.js";
+
+const router = Router();
+const config = getConfig();
+
+router.post("/magic-link/event/create", async (req: Request, res: Response) => {
+ const { email } = req.body;
+ if (!email) {
+ res.render("createEventMagicLink", {
+ ...frontendConfig(),
+ message: {
+ type: "danger",
+ text: "Please provide an email address.",
+ },
+ });
+ return;
+ }
+ const allowedEmails = config.general.creator_email_addresses;
+ if (!allowedEmails?.length) {
+ // No creator email addresses are configured, so skip the magic link check
+ return res.redirect("/new");
+ }
+ if (!allowedEmails.includes(email)) {
+ res.render("createEventMagicLink", {
+ ...frontendConfig(),
+ message: {
+ type: "success",
+ text: "Thanks! If this email address can create events, you should receive an email with a magic link.",
+ },
+ });
+ return;
+ }
+ const token = generateMagicLinkToken();
+ const magicLink = new MagicLink({
+ email,
+ token,
+ expiryTime: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours
+ permittedActions: ["createEvent"],
+ });
+ await magicLink.save();
+
+ // Take this opportunity to delete any expired magic links
+ await MagicLink.deleteMany({ expiryTime: { $lt: new Date() } });
+
+ sendEmailFromTemplate(
+ email,
+ `Magic link to create an event`,
+ "createEventMagicLink",
+ {
+ token,
+ siteName: config.general.site_name,
+ siteLogo: config.general.email_logo_url,
+ domain: config.general.domain,
+ },
+ req,
+ );
+ res.render("createEventMagicLink", {
+ ...frontendConfig(),
+ message: {
+ type: "success",
+ text: "Thanks! If this email address can create events, you should receive an email with a magic link.",
+ },
+ });
+});
+
+export default router;