/
settings.js
392 lines (335 loc) · 11.6 KB
/
settings.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
// # Settings API
// RESTful API for the Setting resource
var _ = require('lodash'),
dataProvider = require('../models'),
when = require('when'),
config = require('../config'),
canThis = require('../permissions').canThis,
errors = require('../errors'),
utils = require('./utils'),
docName = 'settings',
settings,
updateSettingsCache,
settingsFilter,
filterPaths,
readSettingsResult,
settingsResult,
canEditAllSettings,
populateDefaultSetting,
hasPopulatedDefaults = false,
/**
* ## Cache
* Holds cached settings
* @private
* @type {{}}
*/
settingsCache = {};
/**
* ### Update Settings Cache
* Maintain the internal cache of the settings object
* @public
* @param settings
* @returns {Settings}
*/
updateSettingsCache = function (settings) {
settings = settings || {};
if (!_.isEmpty(settings)) {
_.map(settings, function (setting, key) {
settingsCache[key] = setting;
});
return when(settingsCache);
}
return dataProvider.Settings.findAll()
.then(function (result) {
settingsCache = readSettingsResult(result.models);
return settingsCache;
});
};
// ## Helpers
/**
* ### Settings Filter
* Filters an object based on a given filter object
* @private
* @param settings
* @param filter
* @returns {*}
*/
settingsFilter = function (settings, filter) {
return _.object(_.filter(_.pairs(settings), function (setting) {
if (filter) {
return _.some(filter.split(','), function (f) {
return setting[1].type === f;
});
}
return true;
}));
};
/**
* ### Filter Paths
* Normalizes paths read by require-tree so that the apps and themes modules can use them. Creates an empty
* array (res), and populates it with useful info about the read packages like name, whether they're active
* (comparison with the second argument), and if they have a package.json, that, otherwise false
* @private
* @param {object} paths as returned by require-tree()
* @param {array/string} active as read from the settings object
* @returns {Array} of objects with useful info about apps / themes
*/
filterPaths = function (paths, active) {
var pathKeys = Object.keys(paths),
res = [],
item;
// turn active into an array (so themes and apps can be checked the same)
if (!Array.isArray(active)) {
active = [active];
}
_.each(pathKeys, function (key) {
//do not include hidden files or _messages
if (key.indexOf('.') !== 0 &&
key !== '_messages' &&
key !== 'README.md'
) {
item = {
name: key
};
if (paths[key].hasOwnProperty('package.json')) {
item.package = paths[key]['package.json'];
} else {
item.package = false;
}
if (_.indexOf(active, key) !== -1) {
item.active = true;
}
res.push(item);
}
});
return res;
};
/**
* ### Read Settings Result
* @private
* @param settingsModels
* @returns {Settings}
*/
readSettingsResult = function (settingsModels) {
var settings = _.reduce(settingsModels, function (memo, member) {
if (!memo.hasOwnProperty(member.attributes.key)) {
memo[member.attributes.key] = member.attributes;
}
return memo;
}, {}),
themes = config().paths.availableThemes,
apps = config().paths.availableApps,
res;
if (settings.activeTheme) {
res = filterPaths(themes, settings.activeTheme.value);
settings.availableThemes = {
key: 'availableThemes',
value: res,
type: 'theme'
};
}
if (settings.activeApps) {
res = filterPaths(apps, JSON.parse(settings.activeApps.value));
settings.availableApps = {
key: 'availableApps',
value: res,
type: 'app'
};
}
return settings;
};
/**
* ### Settings Result
* @private
* @param settings
* @param type
* @returns {{settings: *}}
*/
settingsResult = function (settings, type) {
var filteredSettings = _.values(settingsFilter(settings, type)),
result = {
settings: filteredSettings,
meta: {}
};
if (type) {
result.meta.filters = {
type: type
};
}
return result;
};
/**
* ### Populate Default Setting
* @private
* @param key
* @param type
* @returns Promise(Setting)
*/
populateDefaultSetting = function (key) {
// Call populateDefault and update the settings cache
return dataProvider.Settings.populateDefault(key).then(function (defaultSetting) {
// Process the default result and add to settings cache
var readResult = readSettingsResult(defaultSetting);
// Add to the settings cache
return updateSettingsCache(readResult).then(function () {
// Update theme with the new settings
return config.theme.update(settings, config().url);
}).then(function () {
// Get the result from the cache with permission checks
return defaultSetting;
});
}).otherwise(function (err) {
// Pass along NotFoundError
if (typeof err === errors.NotFoundError) {
return when.reject(err);
}
// TODO: Different kind of error?
return when.reject(new errors.NotFoundError('Problem finding setting: ' + key));
});
};
/**
* ### Can Edit All Settings
* Check that this edit request is allowed for all settings requested to be updated
* @private
* @param settingsInfo
* @returns {*}
*/
canEditAllSettings = function (settingsInfo, options) {
var checkSettingPermissions = function (setting) {
if (setting.type === 'core' && !(options.context && options.context.internal)) {
return when.reject(
new errors.NoPermissionError('Attempted to access core setting from external request')
);
}
return canThis(options.context).edit.setting(setting.key);
},
checks = _.map(settingsInfo, function (settingInfo) {
var setting = settingsCache[settingInfo.key];
if (!setting) {
// Try to populate a default setting if not in the cache
return populateDefaultSetting(settingInfo.key).then(function (defaultSetting) {
// Get the result from the cache with permission checks
return checkSettingPermissions(defaultSetting);
});
}
return checkSettingPermissions(setting);
});
return when.all(checks);
};
/**
* ## Settings API Methods
*
* **See:** [API Methods](index.js.html#api%20methods)
*/
settings = {
/**
* ### Browse
* @param options
* @returns {*}
*/
browse: function browse(options) {
// First, check if we have populated the settings from default-settings yet
if (!hasPopulatedDefaults) {
return dataProvider.Settings.populateDefaults().then(function () {
hasPopulatedDefaults = true;
return settings.browse(options);
});
}
options = options || {};
var result = settingsResult(settingsCache, options.type);
// If there is no context, return only blog settings
if (!options.context) {
return when(_.filter(result.settings, function (setting) { return setting.type === 'blog'; }));
}
// Otherwise return whatever this context is allowed to browse
return canThis(options.context).browse.setting().then(function () {
// Omit core settings unless internal request
if (!options.context.internal) {
result.settings = _.filter(result.settings, function (setting) { return setting.type !== 'core'; });
}
return result;
});
},
/**
* ### Read
* @param options
* @returns {*}
*/
read: function read(options) {
if (_.isString(options)) {
options = { key: options };
}
var getSettingsResult = function () {
var setting = settingsCache[options.key],
result = {};
result[options.key] = setting;
if (setting.type === 'core' && !(options.context && options.context.internal)) {
return when.reject(
new errors.NoPermissionError('Attempted to access core setting from external request')
);
}
if (setting.type === 'blog') {
return when(settingsResult(result));
}
return canThis(options.context).read.setting(options.key).then(function () {
return settingsResult(result);
}, function () {
return when.reject(new errors.NoPermissionError('You do not have permission to read settings.'));
});
};
// If the setting is not already in the cache
if (!settingsCache[options.key]) {
// Try to populate the setting from default-settings file
return populateDefaultSetting(options.key).then(function () {
// Get the result from the cache with permission checks
return getSettingsResult();
});
}
// Get the result from the cache with permission checks
return getSettingsResult();
},
/**
* ### Edit
* Update properties of a post
* @param {{settings: }} object Setting or a single string name
* @param {{id (required), include,...}} options (optional) or a single string value
* @return {Promise(Setting)} Edited Setting
*/
edit: function edit(object, options) {
options = options || {};
var self = this,
type;
// Allow shorthand syntax where a single key and value are passed to edit instead of object and options
if (_.isString(object)) {
object = { settings: [{ key: object, value: options }]};
}
//clean data
_.each(object.settings, function (setting) {
if (!_.isString(setting.value)) {
setting.value = JSON.stringify(setting.value);
}
});
type = _.find(object.settings, function (setting) { return setting.key === 'type'; });
if (_.isObject(type)) {
type = type.value;
}
object.settings = _.reject(object.settings, function (setting) {
return setting.key === 'type' || setting.key === 'availableThemes' || setting.key === 'availableApps';
});
return canEditAllSettings(object.settings, options).then(function () {
return utils.checkObject(object, docName).then(function (checkedData) {
options.user = self.user;
return dataProvider.Settings.edit(checkedData.settings, options);
}).then(function (result) {
var readResult = readSettingsResult(result);
return updateSettingsCache(readResult).then(function () {
return config.theme.update(settings, config().url);
}).then(function () {
return settingsResult(readResult, type);
});
});
});
}
};
module.exports = settings;
module.exports.updateSettingsCache = updateSettingsCache;