-
Notifications
You must be signed in to change notification settings - Fork 1
/
handlers.js
839 lines (774 loc) · 23.9 KB
/
handlers.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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
/****************************************************************
Handlers callback a status code & possibly a payload object
****************************************************************/
const __database = require('../config').database.database;
const _db = require('../' + __database + '/db');
const config = require('../config').handlers;
const _is = require('../lib/helpers').is;
const _hash = require('../lib/helpers').hash;
const _createRandomString = require('../lib/helpers').createRandomString;
const {getTemplate, addUniversalTemplates, getStaticAsset} = require('../lib/serve_contents');
const handlers = {};
/////////////////////////////////////////////////////////////////
/****************************************************************
html Handler
****************************************************************/
/////////////////////////////////////////////////////////////////
handlers.index = (data, cb) => {
if (data.method === 'get') {
let templateData = {
'head.title' : 'Home',
'head.description' : 'Uptime monitoring site',
'body.title' : 'Hello World!',
'body.class' :'index'
};
getTemplate('index', templateData,(err, str) => {
if (!err && str) {
addUniversalTemplates(str, templateData, (err, str) => {
if (!err && str) {
cb(200, str, 'html');
} else {
cb(500,undefined,'html');
}
});
} else {
cb(500,undefined,'html');
}
});
} else {
cb(405, undefined, 'html');
}
};
handlers.accountCreate = (data, cb) => {
if (data.method === 'get') {
let templateData = {
'head.title' : 'Create an account',
'head.description' : 'Sign up is easy and only takes a few second.',
'body.class' :'accountCreate'
};
getTemplate('accountCreate', templateData,(err, str) => {
if (!err && str) {
addUniversalTemplates(str, templateData, (err, str) => {
if (!err && str) {
cb(200, str, 'html');
} else {
cb(500,undefined,'html');
}
});
} else {
cb(500,undefined,'html');
}
});
} else {
cb(405, undefined, 'html');
}
};
handlers.sessionCreate = (data, cb) => {
if (data.method === 'get') {
let templateData = {
'head.title' : 'Login',
'head.description' : 'Please enter your credentials.',
'body.class' :'sessionCreate'
};
getTemplate('sessionCreate', templateData,(err, str) => {
if (!err && str) {
addUniversalTemplates(str, templateData, (err, str) => {
if (!err && str) {
cb(200, str, 'html');
} else {
cb(500,undefined,'html');
}
});
} else {
cb(500,undefined,'html');
}
});
} else {
cb(405, undefined, 'html');
}
};
handlers.sessionDeleted = (data, cb) => {
if (data.method === 'get') {
let templateData = {
'head.title' : 'Logged Out',
'head.description' : 'You have been logged out.',
'body.class' :'sessionDeleted'
};
getTemplate('sessionDeleted', templateData,(err, str) => {
if (!err && str) {
addUniversalTemplates(str, templateData, (err, str) => {
if (!err && str) {
cb(200, str, 'html');
} else {
cb(500,undefined,'html');
}
});
} else {
cb(500,undefined,'html');
}
});
} else {
cb(405, undefined, 'html');
}
};
handlers.accountEdit = (data, cb) => {
if (data.method === 'get') {
let templateData = {
'head.title' : 'Account Settings',
'body.class' :'accountEdit'
};
getTemplate('accountEdit', templateData,(err, str) => {
if (!err && str) {
addUniversalTemplates(str, templateData, (err, str) => {
if (!err && str) {
cb(200, str, 'html');
} else {
cb(500,undefined,'html');
}
});
} else {
cb(500,undefined,'html');
}
});
} else {
cb(405, undefined, 'html');
}
};
handlers.accountDeleted = (data, cb) => {
if (data.method === 'get') {
let templateData = {
'head.title' : 'Account Deleted',
'head.description' : 'Your account has been deleted.',
'body.class' :'accountDeleted'
};
getTemplate('accountDeleted', templateData,(err, str) => {
if (!err && str) {
addUniversalTemplates(str, templateData, (err, str) => {
if (!err && str) {
cb(200, str, 'html');
} else {
cb(500,undefined,'html');
}
});
} else {
cb(500,undefined,'html');
}
});
} else {
cb(405, undefined, 'html');
}
};
handlers.checksCreate = (data, cb) => {
if (data.method === 'get') {
let templateData = {
'head.title' : 'Create a New Check',
'body.class' :'checksCreate'
};
getTemplate('checksCreate', templateData,(err, str) => {
if (!err && str) {
addUniversalTemplates(str, templateData, (err, str) => {
if (!err && str) {
cb(200, str, 'html');
} else {
cb(500,undefined,'html');
}
});
} else {
cb(500,undefined,'html');
}
});
} else {
cb(405, undefined, 'html');
}
};
handlers.checksList = (data, cb) => {
if (data.method === 'get') {
let templateData = {
'head.title' : 'Dashboard',
'body.class' :'checksList'
};
getTemplate('checksList', templateData,(err, str) => {
if (!err && str) {
addUniversalTemplates(str, templateData, (err, str) => {
if (!err && str) {
cb(200, str, 'html');
} else {
cb(500,undefined,'html');
}
});
} else {
cb(500,undefined,'html');
}
});
} else {
cb(405, undefined, 'html');
}
};
handlers.checksEdit = (data, cb) => {
if (data.method === 'get') {
let templateData = {
'head.title' : 'Check Details',
'body.class' :'checksEdit'
};
getTemplate('checksEdit', templateData,(err, str) => {
if (!err && str) {
addUniversalTemplates(str, templateData, (err, str) => {
if (!err && str) {
cb(200, str, 'html');
} else {
cb(500,undefined,'html');
}
});
} else {
cb(500,undefined,'html');
}
});
} else {
cb(405, undefined, 'html');
}
};
handlers.favicon = (data, cb) => {
if (data.method === 'get') {
getStaticAsset('favicon.ico', (err, data) => {
if (!err && data) {
cb(200, data, 'ico');
} else {
cb(500,undefined,'html');
}
});
} else {
cb(405, undefined, 'html');
}
};
handlers.public = (data, cb) => {
if (data.method === 'get') {
const assetName = data.path.replace('public/', '').trim();
if (assetName.length > 0) {
getStaticAsset(assetName, (err, data) => {
if (!err && data) {
const contentType = assetName.split('.').pop().length > 1 ? assetName.split('.').pop() : 'plain';
cb(200, data, contentType);
} else {
cb(404,undefined,'html');
}
});
} else {
cb(404);
}
} else {
cb(405, undefined, 'html');
}
};
/////////////////////////////////////////////////////////////////
/****************************************************************
JSON Handler
****************************************************************/
/////////////////////////////////////////////////////////////////
/****************************************************************
users Handler
****************************************************************/
handlers.users = (data, cb) => {
const methods = ['post', 'get', 'put', 'delete'];
if (methods.indexOf(data.method) > -1) {
handlers._users[data.method](data, cb);
} else {
cb(405);
}
};
handlers._users = {};
// Users - post
// Required data: firstName, lastName, email, password($config.minPasswordLength characters, no leading or trailling whitespaces), tosAgreement
// Optional data: none
handlers._users.post = (data, cb) => {
const firstName = _is.str(data.payload.firstName);
const lastName = _is.str(data.payload.lastName);
const email = _is.email(data.payload.email);
const password = _is.str(data.payload.password, config.minPasswordLength);
const tosAgreement = typeof(data.payload.tosAgreement) === 'boolean' && data.payload.tosAgreement === true ? true : false;
if (firstName && lastName && email && password && tosAgreement) {
// Make sure the user doesn't exist already
_db.read('users', email, (err, data) => {
if (err || !data.length) {
// Hash the password
const hashedPassword = _hash(password);
if (hashedPassword) {
const userObject = {
firstName,
lastName,
email,
password: hashedPassword,
tosAgreement: true
};
_db.create('users', email, userObject, (err) => {
if (!err) {
cb(200);
} else {
cb(500, {'Error' : 'Could not create the new user.'});
}
});
} else {
cb(500, {'Error' : 'Could not hash the password.'});
}
} else {
cb(400,{'Error': 'A user with that email already exists.'});
}
});
} else {
cb(400, {'Error' : 'Missing or invalid fields.'});
}
};
// Users - get
// Required data: email, token
// Optional data: none
handlers._users.get = (data, cb) => {
const email = _is.email(data.query.email);
const token = _is.token(data.headers.token);
if (email && token) {
handlers._tokens.verifyToken(token, email, (tokenIsValid) => {
if (tokenIsValid) {
_db.read('users', email, (err, resp) => {
if (!err && resp) {
delete resp.password;
cb(200, resp);
} else {
cb(404);
}
});
} else {
cb(403, {"Error":"Expired or invalid session."});
}
});
} else {
cb(400, {"Error" : "Missing or invalid fields."});
}
};
// Users - put
// Required data: email, at least one optional data, token
// Optional data: firstName, lastName, password
handlers._users.put = (data, cb) => {
const email = _is.email(data.payload.email);
const firstName = _is.str(data.payload.firstName);
const lastName = _is.str(data.payload.lastName);
const password = _is.str(data.payload.password, config.minPasswordLength);
const token = _is.token(data.headers.token);
if (email && token && (firstName || lastName || password)) {
handlers._tokens.verifyToken(token, email, (tokenIsValid) => {
if (tokenIsValid) {
_db.read('users', email, (err, userData) => {
if (!err && userData) {
if (firstName) {
userData.firstName = firstName;
}
if (lastName) {
userData.lastName = lastName;
}
if (password) {
userData.password = _hash(password);
}
_db.update('users', email, userData, (err) => {
if (!err) {
cb(200);
} else {
cb(500, {'Error' : 'Could not update the user.'});
}
});
} else {
cb(404, {'Error': 'The user was not found.'});
}
});
} else {
cb(403, {"Error":"Expired or invalid session."});
}
});
} else {
cb(400, {'Error' : 'Missing or invalid fields.'});
}
};
// Users - delete
// Required data: email, token
// Optional data: none
// @TODO delete any other data associated with the user
handlers._users.delete = (data, cb) => {
const email = _is.email(data.query.email);
const token = _is.token(data.headers.token);
if (email && token) {
handlers._tokens.verifyToken(token, email, (tokenIsValid) => {
if (tokenIsValid) {
_db.read('users', email, (err) => {
if (!err) {
_db.delete('users', email, (err) => {
if (!err) {
cb(200);
} else {
cb(500, {"Error" : "Could not delete the specified user."});
}
});
} else {
cb(404, {"Error" : "Could not find the specified user."});
}
});
} else {
cb(403, {"Error":"Expired or invalid session."});
}
});
} else {
cb(400, {"Error" : "Missing or invalid fields."});
}
};
/****************************************************************
tokens Handler
****************************************************************/
handlers.tokens = (data, cb) => {
const methods = ['post', 'get', 'put', 'delete'];
if (methods.indexOf(data.method) > -1) {
handlers._tokens[data.method](data, cb);
} else {
cb(405);
}
};
handlers._tokens = {};
// Tokens - post
// Required data: email, password
// Optional data: none
handlers._tokens.post = (data, cb) => {
const email = _is.email(data.payload.email);
const password = _is.str(data.payload.password);
if (email && password) {
// Find the user
_db.read('users', email, (err, userData) => {
if (!err && userData) {
// Hash the password
const hashedPassword = _hash(password);
if (hashedPassword === userData.password) {
const tokenId = _createRandomString(config.tokenIDLength);
const expires = Date.now() + 1000 * 60 * 60; //+1 hour
const tokenObject = {
email,
id: tokenId,
expires
};
_db.create('tokens', tokenId, tokenObject, (err) => {
if (!err) {
cb(200, tokenObject);
} else {
cb(500, {'Error' : 'Could not create the new token.'});
}
});
} else {
cb(400, {'Error' : 'Incorrect password.'});
}
} else {
cb(400,{'Error': 'A user with that email was not found.'});
}
});
} else {
cb(400, {'Error' : 'Missing or invalid fields.'});
}
};
// Tokens - get
// Required data: id
// Optional data: none
handlers._tokens.get = (data, cb) => {
const id = _is.token(data.query.id);
if (id) {
_db.read('tokens', id, (err, tokenData) => {
if (!err && tokenData) {
cb(200, tokenData);
} else {
cb(404);
}
});
} else {
cb(400, {"Error" : "Missing or invalid fields."});
}
};
// Tokens - put
// Required data: id, extend
// Optional data: none
handlers._tokens.put = (data, cb) => {
const id = _is.token(data.payload.id);
const extend = typeof(data.payload.extend) === 'boolean' && data.payload.extend === true ? true : false;
if (extend) {
_db.read('tokens', id, (err, tokenData) => {
if (!err && tokenData) {
if (tokenData.expires > Date.now()) {
tokenData.expires = Date.now() + 1000 * 60 * 60;
_db.update('tokens', id, tokenData, (err) => {
if (!err) {
cb(200);
} else {
cb(500, {'Error' : 'Could not update the token\'s expiration.'});
}
});
} else {
_db.delete('tokens', id, () => {
cb(401, {'Error' : 'The token has already expired!'});
});
}
} else {
cb(404, {'Error': 'Specified token does not exist.'});
}
});
} else {
cb(400, {'Error' : 'Missing or invalid fields.'});
}
};
// Tokens - delete
// Required data: id
// Optional data: none
handlers._tokens.delete = (data, cb) => {
const id = _is.token(data.query.id);
if (id) {
_db.read('tokens', id, (err) => {
if (!err) {
_db.delete('tokens', id, (err) => {
if (!err) {
cb(200);
} else {
cb(500, {"Error" : "Could not delete the specified token."});
}
});
} else {
cb(404, {"Error" : "Could not find the specified token."});
}
});
} else {
cb(400, {"Error" : "Missing or invalid fields."});
}
};
// Tokens - session validation
// Required data: id, email, cb
// Optional data: none
handlers._tokens.verifyToken = (token, email, cb) => {
token = _is.token(token);
email = _is.email(email);
if (token && email) {
_db.read('tokens', token, (err, tokenData) => {
if (!err && tokenData) {
if (tokenData.expires > Date.now() && tokenData.email === email) {
cb(true);
} else {
cb(false);
}
} else {
cb(false);
}
});
} else {
cb(false);
}
};
/****************************************************************
Checks services
****************************************************************/
handlers.checks = (data, cb) => {
const methods = ['post', 'get', 'put', 'delete'];
if (methods.indexOf(data.method) > -1) {
handlers._checks[data.method](data, cb);
} else {
cb(405);
}
};
handlers._checks = {};
// Checks - post
// Required data: protocol, url, method, successCodes, timeoutSeconds, token
// Optional data: none
handlers._checks.post = (data, cb) => {
const protocol = _is.protocol(data.payload.protocol);
const url = _is.str(data.payload.url);
const method = _is.method(data.payload.method);
const successCodes = _is.successCodes(data.payload.successCodes);
const timeoutSeconds = _is.timeoutSeconds(data.payload.timeoutSeconds);
const token = _is.token(data.headers.token);
if (protocol && url && method && successCodes && timeoutSeconds && token) {
_db.read('tokens', token, (err, tokenData) => {
if (!err && tokenData) {
const email = tokenData.email;
_db.read('users', email, (err, userData) => {
if (!err && userData) {
// get user checks & ensure max has not exceeded
const userChecks = typeof(userData.checks) === 'object' && userData.checks instanceof Array ? userData.checks : [];
if (userChecks.length < config.maxChecksLimit) {
const checkId = _createRandomString(config.checkIdLength);
const checkObject = {
id: checkId,
email: userData.email,
protocol,
url,
method,
successCodes,
timeoutSeconds
};
_db.create('checks', checkId, checkObject, (err) => {
if (!err) {
userChecks.push(checkId);
userData.checks = userChecks;
_db.update('users', userData.email, userData, (err) => {
if (!err) {
cb(200, checkObject);
} else {
cb(500, {"Error":"Could not update the user with the new check."});
}
});
} else {
cb(500, {"Error":"Could not create the new check."});
}
});
} else {
cb(400, {"Error":`The user already has the maximum number of checks (${config.maxChecksLimit}).`});
}
} else {
cb(500, {"Error":"User was not found."});
}
});
} else {
cb(500, {"Error" : "Session was not found."});
}
});
} else {
cb(400, {"Error" : "Missing or invalid inputs."});
}
};
// Checks - get
// Required data: checkId, token
// Optional data: none
handlers._checks.get = (data, cb) => {
const id = _is.checkId(data.query.id);
if (id) {
_db.read('checks', id, (err, checkData) => {
if (!err && checkData) {
const token = _is.token(data.headers.token);
handlers._tokens.verifyToken(token, checkData.email, (tokenIsValid) => {
if (tokenIsValid) {
cb(200, checkData);
} else {
cb(403, {"Error" : "Unauthorized."});
}
});
} else {
cb(400, {"Error" : "Could not find the check."});
}
});
} else {
cb(400, {"Error" : "Invalid checkId."});
}
};
// Checks - put
// Required data: checkId, an optional parameter, token
// Optional data: protocol, url, method, successCodes, timeoutSeconds
handlers._checks.put = (data, cb) => {
const checkId = _is.checkId(data.payload.id);
const protocol = _is.protocol(data.payload.protocol);
const url = _is.str(data.payload.url);
const method = _is.method(data.payload.method);
const successCodes = _is.successCodes(data.payload.successCodes);
const timeoutSeconds = _is.timeoutSeconds(data.payload.timeoutSeconds);
const token = _is.token(data.headers.token);
if (checkId) {
if (protocol || url || method || successCodes || timeoutSeconds) {
_db.read('checks', checkId, (err, checkData) => {
if (!err && checkData) {
handlers._tokens.verifyToken(token, checkData.email, (tokenIsValid) => {
if (tokenIsValid) {
if (protocol) {
checkData.protocol = protocol;
}
if (url) {
checkData.url = url;
}
if (method) {
checkData.method = method;
}
if (successCodes) {
checkData.successCodes = successCodes;
}
if (timeoutSeconds) {
checkData.timeoutSeconds = timeoutSeconds;
}
_db.update('checks', checkId, checkData, (err) => {
if (!err) {
cb(200, checkData);
} else {
cb(500, {"Error" : "Could not update the check."});
}
});
} else {
cb(403, {"Error" : "Unauthorized."});
}
});
} else {
cb(400, {"Error" : "Could not find the check."});
}
});
} else {
cb(400, {"Error" : "Missing fields to update."});
}
} else {
cb(400, {"Error" : "Invalid checkId."});
}
};
// Checks - delete
// Required data: id
// Optional data: none
handlers._checks.delete = (data, cb) => {
const checkId = _is.checkId(data.query.id);
if (checkId) {
_db.read('checks', checkId, (err, checkData) => {
if (!err && checkData) {
const token = _is.token(data.headers.token);
handlers._tokens.verifyToken(token, checkData.email, (tokenIsValid) => {
if (tokenIsValid) {
_db.delete('checks', checkId, (err) => {
if (!err) {
_db.read('users', checkData.email, (err, userData) => {
if (!err && userData) {
if (userData.checks) {
const checkPosition = userData.checks.indexOf(checkId);
if (checkPosition > -1) {
userData.checks.splice(checkPosition, 1);
_db.update('users', checkData.email, userData, (err) => {
if (!err) {
cb(200);
} else {
cb(500, {"Error" : "Could not update the user's object."});
}
});
} else {
cb(200);
}
} else {
cb(200);
}
} else {
cb(500, {"Error" : "Could not clear the user's check."});
}
});
} else {
cb(500, {"Error" : "Could not delete the check."});
}
});
} else {
cb(403);
}
});
} else {
cb(400, {"Error" : "Could not find the specified check."});
}
});
} else {
cb(400, {"Error" : "Missing or invalid fields."});
}
};
/****************************************************************
PING Handler
****************************************************************/
handlers.ping = (data, cb) => {
cb(200);
};
/****************************************************************
Not Found Handler
****************************************************************/
handlers.notFound = (data, cb) => {
cb(404);
};
module.exports = handlers;