-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
197 lines (173 loc) · 5.22 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
const http = require('http');
const fs = require('fs');
const path = require('path');
const {MongoClient} = require("mongodb");
const port = +(process.env.PORT || 4538);
const downloadFolder = process.env.DOWNLOAD_FOLDER || './download';
const mongodbUri = process.env.MONGODB_URI || "mongodb://eve-database:27017";
// SETTING UP DB
const dbConfig = {};
async function settingUpDB() {
// Create a new MongoClient
dbConfig.client = new MongoClient(mongodbUri);
async function run() {
await dbConfig.client.connect();
console.log("Connected successfully to db server");
}
dbConfig.saveAnomalies = async (anomalies) => {
const database = dbConfig.client.db('eve');
const anomalyCollection = database.collection('anomaly');
for (let anomaly of anomalies) {
const query = {id: anomaly.id, system_id: anomaly.system_id};
const it = await anomalyCollection.findOne(query);
if (it) {
await anomalyCollection.updateOne(query, {$set: anomaly});
} else {
await anomalyCollection.insertOne(anomaly);
}
}
};
dbConfig.loadAnomalies = async () => {
const database = dbConfig.client.db('eve');
const anomalyCollection = database.collection('anomaly');
return anomalyCollection.find().toArray();
};
dbConfig.removeAnomalies = async (anomalies) => {
const database = dbConfig.client.db('eve');
const anomalyCollection = database.collection('anomaly');
for (let anomaly of anomalies) {
await anomalyCollection.deleteOne({id: anomaly.id, system_id: anomaly.system_id});
}
};
return run();
}
// CORS
function injectCORS(res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
res.setHeader('Access-Control-Allow-Headers', '*');
}
// login code redirection code
function loginController(req, res) {
console.log('new authentication at:', new Date());
res.writeHead(200);
res.end('authenticated');
}
function linksController(req, res) {
const links = fs.readFileSync(path.join(__dirname, 'links.json'), {encoding: "utf8"});
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(links, 'utf-8');
}
function dbVersionController(req, res) {
const result = fs.readdirSync(downloadFolder).filter(function (file) {
return file.endsWith('.sqlite') || file.endsWith('.db');
});
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(result), 'utf-8');
}
// download files
function downloadDBController(req, res) {
const fileName = req.url.replace(/^\/download\/db\//, '');
const filePath = path.join(downloadFolder, fileName);
res.writeHead(200, {'Content-Type': 'application/x-sqlite3'});
const fileStream = fs.createReadStream(filePath);
fileStream.on('data', (chunk) => res.write(chunk));
fileStream.on('close', () => {
res.end('The file was successfully downloaded\n');
});
fileStream.on('error', () => {
res.statusCode = 500;
res.end('An error occurred with the downloadable file\n');
});
}
// ANOMALIES
function anomalies(req, res) {
switch (req.method) {
case 'GET':
loadAnomalies(req, res);
return;
case 'POST':
readBodyFromRequest(req).then((body) => {
req.body = body;
if (req.url === '/anomalies') {
saveAnomalies(req, res);
} else {
removeAnomalies(req, res);
}
});
break;
}
}
async function readBodyFromRequest(req) {
let body = '';
return new Promise((resolve) => {
req.on('data', chunk => body += chunk);
req.on('end', chunk => {
try {
const jsonBody = JSON.parse(body);
resolve(jsonBody);
} catch (e) {
resolve(body);
}
});
});
}
function saveAnomalies(req, res) {
dbConfig.saveAnomalies(req.body).then(() => {
res.statusCode = 200;
res.end('Anomalies saved\n');
}).catch(err => {
console.error(err);
res.statusCode = 500;
res.end('Error saving anomalies in db\n');
});
}
function removeAnomalies(req, res) {
dbConfig.removeAnomalies(req.body).then(() => {
res.statusCode = 200;
res.end('Anomalies removed\n');
}).catch(err => {
console.error(err);
res.statusCode = 500;
res.end('Error removing anomalies from db\n');
});
}
function loadAnomalies(req, res) {
dbConfig.loadAnomalies().then((anomalies) => {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(anomalies), 'utf-8');
}).catch(err => {
console.error(err);
res.statusCode = 500;
res.end('Error to get anomalies from db\n');
});
}
const requestListener = function (req, res) {
injectCORS(res);
console.log(req.url)
if (req.url.startsWith('/anomalies')) {
anomalies(req, res);
return;
}
if (req.url.startsWith('/download/db')) {
downloadDBController(req, res);
return;
}
if (req.url === '/db-versions') {
dbVersionController(req, res);
return;
}
if (req.url === '/links') {
linksController(req, res);
return;
}
loginController(req, res);
}
const server = http.createServer(requestListener);
settingUpDB()
.then(() => {
console.log('Server is running');
return server.listen(port);
})
.catch(console.dir);