64 lines
1.5 KiB
JavaScript
64 lines
1.5 KiB
JavaScript
|
import express from 'express'
|
||
|
const nodemailer = require('nodemailer')
|
||
|
const validator = require('validator')
|
||
|
const xssFilters = require('xss-filters')
|
||
|
|
||
|
const app = express()
|
||
|
app.use(express.json())
|
||
|
|
||
|
app.post('/', function (req, res) {
|
||
|
const attributes = ['name', 'email', 'msg']
|
||
|
const sanitizedAttributes = attributes.map(n => validateAndSanitize(n, req.body[n]))
|
||
|
const someInvalid = sanitizedAttributes.some(r => !r)
|
||
|
|
||
|
if (someInvalid) {
|
||
|
return res.status(400).json({ 'error': 'bad request'})
|
||
|
}
|
||
|
|
||
|
sendMail(...sanitizedAttributes)
|
||
|
return res.status(200).json({ 'message': 'success'})
|
||
|
})
|
||
|
|
||
|
export default {
|
||
|
path: '/api/contact',
|
||
|
handler: app,
|
||
|
}
|
||
|
|
||
|
function validateAndSanitize (key, value) {
|
||
|
const rejectFunctions = {
|
||
|
name: v => v.length < 4,
|
||
|
email: v => !validator.isEmail(v),
|
||
|
msg: v => v.length < 1,
|
||
|
}
|
||
|
|
||
|
if (value === undefined || value.length < 1) { return false }
|
||
|
|
||
|
// if object has key and function returns false, return sanitised input.
|
||
|
// Else, return false
|
||
|
return rejectFunctions.hasOwnProperty(key) && !rejectFunctions[key](value) && xssFilters.inHTMLData(value)
|
||
|
}
|
||
|
|
||
|
function sendMail (name, email, msg) {
|
||
|
const transporter = nodemailer.createTransport({
|
||
|
sendmail: true,
|
||
|
newline: 'unix',
|
||
|
path: '/usr/sbin/sendmail'
|
||
|
})
|
||
|
|
||
|
const text =
|
||
|
`Message from ${name}:
|
||
|
|
||
|
${msg}`
|
||
|
|
||
|
const mailJson = {
|
||
|
from: 'server@gabbaell.co.uk',
|
||
|
replyTo: email,
|
||
|
to: 'marcleopold.isnet@gabbaell.co.uk',
|
||
|
subject: 'Contact form message concerning Marc Leopold',
|
||
|
text: text,
|
||
|
}
|
||
|
|
||
|
transporter.sendMail(mailJson)
|
||
|
}
|
||
|
|