-
Notifications
You must be signed in to change notification settings - Fork 1
/
spam-filter.js
87 lines (77 loc) · 1.92 KB
/
spam-filter.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
// Simple Contact Form Spam Filter
exports.handler = function(event, context, callback) {
// 1. Parse the form
try {
// NB: Using `var` since `const` is block-scoped
var body = JSON.parse(event.body)
}
catch (e) {
console.log(event)
callback(
e.message,
{
statusCode: 400,
body: `[ERROR] Invalid JSON - ${e.message}`
}
)
return
}
// 2. Filter
if ( !body.data.name ||
!body.data.message )
{
const errorMessage = '[SPAM DETECTED] Required fields not defined.'
console.log(errorMessage)
callback(
null,
{
statusCode: 200,
body: errorMessage
}
)
return
}
// 3. Forward data to webhook (ie, send email)
const URL = require('url')
const https = require('https')
// TODO: Lazy testing. Replace with `dotenv`
// const webhook_url = URL.parse('https://chrisjmears.com/test')
const webhook_url = URL.parse(process.env.ZAPIER_CONTACT_FORM_WEBHOOK)
const options = {
hostname: webhook_url.hostname,
path: webhook_url.pathname,
method: 'POST',
headers: { 'Content-Type': 'application/json' }
}
// Set up webhook request
const req = https.request(options, function(res) {
console.log(`Status: ${res.statusCode}`);
console.log(`Headers: ${JSON.stringify(res.headers)}`)
res.setEncoding('utf8');
// Log data
res.on('data', function (body) {
console.log(`Body: ${body}`);
})
})
// Handle webhook request error
req.on('error', function(e) {
const errorMessage = `[ERROR] Problem with request: ${e.message}`
console.log(errorMessage)
callback(
e.message,
{
statusCode: 400,
body: errorMessage
}
)
})
// Send form data to webhook request and end request
req.end(JSON.stringify(body))
callback(
null,
{
statusCode: 200,
body: `[SUCCESS] Sending webhook to ${webhook_url.format()}`
}
)
}