forked from Countly/countly-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
1519 lines (1382 loc) · 55.2 KB
/
app.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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Set process name
process.title = "countly: dashboard node " + process.argv[1];
var versionInfo = require('./version.info'),
COUNTLY_VERSION = versionInfo.version,
COUNTLY_COMPANY = versionInfo.company || '',
COUNTLY_TYPE = versionInfo.type,
COUNTLY_PAGE = versionInfo.page = (!versionInfo.title) ? "http://count.ly" : null,
COUNTLY_NAME = versionInfo.title = versionInfo.title || "Countly",
COUNTLY_DOCUMENTATION_LINK = (typeof versionInfo.documentationLink === "undefined") ? true : (typeof versionInfo.documentationLink === "string") ? versionInfo.documentationLink : (typeof versionInfo.documentationLink === "boolean") ? versionInfo.documentationLink : true,
COUNTLY_FEEDBACK_LINK = (typeof versionInfo.feedbackLink === "undefined") ? true : (typeof versionInfo.feedbackLink === "string") ? versionInfo.feedbackLink : (typeof versionInfo.feedbackLink === "boolean") ? versionInfo.feedbackLink : true,
COUNTLY_HELPCENTER_LINK = (typeof versionInfo.helpCenterLink === "undefined") ? true : (typeof versionInfo.helpCenterLink === "string") ? versionInfo.helpCenterLink : (typeof versionInfo.helpCenterLink === "boolean") ? versionInfo.helpCenterLink : true,
COUNTLY_FEATUREREQUEST_LINK = (typeof versionInfo.featureRequestLink === "undefined") ? true : (typeof versionInfo.featureRequestLink === "string") ? versionInfo.featureRequestLink : (typeof versionInfo.featureRequestLink === "boolean") ? versionInfo.featureRequestLink : true,
express = require('express'),
SkinStore = require('connect-mongoskin'),
expose = require('./libs/express-expose.js'),
dollarDefender = require('./libs/dollar-defender.js')({
message: "Dollar sign is not allowed in keys",
hook: function(req) {
console.log("Possible Dollar sign injection", req.originalUrl, req.query, req.params, req.body);
}
}),
crypto = require('crypto'),
fs = require('fs'),
path = require('path'),
jimp = require('jimp'),
request = require('request'),
flash = require('connect-flash'),
cookieParser = require('cookie-parser'),
formidable = require('formidable'),
session = require('express-session'),
methodOverride = require('method-override'),
csrf = require('csurf')(),
errorhandler = require('errorhandler'),
basicAuth = require('basic-auth'),
bodyParser = require('body-parser'),
_ = require('underscore'),
countlyMail = require('../../api/parts/mgmt/mail.js'),
// countlyStats = require('../../api/parts/data/stats.js'),
countlyFs = require('../../api/utils/countlyFs.js'),
common = require('../../api/utils/common.js'),
preventBruteforce = require('./libs/preventBruteforce.js'),
plugins = require('../../plugins/pluginManager.js'),
countlyConfig = require('./config', 'dont-enclose'),
log = require('../../api/utils/log.js')('core:app'),
// url = require('url'),
authorize = require('../../api/utils/authorizer.js'), //for token validations
languages = require('../../frontend/express/locale.conf'),
render = require('../../api/utils/render.js'),
rateLimit = require("express-rate-limit"),
membersUtility = require("./libs/members.js"),
argon2 = require('argon2'),
countlyCommon = require('../../api/lib/countly.common.js');
var COUNTLY_NAMED_TYPE = "Countly Community Edition v" + COUNTLY_VERSION;
var COUNTLY_TYPE_CE = true;
var COUNTLY_TRIAL = (versionInfo.trial) ? true : false;
var COUNTLY_TRACK_TYPE = "OSS";
if (versionInfo.footer) {
COUNTLY_NAMED_TYPE = versionInfo.footer;
COUNTLY_TYPE_CE = false;
if (COUNTLY_NAMED_TYPE === "Countly Cloud") {
COUNTLY_TRACK_TYPE = "Cloud";
}
else if (COUNTLY_TYPE !== "777a2bf527a18e0fffe22fb5b3e322e68d9c07a6") {
COUNTLY_TRACK_TYPE = "Enterprise";
}
}
else if (COUNTLY_TYPE !== "777a2bf527a18e0fffe22fb5b3e322e68d9c07a6") {
COUNTLY_NAMED_TYPE = "Countly Enterprise Edition v" + COUNTLY_VERSION;
COUNTLY_TYPE_CE = false;
COUNTLY_TRACK_TYPE = "Enterprise";
}
if (!countlyConfig.cookie) {
countlyConfig.cookie = {
httpOnly: true,
maxAge: 1000 * 60 * 60 * 24,
secure: countlyConfig.web.secure_cookies || false,
maxAgeLogin: 1000 * 60 * 60 * 24 * 365
};
}
plugins.setConfigs("frontend", {
production: true,
theme: countlyConfig.web.theme || "",
session_timeout: 30,
use_google: true,
code: true,
google_maps_api_key: "",
offline_mode: false
});
plugins.setUserConfigs("frontend", {
production: false,
theme: false,
session_timeout: false,
use_google: false,
code: false,
google_maps_api_key: ""
});
plugins.setConfigs("security", {
login_tries: 3,
login_wait: 5 * 60,
password_min: 8,
password_char: true,
password_number: true,
password_symbol: true,
password_expiration: 0,
password_rotation: 3,
dashboard_additional_headers: "X-Frame-Options:deny\nX-XSS-Protection:1; mode=block\nStrict-Transport-Security:max-age=31536000 ; includeSubDomains\nX-Content-Type-Options: nosniff",
api_additional_headers: "X-Frame-Options:deny\nX-XSS-Protection:1; mode=block\nAccess-Control-Allow-Origin:*",
dashboard_rate_limit_window: 60,
dashboard_rate_limit_requests: 500
});
process.on('uncaughtException', (err) => {
console.log('Caught exception: %j', err, err.stack);
if (log && log.e) {
log.e('Logging caught exception');
}
process.exit(1);
});
process.on('unhandledRejection', (reason, p) => {
console.log("Unhandled rejection at: Promise ", p, " reason: ", reason);
if (log && log.e) {
log.e("Logging unhandled rejection");
}
});
if (countlyConfig.web && countlyConfig.web.track === "all") {
countlyConfig.web.track = null;
}
var countlyConfigOrig = JSON.parse(JSON.stringify(countlyConfig));
var countlyDb = plugins.dbConnection(countlyConfig);
//reference for consistency between app and api processes
common.db = countlyDb;
membersUtility.db = countlyDb;
//checking remote configuration
membersUtility.recheckConfigs(countlyConfigOrig, countlyConfig);
/**
* Create sha1 hash string
* @param {string} str - string to hash
* @param {boolean} addSalt - should salt be added
* @returns {string} hashed string
**/
function sha1Hash(str, addSalt) {
var salt = (addSalt) ? new Date().getTime() : "";
return crypto.createHmac('sha1', salt + "").update(str + "").digest('hex');
}
/**
* Create sha512 hash string
* @param {string} str - string to hash
* @param {boolean} addSalt - should salt be added
* @returns {string} hashed string
**/
function sha512Hash(str, addSalt) {
var salt = (addSalt) ? new Date().getTime() : "";
return crypto.createHmac('sha512', salt + "").update(str + "").digest('hex');
}
/**
* Create argon2 hash string
* @param {string} str - string to hash
* @returns {promise} hash promise
**/
function argon2Hash(str) {
return argon2.hash(str);
}
/**
* Verify argon2 hash string
* @param {string} hashedStr - argon2 hashed string
* @param {string} str - string for verify
* @returns {promise} verify promise
**/
function verifyArgon2Hash(hashedStr, str) {
return argon2.verify(hashedStr, str);
}
/**
* Is hashed string argon2?
* @param {string} hashedStr | argon2 hashed string
* @returns {boolean} return true if string hashed by argon2
*/
function isArgon2Hash(hashedStr) {
return hashedStr.includes("$argon2");
}
/**
* Verify member for Argon2 Hash
* @param {string} username | User name
* @param {password} password | Password string
* @param {Function} callback | Callback function
*/
function verifyMemberArgon2Hash(username, password, callback) {
var secret = countlyConfig.passwordSecret || "";
password = password + secret;
countlyDb.collection('members').findOne({$and: [{ $or: [ {"username": username}, {"email": username}]}]}, (err, member) => {
if (member) {
if (isArgon2Hash(member.password)) {
verifyArgon2Hash(member.password, password).then(match => {
if (match) {
callback(undefined, member);
}
else {
callback("Password is wrong!");
}
}).catch(function() {
callback("Password is wrong!");
});
}
else {
var password_SHA1 = sha1Hash(password);
var password_SHA5 = sha512Hash(password);
if (member.password === password_SHA1 || member.password === password_SHA5) {
argon2Hash(password).then(password_ARGON2 => {
updateUserPasswordToArgon2(member._id, password_ARGON2);
callback(undefined, member);
}).catch(function() {
callback("Password is wrong!");
});
}
else {
callback("Password is wrong!");
}
}
}
else {
callback("Username is wrong!");
}
});
}
/**
* Update user password to new sha512 hash
* @param {string} id - id of the user document
* @param {string} password - password to hash
**/
function updateUserPasswordToArgon2(id, password) {
countlyDb.collection('members').update({ _id: id}, { $set: { password: password}});
}
/**
* Check if user is global admin
* @param {object} req - request object
* @returns {boolean} true if global admin
**/
function isGlobalAdmin(req) {
return (req.session.gadm);
}
/**
* Sort array by list of
* @param {array} arrayToSort - array to sort
* @param {array} sortList - list of values by which to sort
* @returns {array} sorted array
**/
function sortBy(arrayToSort, sortList) {
if (!sortList.length) {
return arrayToSort;
}
var tmpArr = [],
retArr = [];
for (let i = 0; i < arrayToSort.length; i++) {
var objId = arrayToSort[i]._id + "";
if (sortList.indexOf(objId) !== -1) {
tmpArr[sortList.indexOf(objId)] = arrayToSort[i];
}
}
for (let i = 0; i < tmpArr.length; i++) {
if (tmpArr[i]) {
retArr[retArr.length] = tmpArr[i];
}
}
for (let i = 0; i < arrayToSort.length; i++) {
if (retArr.indexOf(arrayToSort[i]) === -1) {
retArr[retArr.length] = arrayToSort[i];
}
}
return retArr;
}
var app = express();
app = expose(app);
app.enable('trust proxy');
app.set('x-powered-by', false);
const limiter = rateLimit({
windowMs: parseInt(plugins.getConfig("security").dashboard_rate_limit_window) * 1000,
max: parseInt(plugins.getConfig("security").dashboard_rate_limit_requests),
headers: false,
//limit only in production mode
skip: function() {
return !plugins.getConfig("frontend").production || plugins.getConfig("security").dashboard_rate_limit_requests <= 0;
}
});
// apply to all requests
app.use(limiter);
var loadedThemes = {};
var curTheme = countlyConfig.web.theme || "";
/**
* Load theme files
* @param {string} theme - theme name
* @param {function} callback - when loading files done
**/
app.loadThemeFiles = function(theme, callback) {
if (!loadedThemes[theme]) {
var tempThemeFiles = {css: [], js: []};
if (theme && theme.length) {
var themeDir = path.resolve(__dirname, "public/themes/" + theme + "/");
fs.readdir(themeDir, function(err, list) {
if (err) {
if (callback) {
callback(tempThemeFiles);
}
return ;
}
var ext;
for (var i = 0; i < list.length; i++) {
ext = list[i].split(".").pop();
if (!tempThemeFiles[ext]) {
tempThemeFiles[ext] = [];
}
tempThemeFiles[ext].push(countlyConfig.path + '/themes/' + theme + "/" + list[i]);
}
if (callback) {
callback(tempThemeFiles);
}
loadedThemes[theme] = tempThemeFiles;
});
}
else if (callback) {
callback(tempThemeFiles);
}
}
else if (callback) {
callback(loadedThemes[theme]);
}
};
plugins.loadConfigs(countlyDb, function() {
curTheme = plugins.getConfig("frontend").theme;
app.loadThemeFiles(curTheme);
app.dashboard_headers = plugins.getConfig("security").dashboard_additional_headers;
});
app.engine('html', require('ejs').renderFile);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.set('view options', {layout: false});
app.use('/stylesheets/ionicons/fonts/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use('/fonts/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use('*.svg', function(req, res, next) {
res.setHeader('Content-Type', 'image/svg+xml; charset=UTF-8');
next();
});
/**
* Add headers to request
* @param {object} req - request object
* @param {object} res - response object
**/
function add_headers(req, res) {
if (countlyConfig.web.secure_cookies) {
//we can't detect if it uses https behind nginx, without specific nginx configuration, so we assume it does
req.headers["x-forwarded-proto"] = "https";
}
//set provided in configuration headers
if (app.dashboard_headers) {
var headers = app.dashboard_headers.replace(/\r\n|\r|\n/g, "\n").split("\n");
var parts;
for (let i = 0; i < headers.length; i++) {
if (headers[i] && headers[i].length) {
parts = headers[i].split(/:(.+)?/);
if (parts.length === 3) {
res.header(parts[0], parts[1]);
}
}
}
}
}
app.use(function(req, res, next) {
add_headers(req, res);
next();
});
plugins.loadAppStatic(app, countlyDb, express);
app.use(cookieParser());
//server theme images
app.use(function(req, res, next) {
if (req.url.indexOf(countlyConfig.path + '/images/') === 0) {
var urlPath = req.url.replace(countlyConfig.path, "");
var theme = req.cookies.theme || curTheme;
if (theme && theme.length) {
fs.exists(__dirname + '/public/themes/' + theme + urlPath, function(exists) {
if (exists) {
res.sendFile(__dirname + '/public/themes/' + theme + urlPath);
}
else {
next();
}
});
}
else { //serve default location
next();
}
}
else {
next();
}
});
//serve app images
app.get(countlyConfig.path + '/appimages/*', function(req, res) {
if (!req.params || !req.params[0] || req.params[0] === '') {
res.sendFile(__dirname + '/public/images/default_app_icon.png');
}
else {
countlyFs.getStats("appimages", __dirname + '/public/' + req.path, {id: req.params[0]}, function(err, stats) {
if (err || !stats || !stats.size) {
res.sendFile(__dirname + '/public/images/default_app_icon.png');
}
else {
countlyFs.getStream("appimages", __dirname + '/public/' + req.path, {id: req.params[0]}, function(err2, stream) {
if (err2 || !stream) {
res.sendFile(__dirname + '/public/images/default_app_icon.png');
}
else {
res.writeHead(200, {
'Accept-Ranges': 'bytes',
'Cache-Control': 'public, max-age=31536000',
'Connection': 'keep-alive',
'Date': new Date().toUTCString(),
'Last-Modified': stats.mtime.toUTCString(),
'Content-Type': 'image/png',
'Content-Length': stats.size
});
stream.pipe(res);
}
});
}
});
}
});
//serve member images
app.get(countlyConfig.path + '/memberimages/*', function(req, res) {
if (!req.params || !req.params[0] || req.params[0] === '') {
res.sendFile(__dirname + '/public/images/default_member_icon.png');
}
else {
countlyFs.getStats("memberimages", __dirname + '/public/' + req.path, {id: req.params[0]}, function(err, stats) {
if (err || !stats || !stats.size) {
res.sendFile(__dirname + '/public/images/default_member_icon.png');
}
else {
countlyFs.getStream("memberimages", __dirname + '/public/' + req.path, {id: req.params[0]}, function(err2, stream) {
if (err2 || !stream) {
res.sendFile(__dirname + '/public/images/default_member_icon.png');
}
else {
res.writeHead(200, {
'Accept-Ranges': 'bytes',
'Cache-Control': 'public, max-age=31536000',
'Connection': 'keep-alive',
'Date': new Date().toUTCString(),
'Last-Modified': stats.mtime.toUTCString(),
'Content-Type': 'image/png',
'Content-Length': stats.size
});
stream.pipe(res);
}
});
}
});
}
});
app.get(countlyConfig.path + "*/screenshots/*", function(req, res) {
countlyFs.getStats("screenshots", __dirname + '/public/' + req.path, {id: "core"}, function(err, stats) {
if (err || !stats || !stats.size) {
return res.send(false);
}
countlyFs.getStream("screenshots", __dirname + '/public/' + req.path, {id: "core"}, function(err2, stream) {
if (err2 || !stream) {
return res.send(false);
}
res.writeHead(200, {
'Accept-Ranges': 'bytes',
'Cache-Control': 'public, max-age=31536000',
'Connection': 'keep-alive',
'Date': new Date().toUTCString(),
'Last-Modified': stats.mtime.toUTCString(),
'Content-Type': 'image/png',
'Content-Length': stats.size
});
stream.pipe(res);
});
});
});
var oneYear = 31557600000;
app.use(countlyConfig.path, express.static(__dirname + '/public', { maxAge: oneYear }));
app.use(session({
secret: countlyConfig.web.session_secret || 'countlyss',
name: countlyConfig.web.session_name || 'connect.sid',
cookie: countlyConfig.cookie,
store: new SkinStore(countlyDb),
saveUninitialized: false,
resave: true,
rolling: true,
proxy: true,
unset: "destroy"
}));
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(function(req, res, next) {
var contentType = req.headers['content-type'];
if (req.method.toLowerCase() === 'post' && contentType && contentType.indexOf('multipart/form-data') >= 0) {
var form = new formidable.IncomingForm();
form.uploadDir = __dirname + '/uploads';
form.parse(req, function(err, fields, files) {
req.files = files;
if (!req.body) {
req.body = {};
}
for (let i in fields) {
if (typeof req.body[i] === "undefined") {
req.body[i] = fields[i];
}
}
next();
});
}
else {
next();
}
});
app.use(flash());
app.use(function(req, res, next) {
req.template = {};
req.template.html = "";
req.template.js = "";
req.template.css = "";
req.template.form = "";
req.countly = {
company: COUNTLY_COMPANY,
version: COUNTLY_VERSION,
type: COUNTLY_TYPE,
page: COUNTLY_PAGE,
title: COUNTLY_NAME,
favicon: "images/favicon.png"
};
plugins.loadConfigs(countlyDb, function() {
var securityConf = plugins.getConfig("security");
app.dashboard_headers = securityConf.dashboard_additional_headers;
add_headers(req, res);
preventBruteforce.fails = Number.isInteger(securityConf.login_tries) ? securityConf.login_tries : 3;
preventBruteforce.wait = securityConf.login_wait || 5 * 60;
curTheme = plugins.getConfig("frontend", req.session && req.session.settings).theme;
app.loadThemeFiles(req.cookies.theme || curTheme, function(themeFiles) {
res.locals.flash = req.flash.bind(req);
req.config = plugins.getConfig("frontend", req.session && req.session.settings);
req.themeFiles = themeFiles;
var _render = res.render;
res.render = function(view, opts, fn, parent, sub) {
if (!opts) {
opts = {};
}
if (!opts.path) {
opts.path = countlyConfig.path || "";
}
if (!opts.cdn) {
opts.cdn = countlyConfig.cdn || "";
}
if (!opts.themeFiles) {
opts.themeFiles = themeFiles;
}
_render.call(res, view, opts, fn, parent, sub);
};
next();
});
});
});
app.use(methodOverride());
app.use(function(req, res, next) {
if (!plugins.callMethod("skipCSRF", {req: req, res: res, next: next})) {
//none of the plugins requested to skip csrf for this request
csrf(req, res, next);
}
else {
//skipping csrf step, some plugin needs it without csrf
next();
}
});
app.use(function(req, res, next) {
if (!plugins.callMethod("skipDollarCheck", {req: req, res: res, next: next})) {
//none of the plugins requested to skip dollar sign check
dollarDefender(req, res, next);
}
else {
//skipping dollar sign check, some plugin needs mongo object as parameters
next();
}
});
//for csrf error handling. redirect to login if getting bad token while logging in(not show forbidden page)
app.use(function(err, req, res, next) { // eslint-disable-line no-unused-vars
var mylink = req.url.split('?');
mylink = mylink[0];
if (err.code === 'EBADCSRFTOKEN' && mylink === countlyConfig.path + "/login") {
res.status(403);
res.redirect(countlyConfig.path + '/login?message=login.token-expired');
}
else {
res.status(403).send("Forbidden Token");
}
});
//prevent bruteforce attacks
preventBruteforce.db = countlyDb;
preventBruteforce.mail = countlyMail;
for (let pathPart of ["/login", "/mobile/login"]) {
const absPath = countlyConfig.path + pathPart;
preventBruteforce.pathIdentifiers[absPath] = "login";
preventBruteforce.userIdentifiers[absPath] = (req) => req.body.username;
}
preventBruteforce.blockHooks.login = function(uid, req, res) { // eslint-disable-line no-unused-vars
preventBruteforce.db.collection("members").findOne({username: uid}, function(err, member) {
if (member) {
preventBruteforce.mail.sendTimeBanWarning(member, preventBruteforce.db);
}
});
};
preventBruteforce.pathIdentifiers[countlyConfig.path + "/forgot"] = "forgot";
app.use(preventBruteforce.middleware);
plugins.loadAppPlugins(app, countlyDb, express);
var env = process.env.NODE_ENV || 'development';
if ('development' === env) {
app.use(errorhandler(true));
}
app.get(countlyConfig.path + '/', function(req, res) {
res.redirect(countlyConfig.path + '/login');
});
var extendSession = function(req) {
membersUtility.extendSession(req);
};
var checkRequestForSession = function(req, res, next) {
if (parseInt(plugins.getConfig("frontend", req.session && req.session.settings).session_timeout)) {
if (req.session.uid) {
if (Date.now() > req.session.expires) {
membersUtility.logout(req, res);
res.redirect(countlyConfig.path + '/login?message=logout.inactivity');
}
else {
//extend session
extendSession(req, res, next);
next();
}
}
else {
next();
}
}
else {
next();
}
};
app.get(countlyConfig.path + '/ping', function(req, res) {
countlyDb.collection("plugins").findOne({_id: "plugins"}, function(err) {
if (err) {
res.status(404).send("DB Error");
}
else {
res.send("Success");
}
});
});
app.get(countlyConfig.path + '/configs', function(req, res) {
membersUtility.recheckConfigs(countlyConfigOrig, countlyConfig);
res.send("Success");
});
app.get(countlyConfig.path + '/session', function(req, res, next) {
if (req.session.auth_token) {
authorize.verify_return({
db: countlyDb,
token: req.session.auth_token,
req_path: "",
callback: function(valid) {
if (!valid) {
//logout user
res.send("logout");
}
else {
if (req.session.uid) {
if (Date.now() > req.session.expires) {
//logout user
res.send("logout");
}
else {
//extend session
if (req.query.check_session) {
res.send("success");
}
else {
extendSession(req, res, next);
res.send("success");
}
}
}
else {
res.send("login");
}
}
}
});
}
else {
res.send("login");
}
});
app.get(countlyConfig.path + '/dashboard', checkRequestForSession);
app.post('*', checkRequestForSession);
app.get(countlyConfig.path + '/logout', function(req, res) {
if (req.query.message) {
res.redirect(countlyConfig.path + '/login?message=' + req.query.message);
}
else {
res.redirect(countlyConfig.path + '/login');
}
});
app.post(countlyConfig.path + '/logout', function(req, res/*, next*/) {
membersUtility.logout(req, res);
if (req.query.message) {
res.redirect(countlyConfig.path + '/login?message=' + req.query.message);
}
else {
res.redirect(countlyConfig.path + '/login');
}
});
/**
* Render dashboard
* @param {object} req - request object
* @param {object} res - response object
* @param {function} next - callback for next middleware
* @param {object} member - dashboard member document
* @param {array} adminOfApps - list of apps member is admin of
* @param {array} userOfApps - list of apps member is user of
* @param {object} countlyGlobalApps - all apps user has any access to, where key is app id and value is app document
* @param {object} countlyGlobalAdminApps - all apps user has write access to, where key is app id and value is app document
**/
function renderDashboard(req, res, next, member, adminOfApps, userOfApps, countlyGlobalApps, countlyGlobalAdminApps) {
var configs = plugins.getConfig("frontend", member.settings);
configs.export_limit = plugins.getConfig("api").export_limit;
app.loadThemeFiles(configs.theme, function(theme) {
if (configs._user.theme) {
res.cookie("theme", configs.theme);
}
req.session.uid = member._id;
req.session.gadm = (member.global_admin === true);
req.session.email = member.email;
req.session.settings = member.settings;
res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
res.header('Expires', '0');
res.header('Pragma', 'no-cache');
if (member.upgrade) {
countlyDb.collection('members').update({"_id": member._id}, {$unset: {upgrade: ""}}, function() {});
}
member._id += "";
delete member.password;
adminOfApps = sortBy(adminOfApps, member.appSortList || []);
userOfApps = sortBy(userOfApps, member.appSortList || []);
var defaultApp = userOfApps[0];
var serverSideRendering = req.query.ssr;
_.extend(req.config, configs);
var countlyGlobal = {
COUNTLY_CONTAINER: process.env.COUNTLY_CONTAINER,
countlyTitle: req.countly.title,
company: req.countly.company,
languages: languages,
countlyVersion: req.countly.version,
countlyFavicon: req.countly.favicon,
pluginsSHA: sha1Hash(plugins.getPlugins()),
apps: countlyGlobalApps,
defaultApp: defaultApp,
admin_apps: countlyGlobalAdminApps,
csrf_token: req.csrfToken(),
auth_token: req.session.auth_token,
member: member,
config: req.config,
security: plugins.getConfig("security"),
plugins: plugins.getPlugins(),
path: countlyConfig.path || "",
cdn: countlyConfig.cdn || "",
message: req.flash("message"),
ssr: serverSideRendering
};
var toDashboard = {
countlyTitle: req.countly.title,
languages: languages,
countlyFavicon: req.countly.favicon,
adminOfApps: adminOfApps,
userOfApps: userOfApps,
defaultApp: defaultApp,
member: member,
intercom: countlyConfig.web.use_intercom,
track: countlyConfig.web.track || false,
installed: req.session.install || false,
cpus: require('os').cpus().length,
countlyVersion: req.countly.version,
countlyType: COUNTLY_TYPE_CE,
countlyTrial: COUNTLY_TRIAL,
countlyTypeName: COUNTLY_NAMED_TYPE,
feedbackLink: COUNTLY_FEEDBACK_LINK,
documentationLink: COUNTLY_DOCUMENTATION_LINK,
helpCenterLink: COUNTLY_HELPCENTER_LINK,
featureRequestLink: COUNTLY_FEATUREREQUEST_LINK,
countlyTypeTrack: COUNTLY_TRACK_TYPE,
frontend_app: versionInfo.frontend_app,
frontend_server: versionInfo.frontend_server,
production: configs.production || false,
pluginsSHA: sha1Hash(plugins.getPlugins()),
plugins: plugins.getPlugins(),
config: req.config,
path: countlyConfig.path || "",
cdn: countlyConfig.cdn || "",
use_google: configs.use_google || false,
themeFiles: theme,
inject_template: req.template,
javascripts: [],
offline_mode: configs.offline_mode || false
};
// google services cannot work when offline mode enable
if (toDashboard.offline_mode) {
toDashboard.use_google = false;
}
if (countlyGlobal.config.offline_mode) {
countlyGlobal.config.use_google = false;
}
var plgns = [].concat(plugins.getPlugins());
if (plgns.indexOf('push') !== -1) {
plgns.splice(plgns.indexOf('push'), 1);
plgns.unshift('push');
}
plgns.forEach(plugin => {
try {
let contents = fs.readdirSync(__dirname + `/../../plugins/${plugin}/frontend/public/javascripts`) || [];
toDashboard.javascripts.push.apply(toDashboard.javascripts, contents.filter(n => n.indexOf('.js') === n.length - 3).map(n => `${plugin}/javascripts/${n}`));
}
catch (e) {
console.log('Error while reading folder of plugin %s: %j', plugin, e.stack);
}
});
if (req.session.install) {
req.session.install = null;
res.clearCookie('install');
}
plugins.callMethod("renderDashboard", {req: req, res: res, next: next, data: {member: member, adminApps: countlyGlobalAdminApps, userApps: countlyGlobalApps, countlyGlobal: countlyGlobal, toDashboard: toDashboard}});
res.expose(countlyGlobal, 'countlyGlobal');
res.render('dashboard', toDashboard);
});
}
app.get(countlyConfig.path + '/dashboard', function(req, res, next) {
if (!req.session.uid) {
res.redirect(countlyConfig.path + '/login');
}
else {
countlyDb.collection('members').findOne({"_id": countlyDb.ObjectID(req.session.uid + "")}, function(err, member) {
if (member) {
req.session.cookie.maxAge = countlyConfig.cookie.maxAgeLogin;
var adminOfApps = [],
userOfApps = [],
countlyGlobalApps = {},
countlyGlobalAdminApps = {};
if (member.global_admin) {
countlyDb.collection('apps').find({}).toArray(function(err2, apps) {
adminOfApps = apps;
userOfApps = apps;
for (let i = 0; i < apps.length; i++) {
apps[i].type = apps[i].type || "mobile";
countlyGlobalApps[apps[i]._id] = apps[i];
countlyGlobalApps[apps[i]._id]._id = "" + apps[i]._id;
}
countlyGlobalAdminApps = countlyGlobalApps;
renderDashboard(req, res, next, member, adminOfApps, userOfApps, countlyGlobalApps, countlyGlobalAdminApps);
});
}
else {
var adminOfAppIds = [],
userOfAppIds = [];
if (member.admin_of.length === 1 && member.admin_of[0] === "") {
member.admin_of = [];
}
for (let i = 0; i < member.admin_of.length; i++) {
if (member.admin_of[i] === "") {
continue;
}
adminOfAppIds[adminOfAppIds.length] = countlyDb.ObjectID(member.admin_of[i]);
}
for (let i = 0; i < member.user_of.length; i++) {
if (member.user_of[i] === "") {
continue;
}
userOfAppIds[userOfAppIds.length] = countlyDb.ObjectID(member.user_of[i]);
}
countlyDb.collection('apps').find({ _id: { '$in': adminOfAppIds } }).toArray(function(err2, admin_of) {
for (let i = 0; i < admin_of.length; i++) {
countlyGlobalAdminApps[admin_of[i]._id] = admin_of[i];
countlyGlobalAdminApps[admin_of[i]._id]._id = "" + admin_of[i]._id;
}
countlyDb.collection('apps').find({ _id: { '$in': userOfAppIds } }).toArray(function(err3, user_of) {
adminOfApps = admin_of;
userOfApps = user_of;
for (let i = 0; i < user_of.length; i++) {
if (user_of[i].apn) {
user_of[i].apn.forEach(a => a._id = '' + a._id);
}
if (user_of[i].gcm) {
user_of[i].gcm.forEach(a => a._id = '' + a._id);
}
countlyGlobalApps[user_of[i]._id] = user_of[i];
countlyGlobalApps[user_of[i]._id]._id = "" + user_of[i]._id;
countlyGlobalApps[user_of[i]._id].type = countlyGlobalApps[user_of[i]._id].type || "mobile";
}
renderDashboard(req, res, next, member, adminOfApps, userOfApps, countlyGlobalApps, countlyGlobalAdminApps);
});