-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1082 lines (902 loc) · 40 KB
/
index.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
"use strict";
const Application = require("neat-base").Application;
const Module = require("neat-base").Module;
const Tools = require("neat-base").Tools;
const redis = require("redis");
const apeStatus = require('ape-status');
const Promise = require("bluebird");
const crypto = require('crypto');
const fs = require('fs');
const pathToRegexp = require('path-to-regexp');
module.exports = class Api extends Module {
static defaultConfig() {
return {
loginPath: "/login",
elementsModuleName: "elements",
webserverModuleName: "webserver",
projectionModuleName: "projection",
cacheModuleName: "cache",
dbModuleName: "database",
authModuleName: "auth",
};
}
init() {
return new Promise((resolve, reject) => {
this.log.debug("Initializing...");
if (Application.modules[this.config.webserverModuleName]) {
Application.modules[this.config.webserverModuleName].addRoute("post", "/api/:model/:action", (req, res, next) => {
this.handleRequest(req, res);
}, 9999);
Application.modules[this.config.webserverModuleName].addRoute("get", "/api/:model/changes/:type/:projection/:from?/:to?", (req, res, next) => {
this.handleChangesRequest(req, res);
}, 9999);
}
return this.loadStaticPages().then(() => {
return resolve(this);
});
});
}
handleRequest(req, res) {
let model, userModel;
try {
model = Application.modules[this.config.dbModuleName].getModel(req.params.model);
} catch (e) {
res.status(400);
return res.err("model " + req.params.model + " does not exist");
}
try {
userModel = Application.modules[this.config.dbModuleName].getModel("user");
} catch (e) {
}
let mongoose = Application.modules[this.config.dbModuleName].mongoose;
let limit = req.body.limit || 10;
let page = req.body.page || 0;
let sort = req.body.sort || {};
let query = req.body.query || {};
let select = req.body.select || {};
let field = req.body.field || null;
let populate = req.body.populate || [];
let projection = req.body.projection || null;
let dbQuery;
let data = req.body.data;
let isFilteringForOwnData = query._createdBy && req.user && query._createdBy + "" === req.user._id + "";
switch (req.params.action) {
case "find":
if (Application.modules[this.config.authModuleName]) {
if (!Application.modules[this.config.authModuleName].hasPermission(req, req.params.model, req.params.action)) {
return res.status(401).end();
}
}
dbQuery = model.find(query).limit(limit).skip(limit * page).populate(populate).select(select).sort(sort);
// if the request didn't ask for a projection allow this only if the user has either complete access to the model or the specific action permission
if (!projection) {
if ((!req.user || !req.user.hasPermission([
req.params.model,
req.params.model + "." + req.params.action,
])) && !isFilteringForOwnData) {
return res.status(401).end("No projection given or no permission to use this projection. Or the projection is missing in the config...");
}
} else if (projection && Application.modules[this.config.projectionModuleName]) {
// check if the current user has permission to use this projection
if (!Application.modules[this.config.projectionModuleName].hasPermission(req.user, req.params.model, projection)) {
return res.status(401).end("No projection given or no permission to use this projection");
}
dbQuery.projection(projection, req);
}
dbQuery.exec().then((docs) => {
res.json(docs);
}, (err) => {
res.err(err);
});
break;
case "findOne":
if (Application.modules[this.config.authModuleName]) {
if (!Application.modules[this.config.authModuleName].hasPermission(req, req.params.model, req.params.action)) {
return res.status(401).end();
}
}
dbQuery = model.findOne(query).select(select).sort(sort).populate(populate);
if (projection && Application.modules[this.config.projectionModuleName]) {
dbQuery.projection(projection, req);
}
dbQuery.exec().then((doc) => {
res.json(doc);
}, (err) => {
res.err(err);
});
break;
case "versions":
if (Application.modules[this.config.authModuleName]) {
if (!Application.modules[this.config.authModuleName].hasPermission(req, req.params.model, req.params.action)) {
return res.status(401).end();
}
}
if (populate && populate.length) {
select = null;
}
model.findOne(query).select(select).sort(sort).then((doc) => {
return Promise.map(doc.get("_versions"), (obj) => {
if (select) {
return obj;
} else {
let doc = new model(obj);
return doc.populate(populate).execPopulate();
}
}).then((docs) => {
return res.json(docs);
});
}, (err) => {
res.err(err);
});
break;
case "unpublished":
if (!req.body._ids || !req.body._ids instanceof Array) {
return res.json([]);
}
model.find({}).lean(true).select({_id: 1}).then((docs) => {
let existing = docs.map((v) => v._id + "");
let deleted = req.body._ids.filter(function (id) {
return existing.indexOf(id) === -1;
});
res.json(deleted);
});
break;
case "count":
if (Application.modules[this.config.authModuleName]) {
if (!Application.modules[this.config.authModuleName].hasPermission(req, req.params.model, req.params.action)) {
return res.status(401).end();
}
}
model.count(query).then((count) => {
res.end(count.toString());
}, (err) => {
res.err(err);
});
break;
case "update":
if (Application.modules[this.config.authModuleName]) {
if (!Application.modules[this.config.authModuleName].hasPermission(req, req.params.model, "save")) {
return res.status(401).end();
}
}
if (userModel && req.user) {
userModel.update({
_id: req.user._id,
}, {
$set: {
lastActivity: new Date(),
},
}).then(() => {
this.log.debug("User Activity updated");
}, () => {
this.log.debug("User Activity update failed");
});
}
data = this.cleanupDataForSave(data, model, req.user);
if (!data) {
return res.err(new Error("no data"), 400);
}
model.update(query, {
$set: data,
}, {
multi: true,
}).then(() => {
res.json({});
}, (err) => {
res.err(err);
});
break;
case "save":
let getPromise = Promise.resolve();
let saveChildDocs = [];
let isUpdate = false;
data = this.cleanupDataForSave(data, model, req.user, true);
if (!data) {
return res.err(new Error("no data"), 400);
}
if (data._id) {
getPromise = model.findOne({
_id: data._id,
});
}
getPromise.then((doc) => {
if (!doc) {
doc = new model(data);
doc.set("_createdBy", req.user ? req.user._id : null);
} else {
isUpdate = true;
for (let key in data) {
if (field === "__v" || field === "_id") {
continue;
}
doc.set(key, data[key]);
}
doc.set("_updatedBy", req.user ? req.user._id : null);
}
if (Application.modules[this.config.authModuleName]) {
if (!Application.modules[this.config.authModuleName].hasPermission(req, req.params.model, req.params.action, doc)) {
return res.status(401).end();
}
}
if (userModel && req.user) {
userModel.update({
_id: req.user._id,
}, {
$set: {
lastActivity: new Date(),
},
}).then(() => {
this.log.debug("User Activity updated");
}, () => {
this.log.debug("User Activity update failed");
});
}
if (req.body.saveReferences) {
if (!(req.body.saveReferences instanceof Array)) {
return res.err(new Error("saveReferences must be an Array with schema paths"));
}
return Promise.map(req.body.saveReferences, (path) => {
let pathConfig = model.schema.paths[path];
if (!pathConfig) {
throw new Error("path " + path + " does not exist");
}
if (pathConfig instanceof mongoose.Schema.Types.Array && pathConfig.caster instanceof mongoose.Schema.Types.ObjectId) {
// path is an array, we need to save multiple things
let relatedModel = Application.modules[this.config.dbModuleName].getModel(pathConfig.caster.options.ref);
let subdata = data[path];
// If not array make one
if (!Array.isArray(subdata)) {
subdata = [subdata].filter(v => !!v);
}
return Promise.map(subdata, (subdata, index) => {
subdata = this.cleanupDataForSave(subdata, relatedModel, req.user);
let itemDoc;
let itemPromise = Promise.resolve();
if (subdata._id) {
itemPromise = relatedModel.findOne({
_id: subdata._id,
});
}
return itemPromise.then((tempItemDoc) => {
if (!tempItemDoc) {
delete subdata._id;
tempItemDoc = new relatedModel(subdata);
}
itemDoc = tempItemDoc;
for (let field in subdata) {
if (field === "__v" || field === "_id") {
continue;
}
itemDoc.set(field, subdata[field]);
}
let err = itemDoc.validateSync();
if (err) {
return Promise.reject(err);
}
return Promise.resolve();
}).then(() => {
return itemDoc;
}, (err) => {
let formatted = Tools.formatMongooseError(err);
let childFormatted = {};
for (let key in formatted) {
childFormatted[path + "." + index + "." + key] = formatted[key];
}
let newErr = Error("child error");
newErr.formatted = childFormatted;
throw newErr;
});
}).then((docs) => {
doc.set(path, docs);
saveChildDocs = saveChildDocs.concat(docs);
});
} else if (pathConfig instanceof mongoose.Schema.Types.ObjectId) {
// path is a single reference
let relatedModel = Application.modules[this.config.dbModuleName].getModel(pathConfig.options.ref);
let subdata = data[path];
subdata = this.cleanupDataForSave(subdata, relatedModel, req.user);
let itemDoc;
let itemPromise = Promise.resolve();
if (subdata._id) {
itemPromise = relatedModel.findOne({
_id: subdata._id,
});
}
return itemPromise.then((tempItemDoc) => {
if (!tempItemDoc) {
delete subdata._id;
tempItemDoc = new relatedModel(subdata);
}
itemDoc = tempItemDoc;
for (let field in subdata) {
if (field === "__v" || field === "_id") {
continue;
}
itemDoc.set(field, subdata[field]);
}
// don't save yet! - prevents saving of child docs when parent doc throws an save error
let err = itemDoc.validateSync();
if (err) {
return Promise.reject(err);
}
return Promise.resolve();
}).then(() => {
doc.set(path, itemDoc._id);
saveChildDocs.push(itemDoc);
}, (err) => {
let formatted = Tools.formatMongooseError(err, this.config.autoTranslateErrors ? req.__ : null);
let childFormatted = {};
for (let key in formatted) {
childFormatted[path + "." + key] = formatted[key];
}
let newErr = Error("child error");
newErr.formatted = childFormatted;
throw newErr;
});
} else {
this.log.warn("path " + path + " is not a supported reference to save");
return;
}
}).then(() => {
let saveChildDocsPromise = Promise.resolve();
let err = doc.validateSync();
if (err) {
return res.err(err);
}
if (saveChildDocs.length) {
saveChildDocsPromise = Promise.map(saveChildDocs, (childDoc) => {
return childDoc.save();
});
}
return saveChildDocsPromise.then(() => {
return doc.save().then(() => {
return model.findOne({
_id: doc._id,
}).read("primary").populate(populate);
}).then((newDoc) => {
res.json(newDoc.toObject({virtuals: true, getters: true}));
}).catch((err) => {
res.err(err);
});
}).catch((err) => {
res.err(err);
});
}, (err) => {
if (err.formatted) {
res.status(400);
return res.json(err.formatted);
}
res.err(err);
});
} else {
return doc.save().then(() => {
return model.findOne({
_id: doc._id,
}).read("primary").populate(populate);
}, (err) => {
throw err;
}).then((newDoc) => {
res.json(newDoc.toObject({virtuals: true, getters: true}));
}, (err) => {
res.err(err);
});
}
});
break;
case "remove":
if (Application.modules[this.config.authModuleName]) {
if (!Application.modules[this.config.authModuleName].hasPermission(req, req.params.model, req.params.action, null, query)) {
return res.status(401).end();
}
}
if (Object.keys(query).length === 0) {
return res.status(401).end("Empty query is not allowed");
}
if (userModel && req.user) {
userModel.update({
_id: req.user._id,
}, {
$set: {
lastActivity: new Date(),
},
}).then(() => {
this.log.debug("User Activity updated");
}, () => {
this.log.debug("User Activity update failed");
});
}
model.find(query).then((docs) => {
return Promise.map(docs, (doc) => {
return doc.remove();
});
}, (err) => {
res.err(err);
}).then(() => {
res.end();
}, (err) => {
res.err(err);
});
break;
case "pagination":
if (Application.modules[this.config.authModuleName]) {
if (!Application.modules[this.config.authModuleName].hasPermission(req, req.params.model, "count", null, query)) {
return res.status(401).end();
}
}
model.count(req.body.query || {}).then((count) => {
res.json(Tools.getPaginationForCount(count, req.body.limit || 15, req.body.page, req.body.pagesInView, req));
}, (err) => {
res.err(err);
});
break;
case "schema":
if (Application.modules[this.config.authModuleName]) {
if (!Application.modules[this.config.authModuleName].hasPermission(req, req.params.model, "schema", null, query)) {
return res.status(401).end();
}
}
return this.getSchemaForModel(model).then((data) => {
res.json(data);
}, (err) => {
res.err(err);
});
break;
case "dropdownoptions":
if (Application.modules[this.config.authModuleName]) {
if (!Application.modules[this.config.authModuleName].hasPermission(req, req.params.model, "find", null, query)) {
return res.status(401).end();
}
}
let preAggregateQuery = query;
let aggregateProject = {};
let sortDir = req.body.sortDir || 1;
let purgeEmpty = req.body.purgeEmpty || true;
preAggregateQuery[field] = {
$exists: true,
};
aggregateProject._id = "$" + field;
aggregateProject.sortKey = {
$toLower: "$" + field,
};
return model.aggregate([
{
$match: preAggregateQuery,
},
{
$project: aggregateProject,
},
{
$group: {
_id: "$_id",
sortKey: {
$first: "$sortKey",
},
},
},
{
$sort: {
sortKey: sortDir,
},
},
]).then((results) => {
let _ids = results.map(v => v._id);
if (purgeEmpty) {
_ids = _ids.filter(v => !!v);
}
res.json(_ids);
}, (err) => {
res.err(err);
});
break;
default:
res.status(501);
res.end();
break;
}
}
/**
* /api/:model/changes/:type/:projection/:from?/:to?
*
* @param req
* @param res
*/
handleChangesRequest(req, res) {
let supportedTypes = ["json"];
let type = req.params.type;
if (supportedTypes.indexOf(type) === -1) {
res.status(400);
return res.err("type " + type + " not supported, try on of the following" + supportedTypes.join(","));
}
let projection = req.params.projection;
let from = req.params.from;
let to = req.params.to;
let count = req.query.count;
let hasPublish = Application.modules[this.config.projectionModuleName].config.publish[req.params.model];
let publishedModel;
let query;
if (hasPublish) {
publishedModel = Application.modules[this.config.dbModuleName].getModel("published");
query = {
model: req.params.model,
projection: projection,
$and: [],
};
} else {
publishedModel = Application.modules[this.config.dbModuleName].getModel(req.params.model);
query = {};
}
let limit = req.query.limit;
let page = req.query.page;
if (from) {
from = new Date(from);
}
if (to) {
to = new Date(to);
}
if (from) {
query.$and.push({
_updatedAt: {
$gte: from,
},
});
}
if (to) {
query.$and.push({
_updatedAt: {
$lte: to,
},
});
}
if (query.$and && query.$and.length === 0) {
delete query.$and;
}
if (hasPublish) {
if (count) {
return publishedModel
.count(query).then((count) => {
res.json({
total: count,
});
}, (err) => {
res.status(500).end(err);
});
}
if (page !== undefined) {
page = parseInt(page) || 0;
limit = parseInt(limit) || 100;
return publishedModel
.find(query)
.lean(true)
.skip(page * limit)
.limit(limit)
.exec().then((data) => {
res.json(data);
}, (err) => {
res.status(500).end(err);
});
}
let lastData = null;
if (type === "json") {
res.header("Content-Type", "application/json;charset=UTF-8");
}
res.write("[");
publishedModel
.find(query)
.lean(true)
.cursor()
.on('data', function (data) {
if (lastData) {
res.write(",");
}
lastData = true;
res.write(JSON.stringify(data.data));
})
.on('end', function () {
res.write("]");
res.end();
});
} else {
if (count) {
return publishedModel
.count(query)
.then((count) => {
res.json({
total: count,
});
}, (err) => {
res.status(500).end(err);
});
}
page = parseInt(page) || 0;
limit = parseInt(limit) || 100;
return publishedModel
.find(query)
.projection(req.params.projection)
.skip(page * limit)
.limit(limit)
.exec().then((data) => {
res.json(data);
}, (err) => {
res.status(500).end(err);
});
}
}
/**
*
* @param {{}} data
* @param {Model} model
* @param {Document} user
* @returns {{}}
*/
cleanupDataForSave(data, model, user, maintainSubDocs) {
if (!data) {
return null;
}
// remove __v by default, you cant update it anyways, do it here so we dont get any warnings
delete data.__v;
// save means new version, so in case any version was submitted, just reset it
data._version = null;
let mongoose = Application.modules[this.config.dbModuleName].mongoose;
let forbiddenPaths = [];
let paths = model.schema.paths;
let modelName = new model().constructor.modelName; // @TODO really isnt there a better way? wasted...
// checks paths for non public paths
for (let path in paths) {
let pathConfig = paths[path];
if (pathConfig.options.permission === undefined) {
// no permission option set, so if other permissions are ok he might modify this field
} else if (pathConfig.options.permission === false) {
// no permission, check for the required permissions
if (!user) {
// no user ? no permission ! probably wont get past the check in api/save anyways...
forbiddenPaths.push(path);
} else if (!user.hasPermission([
modelName,
modelName + ".save",
])) {
// no general or specific save permission
forbiddenPaths.push(path);
}
} else if (typeof pathConfig.options.permission === "string") {
// specific permission to modify this field
if (!user.hasPermission(pathConfig.options.permission)) {
forbiddenPaths.push(path);
}
}
}
// @TODO ok we get more creative here, feel free to refactor...
let tempDoc = new model(data); // make temp model just to have access to mongoose functionality
let finalData = {};
for (let path in paths) {
let pathConfig = paths[path];
// check if the user is not allowed to modify this path
if (forbiddenPaths.indexOf(path) !== -1) {
this.log.debug("Ignored path " + path + " for save, insufficient permissions");
continue;
}
// check if this path is a reference, if so completely ignore it, dont modify it at all!
if (pathConfig instanceof mongoose.Schema.Types.ObjectId || (pathConfig instanceof mongoose.Schema.Types.Array && pathConfig.caster instanceof mongoose.Schema.Types.ObjectId)) {
finalData[path] = Tools.getObjectValueByPath(data, path); // get it from the original data, this is required since the model will just return the id
if (finalData[path] === null) {
delete finalData[path];
}
continue;
}
if (!tempDoc.isModified(path) && path !== "_id") {
continue;
}
finalData[path] = tempDoc.get(path);
}
// this is important, otherwise _id will be null so things will be reeeeeaaaaally weird
if (!finalData._id) {
delete finalData._id;
}
return finalData;
}
start() {
return new Promise((resolve, reject) => {
this.log.debug("Starting...");
return resolve(this);
});
}
stop() {
return new Promise((resolve, reject) => {
this.log.debug("Stopping...");
return resolve(this);
});
}
loadStaticPages() {
return new Promise((resolve, reject) => {
let rootDir = Application.config.config_path + "/pages";
if (!fs.existsSync(rootDir)) {
fs.mkdirSync(rootDir);
}
let files = fs.readdirSync(rootDir);
let pages = {};
for (let i = 0; i < files.length; i++) {
let file = files[i];
if (file.indexOf(".json") === -1) {
continue;
}
let config = Tools.loadCommentedConfigFile(rootDir + "/" + file);
for (let key in config) {
if (pages[key]) {
this.log.warn("Page " + key + " duplicated");
}
pages[key] = config[key];
}
}
this.pages = pages;
resolve();
});
}
getSchemaForModel(model) {
let cleanSchema = {};
return new Promise((resolve, reject) => {
for (let key in model.schema.paths) {
let conf = JSON.parse(JSON.stringify(model.schema.paths[key]));
if (!conf) {
continue;
}
cleanSchema[key] = {
enumValues: conf.enumValues || conf.options.enum || (conf.caster ? conf.caster.enumValues : null),
regExp: conf.regExp,
path: conf.path,
instance: conf.instance,
defaultValue: conf.defaultValue || conf.options.default || null,
map: conf.options.map || null,
};
}
resolve(cleanSchema);
});
}
getPageFromRequest(req) {
for (let key in this.pages) {
let page = this.pages[key];
page.id = key;
if (page.regexp) {
if (new RegExp("^" + page.path + "$").test(req.path)) {
return page;
}
}
let keys = [];
let re = pathToRegexp(page.path, keys);
let result = re.exec(req.path);
if (result) {
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
req.params[key.name] = result[i + 1];
}
req.activePage = page;
return page;
}
}
}
getPageJson(req, page) {
return new Promise((resolve, reject) => {
page = page || this.getPageFromRequest(req);
if (!page) {
return this.getPageJson(req, this.pages[404]).then(resolve, reject);
}
req.activePage = page;
if (page && page.requires && page.requires.auth) {
if (!req.user) {
return resolve({
status: 302,
redirect: this.config.loginPath + "?return=" + req.path,
});
}
if (page.requires.permissions && !req.user.admin) {
if (typeof page.requires.permissions === "string") {
page.requires.permissions = [page.requires.permissions];
}
for (let i = 0; i < page.requires.permissions.length; i++) {
let permission = page.requires.permissions[i];
if (req.user.permissions.indexOf(permission) === -1) {
let redirect = this.config.loginPath + "?return=" + req.path;
let redirectPermissions = page.requires.redirectPermissions || {};
for (let [redirectPermission, link] of Object.entries(redirectPermissions)) {
if (req.user.permissions.indexOf(redirectPermission) !== -1) {
redirect = link;
break;
}
}
return resolve({
status: 302,
redirect: redirect,
});
}
}
}
}
let status = page.status || 200;
let pagePreparationPromise = Promise.resolve();
let stats = {};
if (page.model) {
pagePreparationPromise = new Promise((pageItemResolve, reject) => {
let pageItemModel = Application.modules[this.config.dbModuleName].getModel(page.model.name);
if (pageItemModel.schema.paths._id && pageItemModel.schema.paths._id.instance === "ObjectID") {
try {
Application.modules[this.config.dbModuleName].mongoose.Types.ObjectId(req.params._id);
} catch (e) {
// invalid id => 404
return this.getPageJson(req, this.pages[404]).then(resolve, reject);
}
}
let query = pageItemModel.findOne({
_id: req.params._id,
}).populate(page.model.populate || []);
if (page.model.projection) {
query.projection(page.model.projection, req);
}
return query.then((doc) => {
if (!doc) {
this.log.debug("No Document found in model " + page.model.name + " for id " + req.params._id);
return this.getPageJson(req, this.pages[404]).then(resolve, reject);
}