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)=>{
|
|
|
|
|
|
|
|
// 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 10:04:54 -06:00
|
|
|
// Check for errors
|
|
|
|
if (err){
|
|
|
|
mw.throwErr(err,req);
|
|
|
|
res.redirect('/contact');
|
|
|
|
}
|
|
|
|
if (response.statusCode!==200) {
|
|
|
|
let err = new Error('Bad response from reCaptcha service');
|
|
|
|
mw.throwErr(err,req);
|
|
|
|
res.redirect('/contact');
|
|
|
|
}
|
|
|
|
else {
|
2017-07-04 10:01:11 -06:00
|
|
|
|
2017-07-04 10:04:54 -06:00
|
|
|
// Captcha succeeded
|
|
|
|
if (JSON.parse(body).success){
|
|
|
|
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 10:04:54 -06:00
|
|
|
|
|
|
|
// Captcha failed
|
|
|
|
else {
|
|
|
|
let err = new Error('Failed reCaptcha');
|
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 10:01:11 -06:00
|
|
|
}
|
|
|
|
|
2017-07-04 10:04:54 -06:00
|
|
|
});
|
|
|
|
|
|
|
|
});
|