2021-11-24 11:02:52 -07:00
|
|
|
'use strict'
|
|
|
|
|
2021-11-24 11:19:34 -07:00
|
|
|
require('dotenv').config()
|
2021-11-24 12:20:12 -07:00
|
|
|
const express = require('express')
|
2021-11-24 17:32:01 -07:00
|
|
|
const app = express()
|
2021-11-24 11:19:34 -07:00
|
|
|
const {verify} = require('hcaptcha')
|
|
|
|
|
2021-11-24 12:37:26 -07:00
|
|
|
const mailer = require('nodemailer').createTransport({
|
|
|
|
host: process.env.MAIL_SERVER,
|
|
|
|
port: 587,
|
|
|
|
secure: false, // STARTTLS LATER
|
|
|
|
auth: {
|
|
|
|
user: process.env.MAIL_USER,
|
|
|
|
pass: process.env.MAIL_PASS,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
2021-11-24 17:32:01 -07:00
|
|
|
app.use(express.json())
|
|
|
|
app.get('/', (req, res) => {
|
2021-11-24 13:52:04 -07:00
|
|
|
res.send('Hello')
|
2021-11-24 14:01:47 -07:00
|
|
|
})
|
2021-11-24 17:32:01 -07:00
|
|
|
app.post('/', async (req, res) => {
|
2021-11-24 17:25:56 -07:00
|
|
|
|
|
|
|
console.log(`Received POST`)
|
|
|
|
console.log(req.body)
|
2021-11-24 11:19:34 -07:00
|
|
|
// Check token
|
|
|
|
try {
|
|
|
|
const data = await verify(process.env.HCAPTCHA_SECRET, req.body['token'])
|
2021-11-24 13:57:54 -07:00
|
|
|
} catch (err) {
|
|
|
|
console.error(`Failed to check hcaptcha\n${err}`)
|
|
|
|
return res.sendStatus(500)
|
|
|
|
}
|
2021-11-24 12:37:26 -07:00
|
|
|
if (data.success === true) {
|
|
|
|
|
|
|
|
let from
|
|
|
|
if (req.body['name'] && req.body['email']) from = `${req.body['name']} <${req.body['email']}>`
|
|
|
|
else if (req.body['name']) from = req.body['name']
|
|
|
|
else if (req.body['email']) from = req.body['email']
|
|
|
|
else from = 'Anonymous'
|
2021-11-24 11:02:52 -07:00
|
|
|
|
2021-11-24 12:37:26 -07:00
|
|
|
// Send email
|
|
|
|
try {
|
2021-11-24 13:57:54 -07:00
|
|
|
console.log(`Sending email from ${from}...`)
|
2021-11-24 12:37:26 -07:00
|
|
|
await mailer.sendMail({
|
|
|
|
from: from,
|
|
|
|
to: process.env.MAIL_TO,
|
|
|
|
subject: req.body['subj'],
|
|
|
|
text: req.body['msg'],
|
|
|
|
})
|
2021-11-24 13:57:54 -07:00
|
|
|
} catch (err) {
|
|
|
|
return res.sendStatus(500)
|
|
|
|
console.error(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// hcaptcha failed
|
|
|
|
} else return res.sendStatus(403)
|
2021-11-24 17:32:01 -07:00
|
|
|
})
|
|
|
|
|
|
|
|
app.listen(process.env.PORT, () => {
|
2021-11-24 13:57:54 -07:00
|
|
|
console.log(`API listening on ${process.env.PORT}`)
|
2021-11-24 11:02:52 -07:00
|
|
|
})
|