import express from "express"; import nodemailer from "nodemailer"; import svgCaptcha from "svg-captcha"; import { sendResponse } from "../../../libs/format"; import { mailMethod, smtpConfig, mailTo, siteName } from "../../../config"; import ErrorEvent from "../../../libs/error"; // eslint-disable-next-line new-cap const router = express.Router(); router .route("/") .get(async (req, res, next) => { try { const captcha = svgCaptcha.create({ size: 4, noise: 2, color: true, }); req.session.captcha = captcha.text; res.type("svg"); return res.status(200).send(captcha.data); } catch (err) { return next(err); } }) .post(async (req, res, next) => { try { if (mailMethod === "smtp") { const { email, name, message, captcha } = req.body; if (!captcha || captcha !== req.session.captcha) { throw new ErrorEvent( 406, "Captcha", "Le captcha n'est pas valide" ); } if (!email || !message) { throw new ErrorEvent( 406, "Erreur de saisie", "Le formulaire n'est pas correctement saisi" ); } const transporter = nodemailer.createTransport(smtpConfig); const text = `Bonjour, Vous venez de recevoir un nouveau message de ${name} (${email}) : ${message} `; const data = await transporter.sendMail({ from: smtpConfig.auth.user, to: mailTo, subject: `${siteName} : Nouveau message`, text, }); const { messageId, response } = data; return sendResponse(req, res, { messageId, response }); } throw new ErrorEvent(500, "Routeur", "Méthode non configurée"); } catch (err) { return next(err); } }); export default router;