Skip to content

Commit

Permalink
feat: add send form contact mail endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
MaGOs92 committed Dec 8, 2023
1 parent dd90b9b commit 8872ef0
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 10 deletions.
3 changes: 2 additions & 1 deletion .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,5 @@ KEYCLOAK_ISSUER=
KEYCLOAK_CLIENT_ID=
KEYCLOAK_CLIENT_SECRET=
NEXTAUTH_URL=
NEXTAUTH_SECRET=
NEXTAUTH_SECRET=
RE_CAPTCHA_SECRET_KEY=
11 changes: 11 additions & 0 deletions server/lib/bal-widget/controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const express = require("express");
const cors = require("cors");
const {routeGuard} = require('../../route-guard')
const BALWidgetService = require("./service");
const MailerService = require("../mailer/service");

const BALWidgetRoutes = new express.Router();

Expand All @@ -28,4 +29,14 @@ BALWidgetRoutes.post("/config", routeGuard, async (req, res) => {
}
});

BALWidgetRoutes.post("/send-mail", async (req, res) => {
try {
await MailerService.sendFormContactMail(req.body);
res.json(config);
} catch (err) {
console.error(err);
res.status(500).json({ error: err.message });
}
});

module.exports = BALWidgetRoutes;
23 changes: 16 additions & 7 deletions server/lib/mailer/email.templates.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
module.exports = {
'candidature-partenaire-de-la-charte': {
from: process.env.SMTP_FROM || '[email protected]',
to: '[email protected]',
subject: 'Nouvelle candidature aux partenaires de la charte',
"candidature-partenaire-de-la-charte": {
from: process.env.SMTP_FROM || "[email protected]",
to: "[email protected]",
subject: "Nouvelle candidature aux partenaires de la charte",
text: `Bonjour,\n\nUne nouvelle candidature aux partenaires de la charte a été soumise.\n\nVous pouvez la consulter sur <a href="${process.env.NEXT_PUBLIC_BAL_ADMIN_URL}/partenaires-de-la-charte?tab=candidatures">BAL Admin</a>.\n\nBonne journée,\n\nL’équipe BAL`,
html: `<p>Bonjour,</p><p>Une nouvelle candidature aux partenaires de la charte a été soumise.</p><p>Vous pouvez la consulter sur <a href="${process.env.NEXT_PUBLIC_BAL_ADMIN_URL}/partenaires-de-la-charte?tab=candidatures">BAL Admin</a>.</p><p>Bonne journée,</p><p>L’équipe BAL</p>`
}
}
html: `<p>Bonjour,</p><p>Une nouvelle candidature aux partenaires de la charte a été soumise.</p><p>Vous pouvez la consulter sur <a href="${process.env.NEXT_PUBLIC_BAL_ADMIN_URL}/partenaires-de-la-charte?tab=candidatures">BAL Admin</a>.</p><p>Bonne journée,</p><p>L’équipe BAL</p>`,
},
contact: ({ firstName, lastName, email, message, subject }) => {
return {
from: process.env.SMTP_FROM || "[email protected]",
to: "[email protected]",
subject,
text: `Bonjour,\n\nVous avez reçu un nouveau message via le formulaire de contact de BAL Widget.\n\nNom: ${lastName}\nPrénom: ${firstName}\nEmail: ${email}\n\nMessage:\n${message}\n\nBonne journée,\n\nL’équipe BAL`,
html: `<p>Bonjour,</p><p>Vous avez reçu un nouveau message via le formulaire de contact de la BAL Widget.</p><p>Nom: ${lastName}</p><p>Prénom: ${firstName}</p><p>Email: ${email}</p><p>Message:</p><p>${message}</p><p>Bonne journée,</p><p>L’équipe BAL</p>`
};
},
};
14 changes: 14 additions & 0 deletions server/lib/mailer/schemas.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const { validEmail } = require("../../utils/payload");

const mailSchema = {
firstName: { isRequired: false, type: "string" },
lastName: { isRequired: false, type: "string" },
email: { valid: validEmail, isRequired: true, type: "string" },
message: { isRequired: true, type: "string" },
subject: { isRequired: true, type: "string" },
reCaptchaToken: { isRequired: true, type: "string" },
};

module.exports = {
mailSchema,
};
39 changes: 37 additions & 2 deletions server/lib/mailer/service.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
const nodemailer = require('nodemailer')
const templates = require('./email.templates')
const {mailSchema} = require('./schemas')
const {validPayload} = require('../../utils/payload')

function createTransport() {
// Use mailhog in development
Expand Down Expand Up @@ -27,7 +29,7 @@ function createTransport() {

const transport = createTransport()

async function sendMail(templateKey) {
async function sendTemplateMail(templateKey) {
const template = templates[templateKey]
if (!template) {
throw new Error(`Le template ${templateKey} n'existe pas`)
Expand All @@ -42,6 +44,39 @@ async function sendMail(templateKey) {
return true
}

async function checkReCaptcha(reCaptchaToken) {
const response = await fetch(`https://www.google.com/recaptcha/api/siteverify?secret=${process.env.RE_CAPTCHA_SECRET_KEY}&response=${reCaptchaToken}`, {
method: 'POST'
})

const json = await response.json()

if (!json.success) {
throw new Error('Le reCaptcha est invalide')
}

return json.success
}

async function sendFormContactMail(payload) {
const validatedPayload = validPayload(payload, mailSchema)
const {reCaptchaToken, ...emailData } = validatedPayload

await checkReCaptcha(reCaptchaToken)

const contactTemplate = templates.contact(emailData)

const response = await transport.sendMail(contactTemplate)

if (!response) {
throw new Error('Une erreur est survenue lors de l\'envoi de l\'email')
}

return true
}


module.exports = {
sendMail
sendTemplateMail,
sendFormContactMail
}

0 comments on commit 8872ef0

Please sign in to comment.