-
Notifications
You must be signed in to change notification settings - Fork 975
/
Copy pathrequestProcessor.js
executable file
·3842 lines (3664 loc) · 187 KB
/
requestProcessor.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
/**
* Module for processing data passed to Countly
* @module api/utils/requestProcessor
*/
const Promise = require('bluebird');
const url = require('url');
const common = require('./common.js');
const countlyCommon = require('../lib/countly.common.js');
const { validateAppAdmin, validateUser, validateRead, validateUserForRead, validateUserForWrite, validateGlobalAdmin, dbUserHasAccessToCollection, validateUpdate, validateDelete, validateCreate, getBaseAppFilter } = require('./rights.js');
const authorize = require('./authorizer.js');
const taskmanager = require('./taskmanager.js');
const plugins = require('../../plugins/pluginManager.js');
const versionInfo = require('../../frontend/express/version.info');
const packageJson = require('./../../package.json');
const log = require('./log.js')('core:api');
const fs = require('fs');
var countlyFs = require('./countlyFs.js');
var path = require('path');
const validateUserForWriteAPI = validateUser;
const validateUserForDataReadAPI = validateRead;
const validateUserForDataWriteAPI = validateUserForWrite;
const validateUserForGlobalAdmin = validateGlobalAdmin;
const validateUserForMgmtReadAPI = validateUser;
const request = require('countly-request')(plugins.getConfig("security"));
const Handle = require('../../api/parts/jobs/index.js');
var loaded_configs_time = 0;
const countlyApi = {
data: {
usage: require('../parts/data/usage.js'),
fetch: require('../parts/data/fetch.js'),
events: require('../parts/data/events.js'),
exports: require('../parts/data/exports.js'),
geoData: require('../parts/data/geoData.js')
},
mgmt: {
users: require('../parts/mgmt/users.js'),
apps: require('../parts/mgmt/apps.js'),
appUsers: require('../parts/mgmt/app_users.js'),
eventGroups: require('../parts/mgmt/event_groups.js'),
cms: require('../parts/mgmt/cms.js'),
datePresets: require('../parts/mgmt/date_presets.js'),
}
};
const reloadConfig = function() {
return new Promise(function(resolve) {
var my_time = Date.now();
var reload_configs_after = common.config.reloadConfigAfter || 10000;
//once in minute
if (loaded_configs_time === 0 || (my_time - loaded_configs_time) >= reload_configs_after) {
plugins.loadConfigs(common.db, () => {
loaded_configs_time = my_time;
resolve();
}, true);
}
else {
resolve();
}
});
};
/**
* Default request processing handler, which requires request context to operate. Check tcp_example.js
* @static
* @param {params} params - for request context. Minimum needed properties listed
* @param {object} params.req - Request object, should not be empty and should contain listed params
* @param {string} params.req.url - Endpoint URL that you are calling. May contain query string.
* @param {object} params.req.body - Parsed JSON object with data (same name params will overwrite query string if anything provided there)
* @param {APICallback} params.APICallback - API output handler. Which should handle API response
* @returns {void} void
* @example
* //creating request context
* var params = {
* //providing data in request object
* 'req':{"url":"/i", "body":{"device_id":"test","app_key":"APP_KEY","begin_session":1,"metrics":{}}},
* //adding custom processing for API responses
* 'APICallback': function(err, data, headers, returnCode, params){
* //handling api response, like sending to client or verifying
* if(err){
* //there was problem processing request
* console.log(data, returnCode);
* }
* else{
* //request was processed, let's handle response data
* handle(data);
* }
* }
* };
*
* //processing request
* processRequest(params);
*/
const processRequest = (params) => {
if (!params.req || !params.req.url) {
return common.returnMessage(params, 400, "Please provide request data");
}
const urlParts = url.parse(params.req.url, true),
queryString = urlParts.query,
paths = urlParts.pathname.split("/");
/**
* Main request processing object containing all information shared through all the parts of the same request
* @typedef params
* @type {object}
* @global
* @property {string} href - full URL href
* @property {http.ServerResponse} res - The HTTP response object
* @property {http.IncomingMessage} req - The HTTP request object
* @param {APICallback} params.APICallback - API output handler. Which should handle API response
* @property {object} qstring - all the passed fields either through query string in GET requests or body and query string for POST requests
* @property {string} apiPath - two top level url path, for example /i/analytics, first two segments from the fullPath
* @property {string} fullPath - full url path, for example /i/analytics/dashboards
* @property {object} files - object with uploaded files, available in POST requests which upload files
* @property {Object} [files.app_image] - Uploaded app image file
* @property {string} files.app_image.path - The temporary path of the uploaded app image file
* @property {string} files.app_image.name - The original name of the uploaded app image file
* @property {string} files.app_image.type - The MIME type of the uploaded app image file
* @property {number} files.app_image.size - The size (in bytes) of the uploaded app image file
* @property {string} cancelRequest - Used for skipping SDK requests, if contains true, then request should be ignored and not processed. Can be set at any time by any plugin, but API only checks for it in beggining after / and /sdk events, so that is when plugins should set it if needed. Should contain reason for request cancelation
* @property {boolean} [blockResponses=false] - Flag to block responses from being sent
* @property {boolean} [forceProcessingRequestTimeout=false] - Flag to force processing request timeout
* @property {boolean} bulk - True if this SDK request is processed from the bulk method
* @property {Array<Promise>} promises - Array of the promises by different events. When all promises are fulfilled, request counts as processed
* @property {string} ip_address - IP address of the device submitted request, exists in all SDK requests
* @property {object} user - Data with some user info, like country geolocation, etc from the request, exists in all SDK requests
* @property {string} user.country - User's country
* @property {string} user.city - User's city
* @property {number} [user.tz] - User's timezone offset (in minutes)
* @property {object} app_user - Document from the app_users collection for current user, exists in all SDK requests after validation
* @property {string} app_user.uid - Application user ID
* @property {string} app_user.did - Device ID
* @property {string} app_user.country - User's country
* @property {string} app_user.city - User's city
* @property {number} app_user.tz - User's timezone offset (in minutes)
* @property {Object} [app_user.custom] - Custom properties for the application user
* @property {object} app_user_id - ID of app_users document for the user, exists in all SDK requests after validation
* @property {object} app - Document for the app sending request, exists in all SDK requests after validation and after validateUserForDataReadAPI validation
* @property {string} app._id - ID of the app document
* @property {string} app.name - Name of the app
* @property {string} app.country - Country of the app
* @property {string} app.category - Category of the app
* @property {string} app.timezone - Timezone of the app
* @property {string} app.type - Type of the app
* @property {boolean} app.locked - Flag indicating if the app is locked
* @property {Object} app.plugins - Plugin-specific configuration for the app
* @property {ObjectID} app_id - ObjectID of the app document, available after validation
* @property {string} app_cc - Selected app country, available after validation
* @property {string} appTimezone - Selected app timezone, available after validation
* @property {object} member - All data about dashboard user sending the request, exists on all requests containing api_key, after validation through validation methods
* @property {string} member._id - ID of the dashboard user
* @property {boolean} member.global_admin - Flag indicating if the user has global admin rights
* @property {string} member.auth_token - The authentication token for the user
* @property {boolean} member.locked - Flag indicating if the user is locked
* @property {Array} [member.admin_of] - Array of app IDs the user is an admin of (legacy)
* @property {Array} [member.user_of] - Array of app IDs the user has user access to (legacy)
* @property {string} member.username - Username of the dashboard user
* @property {string} member.email - Email address of the dashboard user
* @property {string} member.full_name - Full name of the dashboard user
* @property {string} member.api_key - API key of the dashboard user
* @property {Object} member.permission - Object containing user's access permissions
* @property {Object} member.permission._ - Object containing special permissions
* @property {Array} member.permission._.u - Array of arrays containing app IDs the user has user access to
* @property {Array} member.permission._.a - Array of app IDs the user has admin access to
* @property {Object} [member.permission.c] - Object containing create permissions for specific apps
* @property {Object} [member.permission.c[app_id]] - Object containing create permissions for a specific app
* @property {boolean} [member.permission.c[app_id].all] - Flag indicating if the user has create access to all features in the app
* @property {Object} [member.permission.c[app_id].allowed] - Object containing allowed create permissions for the app
* @property {Object} [member.permission.r] - Object containing read permissions for specific apps
* @property {Object} [member.permission.r[app_id]] - Object containing read permissions for a specific app
* @property {boolean} [member.permission.r[app_id].all] - Flag indicating if the user has read access to all features in the app
* @property {Object} [member.permission.r[app_id].allowed] - Object containing allowed read permissions for the app
* @property {Object} [member.permission.u] - Object containing update permissions for specific apps
* @property {Object} [member.permission.u[app_id]] - Object containing update permissions for a specific app
* @property {boolean} [member.permission.u[app_id].all] - Flag indicating if the user has update access to all features in the app
* @property {Object} [member.permission.u[app_id].allowed] - Object containing allowed update permissions for the app
* @property {Object} [member.permission.d] - Object containing delete permissions for specific apps
* @property {Object} [member.permission.d[app_id]] - Object containing delete permissions for a specific app
* @property {boolean} [member.permission.d[app_id].all] - Flag indicating if the user has delete access to all features in the app
* @property {Object} [member.permission.d[app_id].allowed] - Object containing allowed delete permissions for the app
* @property {Object} member.eventList - Object containing event collections with replaced app names
* @property {Object} member.viewList - Object containing view collections with replaced app names
* @property {timeObject} time - Time object for the request
* @property {string} request_hash - Hash of the request data
* @property {string} [previous_session] - ID of the user's previous session
* @property {number} [previous_session_start] - Start timestamp of the user's previous session
* @property {string} request_id - Unique ID for this request
* @property {string} [user_id] - ID of the user making the request
* @property {string} [formDataUrl] - URL encoded form data
* @property {boolean} [retry_request] - Flag indicating if this is a retry of a failed request
* @property {boolean} [populator] - Flag indicating if this request is from the populator
* @property {Object} urlParts - Parsed URL parts
* @property {Object} urlParts.query - Parsed query string as key-value pairs
* @property {string} urlParts.pathname - The URL path
* @property {string} urlParts.href - The full URL
* @property {Array<string>} paths - The URL path split into segments
* @property {function} [output] - Callback function to handle the API response
* @property {boolean} [waitForResponse] - If false, return immediately and do not wait for plugin chain execution to complete
* @property {string} [app_name] - Name of the app
* @property {number} time.mstimestamp - Request timestamp in milliseconds
* @property {Object} [app_user.ls] - Last session timestamp of the app user
* @property {boolean} [truncateEventValuesList=false] - Flag indicating whether to truncate event values list
* @property {number} [session_duration] - Total session duration
* @property {boolean} [is_os_processed=false] - Flag indicating if OS and OS version have been processed
* @property {Object} [processed_metrics] - Processed metrics data
* @property {boolean} [app_user.has_ongoing_session] - Flag indicating if the user has an ongoing session
* @property {number} [app_user.last_req] - Timestamp of the user's last request
* @property {Object} [dbDateIds] - Object with date IDs for different time periods
* @property {boolean} [dataTransformed=false] - Flag indicating if the data is already transformed
*/
params.href = urlParts.href;
params.qstring = params.qstring || {};
params.res = params.res || {};
params.urlParts = urlParts;
params.paths = paths;
//request object fillers
params.req.method = params.req.method || "custom";
params.req.headers = params.req.headers || {};
params.req.socket = params.req.socket || {};
params.req.connection = params.req.connection || {};
//copying query string data as qstring param
if (queryString) {
for (let i in queryString) {
params.qstring[i] = queryString[i];
}
}
//copying body as qstring param
if (params.req.body && typeof params.req.body === "object") {
for (let i in params.req.body) {
params.qstring[i] = params.req.body[i];
}
}
if (params.qstring.app_id && params.qstring.app_id.length !== 24) {
common.returnMessage(params, 400, 'Invalid parameter "app_id"');
return false;
}
if (params.qstring.user_id && params.qstring.user_id.length !== 24) {
common.returnMessage(params, 400, 'Invalid parameter "user_id"');
return false;
}
//remove countly path
if (common.config.path === "/" + paths[1]) {
paths.splice(1, 1);
}
let apiPath = '';
for (let i = 1; i < paths.length; i++) {
if (i > 2) {
break;
}
apiPath += "/" + paths[i];
}
params.apiPath = apiPath;
params.fullPath = paths.join("/");
reloadConfig().then(function() {
plugins.dispatch("/", {
params: params,
apiPath: apiPath,
validateAppForWriteAPI: validateAppForWriteAPI,
validateUserForDataReadAPI: validateUserForDataReadAPI,
validateUserForDataWriteAPI: validateUserForDataWriteAPI,
validateUserForGlobalAdmin: validateUserForGlobalAdmin,
paths: paths,
urlParts: urlParts
});
if (!params.cancelRequest) {
switch (apiPath) {
case '/i/bulk': {
let requests = params.qstring.requests;
if (requests && typeof requests === "string") {
try {
requests = JSON.parse(requests);
}
catch (SyntaxError) {
console.log('Parse bulk JSON failed', requests, params.req.url, params.req.body);
requests = null;
}
}
if (!requests) {
common.returnMessage(params, 400, 'Missing parameter "requests"');
return false;
}
if (!Array.isArray(requests)) {
console.log("Passed invalid param for request. Expected Array, got " + typeof requests);
common.returnMessage(params, 400, 'Invalid parameter "requests"');
return false;
}
if (!params.qstring.safe_api_response && !plugins.getConfig("api", params.app && params.app.plugins, true).safe && !params.res.finished) {
common.returnMessage(params, 200, 'Success');
}
common.blockResponses(params);
processBulkRequest(0, requests, params);
break;
}
case '/i/users': {
if (params.qstring.args) {
try {
params.qstring.args = JSON.parse(params.qstring.args);
}
catch (SyntaxError) {
console.log('Parse ' + apiPath + ' JSON failed', params.req.url, params.req.body);
}
}
switch (paths[3]) {
/**
* @api {get} /i/users/create Create new user
* @apiName Create User
* @apiGroup User Management
*
* @apiDescription Access database, get collections, indexes and data
* @apiQuery {Object} args User data object
* @apiQuery {String} args.full_name Full name
* @apiQuery {String} args.username Username
* @apiQuery {String} args.password Password
* @apiQuery {String} args.email Email
* @apiQuery {Object} args.permission Permission object
* @apiQuery {Boolean} args.global_admin Global admin flag
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "full_name":"fn",
* "username":"un",
* "email":"[email protected]",
* "permission": {
* "c":{},
* "r":{},
* "u":{},
* "d":{},
* "_":{
* "u":[[]],
* "a":[]
* }
* },
* "global_admin":true,
* "password_changed":0,
* "created_at":1651240780,
* "locked":false,
* "api_key":"1c5e93c6657d76ae8903f14c32cb3796",
* "_id":"626bef4cb00db29a02f8f7a0"
* }
*
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 400 Bad Request
* {
* "result": "Missing parameter \"app_key\" or \"device_id\"""
* }
*/
case 'create':
validateUserForGlobalAdmin(params, countlyApi.mgmt.users.createUser);
break;
/**
* @api {get} /i/users/update Update user
* @apiName Update User
* @apiGroup User Management
*
* @apiDescription Access database, get collections, indexes and data
* @apiQuery {Object} args User data object
* @apiQuery {String} args.full_name Full name
* @apiQuery {String} args.username Username
* @apiQuery {String} args.password Password
* @apiQuery {String} args.email Email
* @apiQuery {Object} args.permission Permission object
* @apiQuery {Boolean} args.global_admin Global admin flag
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "result":"Success"
* }
*
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 400 Bad Request
* {
* "result": "Missing parameter \"app_key\" or \"device_id\"""
* }
*/
case 'update':
validateUserForGlobalAdmin(params, countlyApi.mgmt.users.updateUser);
break;
/**
* @api {get} /i/users/delete Delete user
* @apiName Delete User
* @apiGroup User Management
*
* @apiDescription Access database, get collections, indexes and data
* @apiQuery {Object} args User data object
* @apiQuery {String} args.user_ids IDs array for users which will be deleted
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "result":"Success"
* }
*
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 400 Bad Request
* {
* "result": "Missing parameter \"app_key\" or \"device_id\"""
* }
*/
case 'delete':
validateUserForGlobalAdmin(params, countlyApi.mgmt.users.deleteUser);
break;
case 'deleteOwnAccount':
validateUserForGlobalAdmin(params, countlyApi.mgmt.users.deleteOwnAccount);
break;
case 'updateHomeSettings':
validateUserForGlobalAdmin(params, countlyApi.mgmt.users.updateHomeSettings);
break;
case 'ack':
validateUserForWriteAPI(countlyApi.mgmt.users.ackNotification, params);
break;
default:
if (!plugins.dispatch(apiPath, {
params: params,
validateUserForDataReadAPI: validateUserForDataReadAPI,
validateUserForMgmtReadAPI: validateUserForMgmtReadAPI,
paths: paths,
validateUserForDataWriteAPI: validateUserForDataWriteAPI,
validateUserForGlobalAdmin: validateUserForGlobalAdmin
})) {
common.returnMessage(params, 400, 'Invalid path, must be one of /create, /update, /deleteOwnAccount or /delete');
}
break;
}
break;
}
case '/i/notes': {
if (params.qstring.args) {
try {
params.qstring.args = JSON.parse(params.qstring.args);
}
catch (SyntaxError) {
console.log('Parse ' + apiPath + ' JSON failed', params.req.url, params.req.body);
}
}
switch (paths[3]) {
case 'save':
validateCreate(params, 'core', () => {
countlyApi.mgmt.users.saveNote(params);
});
break;
case 'delete':
validateDelete(params, 'core', () => {
countlyApi.mgmt.users.deleteNote(params);
});
break;
}
break;
}
case '/i/app_users': {
switch (paths[3]) {
case 'create': {
if (!params.qstring.app_id) {
common.returnMessage(params, 400, 'Missing parameter "app_id"');
return false;
}
if (!params.qstring.data) {
common.returnMessage(params, 400, 'Missing parameter "data"');
return false;
}
else if (typeof params.qstring.data === "string") {
try {
params.qstring.data = JSON.parse(params.qstring.data);
}
catch (ex) {
console.log("Could not parse data", params.qstring.data);
common.returnMessage(params, 400, 'Could not parse parameter "data": ' + params.qstring.data);
return false;
}
}
if (!Object.keys(params.qstring.data).length) {
common.returnMessage(params, 400, 'Parameter "data" cannot be empty');
return false;
}
validateUserForWrite(params, function() {
countlyApi.mgmt.appUsers.create(params.qstring.app_id, params.qstring.data, params, function(err, res) {
if (err) {
common.returnMessage(params, 400, err);
}
else {
common.returnMessage(params, 200, 'User Created: ' + JSON.stringify(res));
}
});
});
break;
}
case 'update': {
if (!params.qstring.app_id) {
common.returnMessage(params, 400, 'Missing parameter "app_id"');
return false;
}
if (!params.qstring.update) {
common.returnMessage(params, 400, 'Missing parameter "update"');
return false;
}
else if (typeof params.qstring.update === "string") {
try {
params.qstring.update = JSON.parse(params.qstring.update);
}
catch (ex) {
console.log("Could not parse update", params.qstring.update);
common.returnMessage(params, 400, 'Could not parse parameter "update": ' + params.qstring.update);
return false;
}
}
if (!Object.keys(params.qstring.update).length) {
common.returnMessage(params, 400, 'Parameter "update" cannot be empty');
return false;
}
if (!params.qstring.query) {
common.returnMessage(params, 400, 'Missing parameter "query"');
return false;
}
else if (typeof params.qstring.query === "string") {
try {
params.qstring.query = JSON.parse(params.qstring.query);
}
catch (ex) {
console.log("Could not parse query", params.qstring.query);
common.returnMessage(params, 400, 'Could not parse parameter "query": ' + params.qstring.query);
return false;
}
}
validateUserForWrite(params, function() {
countlyApi.mgmt.appUsers.count(params.qstring.app_id, params.qstring.query, function(err, count) {
if (err || count === 0) {
common.returnMessage(params, 400, 'No users matching criteria');
return false;
}
if (count > 1 && !params.qstring.force) {
common.returnMessage(params, 400, 'This query would update more than one user');
return false;
}
countlyApi.mgmt.appUsers.update(params.qstring.app_id, params.qstring.query, params.qstring.update, params, function(err2) {
if (err2) {
common.returnMessage(params, 400, err2);
}
else {
common.returnMessage(params, 200, 'User Updated');
}
});
});
});
break;
}
case 'delete': {
if (!params.qstring.app_id) {
common.returnMessage(params, 400, 'Missing parameter "app_id"');
return false;
}
if (!params.qstring.query) {
common.returnMessage(params, 400, 'Missing parameter "query"');
return false;
}
else if (typeof params.qstring.query === "string") {
try {
params.qstring.query = JSON.parse(params.qstring.query);
}
catch (ex) {
console.log("Could not parse query", params.qstring.query);
common.returnMessage(params, 400, 'Could not parse parameter "query": ' + params.qstring.query);
return false;
}
}
if (!Object.keys(params.qstring.query).length) {
common.returnMessage(params, 400, 'Parameter "query" cannot be empty, it would delete all users. Use clear app instead');
return false;
}
validateUserForWrite(params, function() {
countlyApi.mgmt.appUsers.count(params.qstring.app_id, params.qstring.query, function(err, count) {
if (err || count === 0) {
common.returnMessage(params, 400, 'No users matching criteria');
return false;
}
if (count > 1 && !params.qstring.force) {
common.returnMessage(params, 400, 'This query would delete more than one user');
return false;
}
countlyApi.mgmt.appUsers.delete(params.qstring.app_id, params.qstring.query, params, function(err2) {
if (err2) {
common.returnMessage(params, 400, err2);
}
else {
common.returnMessage(params, 200, 'User deleted');
}
});
});
});
break;
}
/**
* @api {get} /i/app_users/deleteExport/:id Deletes user export.
* @apiName Delete user export
* @apiGroup App User Management
* @apiDescription Deletes user export.
*
* @apiParam {Number} id Id of export. For single user it would be similar to: appUser_644658291e95e720503d5087_1, but for multiple users - appUser_62e253489315313ffbc2c457_HASH_3e5b86cb367a6b8c0689ffd80652d2bbcb0a3edf
*
* @apiQuery {String} app_id Application id
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "result":"Export deleted"
* }
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 400 Bad Request
* {
* "result": "Missing parameter \"app_id\""
* }
*/
case 'deleteExport': {
validateUserForWrite(params, function() {
countlyApi.mgmt.appUsers.deleteExport(paths[4], params, function(err) {
if (err) {
common.returnMessage(params, 400, err);
}
else {
common.returnMessage(params, 200, 'Export deleted');
}
});
});
break;
}
/**
* @api {get} /i/app_users/export Exports all data collected about app user
* @apiName Export user data
* @apiGroup App User Management
*
* @apiDescription Creates export and stores in database. export is downloadable on demand.
* @apiQuery {String} app_id Application id
* @apiQuery {String} query Query to match users to run export on. Query should be runnable on mongodb database. For example: {"uid":"1"} will find user, for whuch uid === "1" If is possible to export also multiple users in same export.
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "result": "appUser_644658291e95e720503d5087_1.json"
* }
* @apiErrorExample {json} Error-Response:
* HTTP/1.1 400 Bad Request
* {
* "result": "Missing parameter \"app_id\""
* }
*/
case 'export': {
if (!params.qstring.app_id) {
common.returnMessage(params, 400, 'Missing parameter "app_id"');
return false;
}
validateUserForWrite(params, function() {
taskmanager.checkIfRunning({
db: common.db,
params: params //allow generate request from params, as it is what identifies task in drill
}, function(task_id) {
//check if task already running
if (task_id) {
common.returnOutput(params, {task_id: task_id});
}
else {
if (!params.qstring.query) {
common.returnMessage(params, 400, 'Missing parameter "query"');
return false;
}
else if (typeof params.qstring.query === "string") {
try {
params.qstring.query = JSON.parse(params.qstring.query);
}
catch (ex) {
console.log("Could not parse query", params.qstring.query);
common.returnMessage(params, 400, 'Could not parse parameter "query": ' + params.qstring.query);
return false;
}
}
var my_name = "";
if (params.qstring.query) {
my_name = JSON.stringify(params.qstring.query);
}
countlyApi.mgmt.appUsers.export(params.qstring.app_id, params.qstring.query || {}, params, taskmanager.longtask({
db: common.db,
threshold: plugins.getConfig("api").request_threshold,
force: false,
app_id: params.qstring.app_id,
params: params,
type: "AppUserExport",
report_name: "User export",
meta: JSON.stringify({
"app_id": params.qstring.app_id,
"query": params.qstring.query || {}
}),
name: my_name,
view: "#/exportedData/AppUserExport/",
processData: function(err, res, callback) {
if (!err) {
callback(null, res);
}
else {
callback(err, '');
}
},
outputData: function(err, data) {
if (err) {
common.returnMessage(params, 400, err);
}
else {
common.returnMessage(params, 200, data);
}
}
}));
}
});
});
break;
}
default:
if (!plugins.dispatch(apiPath, {
params: params,
validateUserForDataReadAPI: validateUserForDataReadAPI,
validateUserForMgmtReadAPI: validateUserForMgmtReadAPI,
paths: paths,
validateUserForDataWriteAPI: validateUserForDataWriteAPI,
validateUserForGlobalAdmin: validateUserForGlobalAdmin
})) {
common.returnMessage(params, 400, 'Invalid path, must be one of /all or /me');
}
break;
}
break;
}
case '/i/apps': {
if (params.qstring.args) {
try {
params.qstring.args = JSON.parse(params.qstring.args);
}
catch (SyntaxError) {
console.log('Parse ' + apiPath + ' JSON failed', params.req.url, params.req.body);
}
}
switch (paths[3]) {
case 'create':
validateUserForGlobalAdmin(params, countlyApi.mgmt.apps.createApp);
break;
case 'update':
if (paths[4] === 'plugins') {
validateAppAdmin(params, countlyApi.mgmt.apps.updateAppPlugins);
}
else {
if (params.qstring.app_id) {
validateAppAdmin(params, countlyApi.mgmt.apps.updateApp);
}
else {
validateUserForGlobalAdmin(params, countlyApi.mgmt.apps.updateApp);
}
}
break;
case 'delete':
validateUserForGlobalAdmin(params, countlyApi.mgmt.apps.deleteApp);
break;
case 'reset':
validateUserForGlobalAdmin(params, countlyApi.mgmt.apps.resetApp);
break;
default:
if (!plugins.dispatch(apiPath, {
params: params,
validateUserForDataReadAPI: validateUserForDataReadAPI,
validateUserForMgmtReadAPI: validateUserForMgmtReadAPI,
paths: paths,
validateUserForDataWriteAPI: validateUserForDataWriteAPI,
validateUserForGlobalAdmin: validateUserForGlobalAdmin
})) {
common.returnMessage(params, 400, 'Invalid path, must be one of /create, /update, /delete or /reset');
}
break;
}
break;
}
case '/i/event_groups':
switch (paths[3]) {
case 'create':
validateCreate(params, 'core', countlyApi.mgmt.eventGroups.create);
break;
case 'update':
validateUpdate(params, 'core', countlyApi.mgmt.eventGroups.update);
break;
case 'delete':
validateDelete(params, 'core', countlyApi.mgmt.eventGroups.remove);
break;
default:
break;
}
break;
case '/i/tasks': {
if (!params.qstring.task_id) {
common.returnMessage(params, 400, 'Missing parameter "task_id"');
return false;
}
switch (paths[3]) {
case 'update':
validateUserForWrite(params, () => {
taskmanager.rerunTask({
db: common.db,
id: params.qstring.task_id
}, (err, res) => {
common.returnMessage(params, 200, res);
});
});
break;
case 'stop':
validateUserForWrite(params, () => {
taskmanager.stopTask({
db: common.db,
id: params.qstring.task_id,
op_id: params.qstring.op_id
}, (err, res) => {
common.returnMessage(params, 200, res);
});
});
break;
case 'delete':
validateUserForWrite(params, () => {
taskmanager.deleteResult({
db: common.db,
id: params.qstring.task_id
}, (err, task) => {
plugins.dispatch("/systemlogs", {params: params, action: "task_manager_task_deleted", data: task});
common.returnMessage(params, 200, "Success");
});
});
break;
case 'name':
validateUserForWrite(params, () => {
taskmanager.nameResult({
db: common.db,
id: params.qstring.task_id,
name: params.qstring.name
}, () => {
common.returnMessage(params, 200, "Success");
});
});
break;
case 'edit':
validateUserForWrite(params, () => {
const data = {
"report_name": params.qstring.report_name,
"report_desc": params.qstring.report_desc,
"global": params.qstring.global + "" === 'true',
"autoRefresh": params.qstring.autoRefresh + "" === 'true',
"period_desc": params.qstring.period_desc
};
taskmanager.editTask({
db: common.db,
data: data,
id: params.qstring.task_id
}, (err, d) => {
if (err) {
common.returnMessage(params, 503, "Error");
}
else {
common.returnMessage(params, 200, "Success");
}
plugins.dispatch("/systemlogs", {params: params, action: "task_manager_task_updated", data: d});
});
});
break;
default:
if (!plugins.dispatch(apiPath, {
params: params,
validateUserForDataReadAPI: validateUserForDataReadAPI,
validateUserForMgmtReadAPI: validateUserForMgmtReadAPI,
paths: paths,
validateUserForDataWriteAPI: validateUserForDataWriteAPI,
validateUserForGlobalAdmin: validateUserForGlobalAdmin
})) {
common.returnMessage(params, 400, 'Invalid path');
}
break;
}
break;
}
case '/i/events': {
switch (paths[3]) {
case 'whitelist_segments':
{
validateUpdate(params, "events", function() {
common.db.collection('events').findOne({"_id": common.db.ObjectID(params.qstring.app_id)}, function(err, event) {
if (err) {
common.returnMessage(params, 400, err);
return;
}
else if (!event) {
common.returnMessage(params, 400, "Could not find record in event collection");
return;
}
//rewrite whitelisted
if (params.qstring.whitelisted_segments && params.qstring.whitelisted_segments !== "") {
try {
params.qstring.whitelisted_segments = JSON.parse(params.qstring.whitelisted_segments);
}
catch (SyntaxError) {
params.qstring.whitelisted_segments = {}; console.log('Parse ' + params.qstring.whitelisted_segments + ' JSON failed', params.req.url, params.req.body);
}
var update = {};
var whObj = params.qstring.whitelisted_segments;
for (let k in whObj) {
if (Array.isArray(whObj[k]) && whObj[k].length > 0) {
update.$set = update.$set || {};
update.$set["whitelisted_segments." + k] = whObj[k];
}
else {
update.$unset = update.$unset || {};
update.$unset["whitelisted_segments." + k] = true;
}
}
common.db.collection('events').update({"_id": common.db.ObjectID(params.qstring.app_id)}, update, function(err2) {
if (err2) {
common.returnMessage(params, 400, err2);
}
else {
var data_arr = {update: {}};
if (update.$set) {
data_arr.update.$set = update.$set;
}
if (update.$unset) {
data_arr.update.$unset = update.$unset;
}
data_arr.update = JSON.stringify(data_arr.update);
common.returnMessage(params, 200, 'Success');
plugins.dispatch("/systemlogs", {
params: params,
action: "segments_whitelisted_for_events",
data: data_arr
});
}
});
}
else {
common.returnMessage(params, 400, "Value for 'whitelisted_segments' missing");
return;
}
});
});
break;
}
case 'edit_map':
{
if (!params.qstring.app_id) {
common.returnMessage(params, 400, 'Missing parameter "app_id"');
return false;
}
validateUpdate(params, 'events', function() {
common.db.collection('events').findOne({"_id": common.db.ObjectID(params.qstring.app_id)}, function(err, event) {
if (err) {
common.returnMessage(params, 400, err);
return;
}
else if (!event) {
common.returnMessage(params, 400, "Could not find event");
return;
}
var update_array = {};
var update_segments = [];
var pull_us = {};
if (params.qstring.event_order && params.qstring.event_order !== "") {
try {
update_array.order = JSON.parse(params.qstring.event_order);
}
catch (SyntaxError) {
update_array.order = event.order; console.log('Parse ' + params.qstring.event_order + ' JSON failed', params.req.url, params.req.body);