-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtemplates.js
504 lines (409 loc) · 14.8 KB
/
templates.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
var io = require('./io');
var modm = require('modm');
// ******************************
// Constants
// ******************************
var CORE_TEMPLATE_IDS = {
templates: '000000000000000000000000'
};
var PRIVATE_FIELDS = {
_tp: 1,
_li: 1,
db: 1,
collection: 1,
itemAccess: 1,
linkedFields: 1
};
var ROLE_CONFIGURABLE_FIELDS = {
options: 1,
links: 1,
schema: 1
};
var _modmCache = {};
// ******************************
// Templates
// ******************************
// template cache
var templateCache = {};
// init the templates config
function init (params, callback) {
// check preconditions
if (!params.templateConfig) {
var err = new Error('Missing template configuration on init operation')
err.statusCode = 400;
return link.send(err.statusCode, err);
}
if (!params.templateConfig.db) {
var err = new Error('Database name missing from template configuration');
err.statusCode = 400;
return callback(err);
}
var dbName = params.templateConfig.db;
var templateColName = params.templateConfig.collection || 'd_templates';
var config = {
dbName: dbName, // TODO handle with datasources
roleTemplateId: modm.ObjectId('000000000000000000000002'),
templateColName: templateColName, // TODO handle with datasources
templateSchema: {
_id: {type: 'objectid'},
_tp: {type: 'objectid', required: true},
_li: [{type: 'objectid'}],
db: {type: 'string', required: true},
collection: {type: 'string', required: true},
roles: {type: 'object', required: true},
itemAccess: {type: 'string'},
name: {type: 'string', required: true},
schema: {type: 'object', required: true},
links: {type: 'array'},
options: {type: 'object'}
}
};
var templateSchema = new modm.Schema(config.templateSchema);
// template's template must be in the cache, otherwise
// it's impossible to create the first template item
templateCache[CORE_TEMPLATE_IDS.templates] = {
_id: modm.ObjectId(CORE_TEMPLATE_IDS.templates),
_modm: {
db: _modmCache[config.dbName] = modm(config.dbName, {
server: {poolSize: 3},
db: {w: 1}
})
},
db: config.dbName,
collection: config.templateColName,
roles: {
'*': {
access: 'r'
}
},
itemAccess: 'crud',
label: 'Templates',
schema: templateSchema.paths
};
// init collection
templateCache[CORE_TEMPLATE_IDS.templates]._modm.collection = templateCache[CORE_TEMPLATE_IDS.templates]._modm.db(config.templateColName, templateSchema);
// done
callback(null);
}
// ******************************
// Exports
// ******************************
M.on('crud.getTemplate', getTemplate);
exports.init = init;
exports.getTemplate = getTemplate;
exports.getTemplates = getTemplates;
exports.getMergeTemplates = getMergeTemplates;
exports.getAccessKey = getAccessKey;
exports.CORE_TEMPLATE_IDS = CORE_TEMPLATE_IDS;
// ******************************
// Public functions
// ******************************
// called from the model.js to check template access
function getTemplate (request, callback) {
var templateRequest = {
query: [request.templateId],
options: request.options,
role: request.role,
method: request.method
};
fetchTemplates(templateRequest, function (err, template) {
if (err) {
err.statusCode = err.statusCode || 500;
return callback(err);
}
if (!template || !template.length) {
err = new Error('Templates not found.');
err.statusCode = 404;
return callback(err);
}
if (template[0].roles)
request.template = template[0];
callback(null, request);
});
}
// get templates for joins
function getMergeTemplates (request, role, callback) {
request = {
query: request.length ? request : [],
role: role,
method: 'read'
};
fetchTemplates(request, function (err, templates) {
if (err) {
return callback(err);
}
callback(null, templates);
});
}
// special function when requesting template items
function getTemplates (request, callback) {
fetchTemplates(request, function (err, templates) {
if (err) {
return callback(err);
}
var result = [];
for (var i = 0, l = templates.length, admin; i < l; ++i) {
result[i] = {};
// return full template if user has admin rigths
admin = false;
if (templates[i].roles[request.role] && templates[i].roles[request.role].access.match(/c|u|d/)) {
admin = true;
}
// delete private fields from result templates
for (var field in templates[i]) {
if ((admin || !PRIVATE_FIELDS[field]) && field !== '_modm') {
// clone for template parts that will be modified
if (['roles'].indexOf(field) !== -1) {
result[i][field] = JSON.parse(JSON.stringify(templates[i][field]));
for (var roleId in result[i][field]) {
if (roleId != request.role) {
delete result[i][field][roleId];
}
}
}
else {
result[i][field] = templates[i][field];
}
}
}
// we must overwrite the template with the role configuration
if (templates[i].roles[request.role] && templates[i].roles[request.role].config) {
mergeRoleTemplateConfig(result[i], templates[i].roles[request.role].config);
}
// leave only the user role in this template
for (var role in result[i].roles) {
if (role != request.role) {
delete result[i].roles[role];
}
}
}
callback(null, result);
});
}
// the access key for a crud operation is the first letter of the method
function getAccessKey (method) {
return typeof method === 'string' ? method[0] : undefined;
}
// ******************************
// Private functions
// ******************************
// check access
function checkAccess (template, role, method) {
// grant access for templates without roles or for the role wildcard
if (!template.roles || (template.roles['*'] && typeof template.roles['*'].access === 'string' && template.roles['*'].access.indexOf(getAccessKey(method)) > -1)) {
return true;
}
// check if role has read rights
if (template.roles[role] && typeof template.roles[role].access === 'string' && template.roles[role].access.indexOf(getAccessKey(method)) > -1) {
return true;
}
return false;
}
function initAndCache (template) {
if (templateCache[template._id.toString()]) {
return templateCache[template._id];
}
// save modm instance on template
template._modm = {
model: _modmCache[template.db] || (_modmCache[template.db] =
modm(template.db, {
server: {poolSize: 3},
db: {w: 1}
}))
};
// add mandatory field _tp
template.schema._tp = {
type: 'objectid',
required: true
};
// add mandatory field _id
template.schema._id = {
type: 'objectid',
required: true
};
// add mandatory field _li
template.schema._li = [{
type: 'objectid'
}];
template._modm.schema = new modm.Schema(template.schema);
template._modm.collection = template._modm.model(template.collection, template._modm.schema);
template.schema = template._modm.schema.paths;
// collect all links for faster access
for (var field in template.schema) {
if (template.schema[field].link) {
if (!template.linkedFields) {
template.linkedFields = {};
}
template.linkedFields[field] = template.schema[field];
}
}
templateCache[template._id] = template;
return templateCache[template._id];
}
function getCachedTemplates (templates, role, method) {
var result = {
query: [],
cached: []
}
var addedTemplates = {};
for (var i in templates) {
// check if template is in cache
if (templateCache[templates[i]]) {
// check role access
if (checkAccess(templateCache[templates[i]], role, method)) {
// if this role has a special template configuration
if (templateCache[templates[i]].roles[role] && templateCache[templates[i]].roles[role].config) {
// we must build new template objects in order not to affect
// the cache with the role configurations
var partialClone = {};
// built the partial template clone
for (var key in templateCache[templates[i]]) {
// the non configurable template properties are copied as reference
if (!ROLE_CONFIGURABLE_FIELDS[key]) {
partialClone[key] = templateCache[templates[i]][key];
}
// the configurable template properties must be cloned
else {
partialClone[key] = cloneJSON(templateCache[templates[i]][key]);
}
}
// noe we can safely merge the role config without affcting the cache
mergeRoleTemplateConfig(partialClone, templateCache[templates[i]].roles[role].config);
result.cached.push(partialClone);
}
// otherwise we are safe to pass the cached template reference
else {
result.cached.push(templateCache[templates[i]]);
}
}
}
// add template to query
else if (!addedTemplates[templates[i]]) {
addedTemplates[templates[i]] = true;
result.query.push(templates[i]);
}
}
return result;
}
function fetchTemplates (request, callback) {
if (!request.query) {
return callback('No templates to fetch.');
}
if (!templateCache[CORE_TEMPLATE_IDS.templates]) {
return callback('Core templates not initialized');
}
// build query
var dbReq = {
query: {},
options: {},
template: templateCache[CORE_TEMPLATE_IDS.templates]
};
var oldCached = {};
// [] => check cache then fetch
if (request.query.constructor.name === 'Array') {
oldCached = getCachedTemplates(request.query, request.role, request.method);
// return if no templates must be fetched from db
if (oldCached.query.length === 0) {
return callback(null, oldCached.cached);
}
// convert the string IDs into ObjectId's
for (var i = 0; i < oldCached.query.length; ++i) {
if (typeof oldCached.query[i] === 'string') {
oldCached.query[i] = modm.ObjectId(oldCached.query[i]);
}
}
dbReq.query._id = { $in: oldCached.query };
dbReq.options.limit = oldCached.query.length;
}
// {} => fetch then check cache
// TODO handle $in queries with cache
else if (request.query.constructor.name === 'Object') {
oldCached.cached = [];
dbReq.query = request.query;
dbReq.options = request.options;
dbReq.options.fields = {};
}
// check access on template item
dbReq.query._tp = modm.ObjectId(CORE_TEMPLATE_IDS.templates);
dbReq.query['roles.' + request.role + '.access'] = {$regex: getAccessKey(request.method)};
// fetch requested templates from db
io.read(dbReq, function (err, cursor) {
if (err) {
err.statusCode = 500;
return callback(err);
}
if (!cursor) {
err = new Error('Templates not found.');
err.statusCode = 404;
return callback(err);
}
cursor.toArray(function (err, templates) {
if (err) {
err.statusCode = 500;
return callback(err);
}
if (!templates || templates.length === 0) {
err = new Error('Templates not found.');
err.statusCode = 404;
return callback(err);
}
// cache the new templates
var newTemplates = [];
for (var i = 0, l = templates.length; i < l; ++i) {
initAndCache(templates[i])
newTemplates.push(templates[i]._id);
}
var newCached = getCachedTemplates(newTemplates, request.role, request.method);
// merge with initially cached templates
oldCached.cached = oldCached.cached.concat(newCached.cached);
callback(null, oldCached.cached);
});
});
}
// merges a role template configuration into a template but only the allowed fields
function mergeRoleTemplateConfig (template, roleConfig) {
// TODO this currently only handles top level fields in schema
// because the others are flatten
for (var key in ROLE_CONFIGURABLE_FIELDS) {
mergeRoleTemplateConfigRecursive(template[key], roleConfig[key]);
}
}
// TODO add support for:
// - Arrays (currently being overwritten)
// - key removal (currently you must explicitly specify a value)
// - object overwriting (currently the recursion goes to the leaf values)
function mergeRoleTemplateConfigRecursive (template, roleConfig) {
for (var key in roleConfig) {
if (typeof roleConfig[key] === 'object' && roleConfig[key].constructor.name !== 'Array') {
template[key] = template[key] || {};
mergeRoleTemplateConfigRecursive(template[key], roleConfig[key]);
} else {
template[key] = roleConfig[key];
}
}
}
function cloneJSON(obj) {
// basic type deep copy
if (obj === null || obj === undefined || typeof obj !== 'object') {
return obj
}
// just return ObjectId's as they are
if (obj.constructor.name === 'ObjectID') {
return obj;
}
// array deep copy
if (obj instanceof Array) {
var cloneA = [];
for (var i = 0; i < obj.length; ++i) {
cloneA[i] = cloneJSON(obj[i]);
}
return cloneA;
}
// object deep copy
var cloneO = {};
for (var key in obj) {
if (!obj.hasOwnProperty(key)) continue;
cloneO[key] = cloneJSON(obj[key]);
}
return cloneO;
}