-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
477 lines (438 loc) · 17.1 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
const path = require('path');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const MongoDB = require('./mongo.js').MongoDB;
const cors = require('cors');
const utils = require('./utils.js');
const request = require('request');
const MAX_AUTH_ATTEMPTS = 5;
const AUTH_COOLDOWN_TIME_MINUTES = 5;
const ENABLE_AUTH_VALIDATION_ENDPOINT = false;
app.set('port', (process.env.PORT || 8080));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
app.post('/api/auth', function (req, res) {
const username = req.body.username;
const password = req.body.password;
if (!username) {
res.status(400).json({error: 'Username not provided'});
return;
}
if (!password) {
res.status(400).json({error: 'Password not provided'});
return;
}
const hashedPassword = utils.getHash(password);
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
const date = new Date();
date.setMinutes(date.getMinutes() - AUTH_COOLDOWN_TIME_MINUTES);
MongoDB(
'blog',
'logins',
function (collection, closeDBConnection) {
collection.count(
{
ip: ip,
date: {$gt: date},
successful: false
}
).then(
function (attempts) {
console.log('This ip made ' + attempts + ' unsuccessful attempts since ' + date.toTimeString());
if (attempts < MAX_AUTH_ATTEMPTS) {
utils.login(
username,
hashedPassword,
function (token) {
collection.insertOne({
date: new Date(),
username: username,
password: hashedPassword,
ip: ip,
successful: true,
capped: false
},
function () {
closeDBConnection();
});
res.json({secret: token});
},
function () {
collection.insertOne({
date: new Date(),
username: username,
password: hashedPassword,
ip: ip,
successful: false,
capped: false
},
function () {
closeDBConnection();
});
res.status(401).json({error: 'Login failed'});
}
);
}
else {
collection.insertOne({
date: new Date(),
username: username,
password: hashedPassword,
ip: ip,
successful: false,
capped: true
},
function () {
closeDBConnection();
});
res.status(401).json({error: 'Too many unsuccessful attempts attempts'});
}
}
);
},
function () {
res.status(400).json({error: 'Could not get entry: DB connection failed.'});
}
);
});
app.post('/api/validate', function (req, res) {
if (ENABLE_AUTH_VALIDATION_ENDPOINT) {
const secret = req.body.secret;
console.log(secret);
utils.validateToken(
secret,
function () {
res.json({result: 'success'});
},
function () {
res.json({result: 'failure'});
}
);
}
else {
res.json({result: 'failure'});
}
});
app.post('/api/contact', function (req, res) {
const email = req.body.email;
const subject = req.body.subject;
const message = req.body.message;
const validationPt1 = parseInt(req.body.validationPt1);
const validationPt2 = parseInt(req.body.validationPt2);
const validationResult = parseInt(req.body.validationResult);
if (validationPt1 + validationPt2 !== validationResult) {
res.status(400).json({error: 'Validation failed'});
return;
}
if (!email) {
res.status(400).json({error: 'Email not provided'});
return;
}
if (!subject) {
res.status(400).json({error: 'Subject not provided'});
return;
}
if (!message) {
res.status(400).json({error: 'Message not provided'});
return;
}
const emailRegex = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
if (!emailRegex.test(email)) {
res.status(400).json({error: 'Email not valid'});
return;
}
MongoDB(
'contact',
'message',
function (collection, closeDBConnection) {
collection.insertOne({
date: new Date(),
email: email,
subject: subject,
message: message
},
function (error) {
if (error) {
res.status(400).json({error: 'Could not send message: Insert failed.'});
}
else {
res.json({result: 'Message was sent.'});
}
closeDBConnection();
}
);
},
function () {
res.status(400).json({error: 'Could not send message: DB connection failed.'});
}
);
});
app.get('/api/blog', function (req, res) {
MongoDB(
'blog',
'entry',
function (collection, closeDBConnection) {
const cursor = collection.find();
const entries = [];
cursor.sort({date: -1});
cursor.each(
function (error, result) {
if (error) {
res.status(404).json({error: 'Could not find any entries'});
closeDBConnection();
}
else if (!result) {
res.json(entries);
closeDBConnection();
}
else {
entries.push(result);
}
}
);
},
function () {
res.status(400).json({error: 'Could not get entry: DB connection failed.'});
}
);
});
app.get('/api/blog/:id', function (req, res) {
MongoDB(
'blog',
'entry',
function (collection, closeDBConnection) {
collection.findOne(
{id: req.params.id},
function (error, result) {
if (error || !result) {
res.status(404).json({error: 'Could not find an entry with id ' + req.params.id});
}
else {
res.json(result);
}
closeDBConnection();
}
);
},
function () {
res.status(400).json({error: 'Could not get entry: DB connection failed.'});
}
);
});
app.put('/api/blog', function (req, res) {
const auth = req.body.auth;
const isNew = req.body.isNew;
const isIdUpdate = req.body.isIdUpdate;
const date = req.body.date;
const id = req.body.id;
const title = req.body.title;
const body = req.body.body;
const author = req.body.author;
if (!auth) {
res.status(401).json({error: 'Auth failed'});
console.log('Auth failed');
return;
}
if (!date) {
res.status(400).json({error: 'Date invalid'});
console.log('Date invalid');
return;
}
if (!id) {
res.status(400).json({error: 'Id invalid'});
console.log('Id invalid');
return;
}
if (!title) {
res.status(400).json({error: 'Title invalid'});
console.log('Title invalid');
return;
}
if (!body) {
res.status(400).json({error: 'Body invalid'});
console.log('Body invalid');
return;
}
if (!author) {
res.status(400).json({error: 'Author invalid'});
console.log('Author invalid');
return;
}
if (isIdUpdate === 'true') {
res.status(400).json({error: 'Id updates are not supported'});
console.log('Id updates are not supported');
return;
}
//TODO: Backoff for validation
utils.validateToken(
auth,
function () {
MongoDB(
'blog',
'entry',
function (collection, closeDBConnection) {
collection.findOne(
{id: id},
function (error, result) {
if (error || !result) {
console.log('No entry with id; ' + id + ', creating entry');
collection.insertOne(
{
id: id,
date: new Date(date),
title: title,
body: body,
author: author
},
function (error, result) {
if (error) {
console.log('Failed to create entry with id; ' + id);
res.status(400).json({error: 'Could not save blog entry.'});
}
else {
console.log('Entry with id; ' + id + ', created');
res.json({result: 'Blog entry was saved.'});
}
closeDBConnection();
}
);
}
else {
if (isNew === 'false') {
console.log('Entry with id; ' + id + ' exists and will be updated');
collection.updateOne(
{
id: id
},
{
id: id,
date: new Date(date),
title: title,
body: body,
author: author
},
function (error, result) {
if (error) {
console.log('Failed to update entry with id; ' + id);
res.status(400).json({error: 'Could not update blog entry.'});
}
else {
console.log('Entry with id; ' + id + ', updated');
res.json({result: 'Blog entry was updated.'});
}
closeDBConnection();
}
);
}
else {
console.log('Entry with id; ' + id + ' exists, collision');
res.status(400).json({error: 'Blog entry id collision for new entry.'});
closeDBConnection();
}
}
}
);
},
function () {
res.status(400).json({error: 'Could not get entry: DB connection failed.'});
}
);
},
function () {
res.status(401).json({error: 'Auth failed'});
}
);
});
app.delete('/api/blog', function (req, res) {
const auth = req.body.auth;
const id = req.body.id;
if (!auth) {
res.status(401).json({error: 'Auth failed'});
console.log('Auth failed');
return;
}
if (!id) {
res.status(400).json({error: 'Id invalid'});
console.log('Id invalid');
return;
}
//TODO: Backoff
utils.validateToken(
auth,
function () {
MongoDB(
'blog',
'entry',
function (entryCollection, closeEntryDBConnection) {
entryCollection.findOne(
{
id: id
},
function (error, result) {
if (error || !result) {
res.status(404).json({error: 'Could not find an entry with id ' + id});
closeEntryDBConnection();
}
else {
MongoDB(
'blog',
'entry_archive',
function (archiveCollection, closeArhiveDBConnection) {
archiveCollection.insertOne(
result,
function (error) {
if (error) {
res.status(404).json({error: 'Could not copy entry with id ' + id + ' to archive'});
}
else {
entryCollection.remove(
{id: id},
function (error, result) {
if (error || !result) {
res.status(404).json({error: 'Could not remove entry with id ' + id});
}
else {
res.json({result: 'success'});
}
closeEntryDBConnection();
}
)
}
closeArhiveDBConnection();
}
)
},
function () {
res.status(400).json({error: 'Could not get entry archive: DB connection failed.'});
}
);
}
}
)
},
function () {
res.status(400).json({error: 'Could not get entry: DB connection failed.'});
}
);
},
function () {
res.status(401).json({error: 'Auth failed'});
}
);
});
app.post('/api/share', function (req, res) {
const url = req.body.url;
request('http://graph.facebook.com/' + url, function (error, response, body) {
if (!error && response.statusCode == 200) {
res.json(JSON.parse(body));
}
else {
res.status(response.statusCode).json(JSON.parse(body));
}
})
});
app.listen(app.get('port'), function () {
console.log('Server started: http://localhost:' + app.get('port') + '/');
});