tracman-server/config/routes/contact.js

93 lines
2.0 KiB
JavaScript
Raw Normal View History

2017-07-04 10:01:11 -06:00
'use strict';
const env = require('../env/env.js'),
request = require('request'),
mw = require('../middleware.js'),
mail = require('../mail.js'),
router = require('express').Router();
module.exports = router
// Display contact form
2017-07-04 10:04:54 -06:00
.get('/', (req,res)=>{
2017-07-04 10:01:11 -06:00
res.render('contact', {active:'contact',
sitekey: env.recaptchaSitekey
});
})
2017-07-04 10:04:54 -06:00
.post('/', (req,res,next)=>{
2017-07-04 11:14:28 -06:00
// Check email
if (req.body.email==='') {
req.flash('warning', `You need to enter an email address. `);
res.redirect('/contact');
}
else if (!mw.validateEmail(req.body.email)) {
req.flash('warning', `<u>${req.body.email}</u> is not a valid email address. `);
res.redirect('/contact');
}
// Check for message
else if (req.body.message==='') {
req.flash('warning', `You need to enter a message. `);
res.redirect('/contact');
}
// Passed validations
else {
// Confirm captcha
request.post( 'https://www.google.com/recaptcha/api/siteverify', {form:{
secret: env.recaptchaSecret,
response: req.body['g-recaptcha-response'],
remoteip: req.ip
}}, (err, response, body)=>{
2017-07-04 10:01:11 -06:00
2017-07-04 11:14:28 -06:00
// Check for errors
if (err){
mw.throwErr(err,req);
res.redirect('/contact');
2017-07-04 10:01:11 -06:00
}
2017-07-04 11:14:28 -06:00
if (response.statusCode!==200) {
let err = new Error('Bad response from reCaptcha service');
2017-07-04 10:01:11 -06:00
mw.throwErr(err,req);
res.redirect('/contact');
}
2017-07-04 10:04:54 -06:00
2017-07-04 11:14:28 -06:00
// No errors
else {
// Captcha failed
if (!JSON.parse(body).success){
let err = new Error('Failed reCaptcha');
mw.throwErr(err,req);
res.redirect('/contact');
}
// Captcha succeeded
else {
mail.send({
from: `${req.body.name} <${req.body.email}>`,
to: `Tracman Contact <contact@tracman.org>`,
subject: req.body.subject||'A message',
text: req.body.message
})
.then(()=>{
req.flash('success', `Your message has been sent. `);
res.redirect(req.session.next || '/');
})
.catch((err)=>{
mw.throwErr(err,req);
res.redirect('/contact');
});
}
}
});
2017-07-04 10:01:11 -06:00
2017-07-04 11:14:28 -06:00
}
2017-07-04 10:04:54 -06:00
});