const domainChecker = async (req, res, next) => { const formUuid = req.params.formUuid; const referer = req.headers.referer || req.headers.origin; try { const [rows] = await req.db.query( "SELECT allowed_domains FROM forms WHERE uuid = ?", [formUuid] ); if (rows.length === 0) { return res.status(404).json({ error: "Form not found" }); } const form = rows[0]; // If no domains are specified or it's empty/null, allow all if (!form.allowed_domains || form.allowed_domains.trim() === "") { return next(); } const allowedDomains = form.allowed_domains.split(",").map((d) => d.trim()); if (!referer) { return res.status(403).json({ error: "Referer header is required" }); } const refererUrl = new URL(referer); const isAllowed = allowedDomains.some( (domain) => refererUrl.hostname === domain || refererUrl.hostname.endsWith("." + domain) ); if (!isAllowed) { return res .status(403) .json({ error: "Submission not allowed from this domain" }); } next(); } catch (error) { console.error("Domain check error:", error); res.status(500).json({ error: "Internal server error" }); } }; module.exports = domainChecker;