-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
119 lines (89 loc) · 2.59 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
const axios = require('axios');
const cors = require('cors');
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const preview = require('./model/preview.json');
const studies = require('./model/studies.json');
const app = express();
const port = process.env.PORT || 8080;
const validateRecaptcha = async (req, token) => {
if (!token) return false;
const url = `https://www.google.com/recaptcha/api/siteverify?secret=${process.env.SECRET_KEY}&response=${token}&remoteip=${req.connection.remoteAddress}`;
try {
const response = await axios.get(url);
const score = JSON.parse(response.data.score);
return score > 0.5;
} catch (err) {
return false;
}
};
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
app.get('/api/v1/studies', (req, res) => {
const studies = preview;
if (!studies) {
res.status(204);
}
res.json(studies);
});
app.get('/api/v1/study/:id', (req, res) => {
const study = studies[req.params.id];
if (!study) {
res.status(204);
}
res.json(study);
});
app.post('/api/v1/send-email', async (req, res) => {
const data = req.body;
const message = 'Please email contact@matthewsullivan.media directly.';
if (!data.userEmail || !data.userMessage || !data.userName) {
res.status(400).send('All fields are required.');
return;
}
const validUser = validateRecaptcha(req, data.token);
if (!validUser) {
res.status(418).send(message);
return;
}
const smtpTransport = nodemailer.createTransport({
service: 'Gmail',
port: 465,
auth: {
user: process.env.MAIL_USER,
pass: process.env.MAIL_PASS,
},
});
const mailOptions = {
from: data.email,
to: 'contact@matthewsullivan.media',
subject: 'Email from www.matthewsullivan.media',
html: `<p>${data.userName}</p>
<p>${data.userEmail}</p>
<p>${data.userMessage}</p>`,
};
smtpTransport.sendMail(mailOptions, (err) => {
if (err) {
res.status(400).send(message);
return;
}
res.send(`Thanks, ${data.userName}. I will be in touch shortly.`);
smtpTransport.close();
});
});
if (
process.env.NODE_ENV === 'production' ||
process.env.NODE_ENV === 'staging'
) {
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', (req, res) => {
res.sendFile(path.resolve('build/index.html'));
});
require('newrelic');
}
app.listen(port, () => {
console.log(`Server Port: ${port}`);
console.log(`Environment: ${process.env.NODE_ENV}`);
});