· 6 years ago · Feb 12, 2019, 10:20 PM
1var express = require('express');
2var router = express.Router();
3var expressValidator = require('express-validator');
4const request = require('request');
5
6var winston = require('../config/winston');
7
8
9
10router.get('/', function(req, res, next) {
11console.log("contact");
12 res.render('contact', {title: "Let's talk!", name: "", email: "", subject: "", content: "", errs: []});
13});
14
15
16router.post('/', function(req, res, next) {
17 //-------------------------------------------------------RECAPTCHA PART---------------------------------------------------------------------
18 //tutorial on: https://codeforgeek.com/2016/03/google-recaptcha-node-js-tutorial/
19 //for the testing phase, the following keys are used:
20 //Site key, in contact.jade file form:
21 //Site key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
22 //secret key, here.
23 //Secret key: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe
24 //these are the development keys and will be changed for your own generated keys on the server. Get your keys at: https://www.google.com/recaptcha/admin
25
26 // g-recaptcha-response is the key that browser will generate upon form submit.
27 // if its blank or null means user has not selected the captcha, so return the error.
28 if(req.body['g-recaptcha-response'] === undefined || req.body['g-recaptcha-response'] === '' || req.body['g-recaptcha-response'] === null) {
29 return res.render('contact', {
30 title: "Let's talk!",
31 name: req.body.name,
32 email: req.body.email,
33 subject: req.body.subject,
34 content: req.body.content,
35 errs: [{msg: "Please check the captcha checkbox."}]
36 });
37 }
38 // Put your secret key here.
39 var secretKey = process.env.CAPTCHA_KEY_PORTFOLIO;
40 // req.connection.remoteAddress will provide IP address of connected user.
41 var verificationUrl = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + req.body['g-recaptcha-response'] + "&remoteip=" + req.connection.remoteAddress;
42 // Hitting GET request to the URL, Google will respond with success or error scenario.
43 request(verificationUrl,function(error,response,body) {
44 body = JSON.parse(body);
45 // Success will be true or false depending upon captcha validation.
46 if(body.success !== undefined && !body.success) {
47 return res.render('contact', {
48 title: "Let's talk!",
49 name: req.body.name,
50 email: req.body.email,
51 subject: req.body.subject,
52 content: req.body.content,
53 errs: [{msg: "Failed captcha verification, try again."}]
54 }); }
55 });
56
57
58 //--------------------------------------FORM VALIDATION PART----------------------------------------------------
59 req.checkBody('name', 'name is required').notEmpty().isLength({min: 3}).escape();
60 req.checkBody('email', 'email must be a valid email format').notEmpty().isEmail().normalizeEmail();
61 req.checkBody('subject', 'subject is required').notEmpty().escape();
62 req.checkBody('content', 'content is required').notEmpty().trim().escape();
63
64 var errors = req.validationErrors();
65 console.log(errors);
66 if(errors) {
67 console.log(errors);
68 return res.render('contact', {
69 title: "Let's talk!",
70 name: req.body.name,
71 email: req.body.email,
72 subject: req.body.subject,
73 content: req.body.content,
74 errs: errors
75 });
76 }
77
78 ///----------------------------------MESSAGE SENDING PART---------------------------------------------------------
79 const msg = {
80 to: 'someemail@something.com',
81 from: {
82 email: req.body.email,
83 name: req.body.name
84 },
85 subject: req.body.subject,
86 text: req.body.content + ' \r\n sent from portfolio site',
87 };
88 var host = req.get('host');
89 winston.info(`host: ${host} sent a message from - ${req.originalUrl} - ${req.method} - ${req.ip}`);
90 winston.info(msg);
91
92 const sgMail = require('@sendgrid/mail');
93
94 //this reads the secret key from the process environment
95 //the key was loaded in there by a .env file in the root folder of the project
96 sgMail.setApiKey(process.env.SENDGRID_API_KEY);
97
98
99
100 sgMail.send(msg, function(err, json) {
101 if (err) {
102 return res.render('contactResponse',
103 {title: 'An error with sending the email has occured. Please try again later or contact me via LinkedIn'});
104 }
105
106 res.render('contactResponse',
107 {title: 'Thank you for your email. I will respond as soon as possible.'});
108
109 });
110
111});
112
113module.exports = router;