This repository was archived by the owner on May 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathindex.js
76 lines (69 loc) · 2.13 KB
/
index.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
'use strict';
var restify = require('restify'),
async = require('async');
module.exports = function(config, elasticsearch) {
var elasticClient;
elasticClient = new elasticsearch.Client({
host: config.ElasticSearchHost,
// log: 'trace',
log: 'error',
// log: 'info;',
apiVersion: config.ElasticSearchVersion
});
return function(req, res, next) {
var cspData;
var timestamp = new Date().toISOString();
async.waterfall([
function cspDataParse(next) {
var userAgent = req.headers['user-agent'];
var referer = req.headers['referer'];
var realIP = req.headers['x-real-ip'] || req.connection.remoteAddress;
var xffor = req.headers['x-forwarded-for'];
if (xffor) {
realIP = xffor;
}
try {
cspData = req.body;
cspData["@timestamp"] = timestamp;
cspData["client-ip"] = realIP;
cspData["user-agent"] = userAgent;
cspData["referer"] = referer;
if (cspData["csp-report"]) {
cspData["parse"] = "valid";
cspData["error"] = "";
}
else {
cspData["parse"] = "error";
cspData["error"] = "csp-report object not found";
}
}
catch (e) {
cspData["parse"] = "error";
cspData["error"] = e;
}
return next(null, cspData);
},
function indexIntoElasticSearch(cspData, next) {
// console.log("Indexing to Elastic data %s", cspData);
// req.log.info(sprintf("Indexing to Elastic data %s", cspData));
var yearMonthDay = timestamp.substr(0, 10).replace(/-/g, '.');
elasticClient.index({
index: config.ElasticSearchIndex + '-' + yearMonthDay,
type: 'csp',
body: cspData
}, function(err) {
if (err) {
return next(new restify.errors.InternalServerError(err, "Error indexing ElasticSearch for cspData"));
}
return next(null);
});
}
], function(err) {
if (err) {
return next(err);
}
res.send(200);
return next();
});
};
};