Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions api/controllers/pages/settings.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
const path = require('path');

// GET /about/settings: the FOG 1.6 FOG Settings page
// (FOGConfigurationPage::settings and _renderSettings,
// FOGConfigurationPage.php:5638-5870). It lists every key of the settings
// catalog (config/fog-settings.js) with its value from
// sails.helpers.settings.get, one panel per category. A Setting record whose
// name is not a catalog key, such as `schema`, never shows. Each control
// saves on change through POST /api/v1/setting/save
// (api/controllers/setting/save.js, views/pages/partials/settings.js).

// The control types this page renders. Both catalog keys are `select`. The
// change that adds the first number, text or checkbox key adds its control.
const RENDERED_TYPES = ['select'];

// The 1.6 reload note, added to the label tooltip of a `reload: true` row
// (FOGConfigurationPage.php _renderSettings, $refreshtip).
const RELOAD_TIP = 'Changing this setting takes effect after you reload the page. '
+ 'A hard refresh (Ctrl+F5, or Cmd+Shift+R) may be required.';

// Natural order without case, as 1.6 ksort(SORT_NATURAL | SORT_FLAG_CASE).
const natural = (a, b) => a.localeCompare(b, undefined, {numeric: true, sensitivity: 'base'});

// The options of a select, with the stored value selected. A valid stored
// value that is not one of the options (FOG_VIEW_DEFAULT_SCREEN = 30) is one
// more option, labeled with the value, so the page shows what is stored.
function selectOptions(entry, value) {
const options = entry.options.map((option) => ({
value: String(option.value),
label: option.label,
selected: String(option.value) === String(value)
}));
if (!options.some((option) => option.selected)) {
options.push({value: String(value), label: String(value), selected: true});
}
return options;
}

module.exports = {
friendlyName: 'FOG Settings',
description: 'The FOG Settings page.',
exits: {
forbidden: {
responseType: 'forbidden'
},
success: {
viewTemplatePath: 'pages/settings'
}
},
fn: async function () {
if (!sails.helpers.audit.can(this.req, 'setting.read')) {
throw 'forbidden';
}
const catalog = sails.config.fogSettings;
const byCategory = {};
for (const key of Object.keys(catalog).sort(natural)) {
const entry = catalog[key];
// A thrown Error answers 500, and Sails logs its message.
if (!RENDERED_TYPES.includes(entry.type)) {
throw new Error(`FOG Settings: the catalog key ${key} has the type "${entry.type}", and this page renders no control for it`);
}
const value = await sails.helpers.settings.get(key);
(byCategory[entry.category] = byCategory[entry.category] || []).push({
key,
description: entry.description,
reload: entry.reload,
// One tooltip on the label: the description, then the reload note.
tip: entry.reload ? `${entry.description} — ${RELOAD_TIP}` : entry.description,
options: selectOptions(entry, value)
});
}
return {
// The FOG 1.6 content header and tab title (FOGConfigurationPage.php:64, :5640).
section: 'FOG Configuration',
page: 'FOG Settings',
categories: Object.keys(byCategory).sort(natural).map((name) => ({name, rows: byCategory[name]})),
// false disables every control. The save route checks setting.update
// itself, so this only spares a user a save that is refused.
canUpdate: sails.helpers.audit.can(this.req, 'setting.update'),
partialname: path.join(__dirname, '..', '..', '..', 'views', 'pages', 'partials', 'settings.js')
};
}
};
56 changes: 56 additions & 0 deletions api/controllers/setting/save.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* POST /api/v1/setting/save
*
* Stores one setting of the FOG settings catalog (config/fog-settings.js)
* from the FOG Settings page (views/pages/partials/settings.js), as 1.6
* FOGConfigurationPage::settingsPost does (FOGConfigurationPage.php:5218).
* Body: {key, value}. Needs setting.update.
*
* - A key that is not in the catalog answers 400
* {error: 'Unknown setting: <key>', title: 'Settings Update Fail'}.
* - A value that the entry's normalize() rejects answers 400
* {error: '<key> value is not valid', title: 'Settings Update Fail'}.
* - Otherwise it stores the normalized value in the Setting record of that
* name (updated, or created) and answers 202 with the 1.6 success body
* (FOGConfigurationPage.php:5534-5552).
*
* A 400 stores nothing. req.audit names the stored setting, so the audit
* hook's row (api/hooks/audit) says which one changed.
*/
module.exports = {
friendlyName: 'Save a setting',
description: 'Store one catalog setting, validated by its normalize().',
fn: async function () {
const req = this.req;
const res = this.res;
if (!sails.helpers.audit.can(req, 'setting.update')) {
return res.forbidden();
}
const fail = (error) => res.status(400).json({error, title: 'Settings Update Fail'});
const catalog = sails.config.fogSettings;
const key = _.get(req.body, 'key');
// Own keys only, as sails.helpers.settings.get reads them: neither
// 'constructor' nor the 'schema' record is a setting. A key that is not
// a string is named by its JSON: a template string would call its
// toString, which a JSON body can replace ({"toString": 1} throws).
if (typeof key !== 'string' || !Object.hasOwn(catalog, key)) {
return fail(`Unknown setting: ${typeof key === 'string' ? key : JSON.stringify(key)}`);
}
// normalize() gets a string or a number only, as a form or a stored
// record holds. An object or an array is not a valid value, and an
// object can make String() throw.
const raw = _.get(req.body, 'value');
const value = (typeof raw === 'string' || typeof raw === 'number') ? catalog[key].normalize(raw) : undefined;
if (value === undefined) {
return fail(`${key} value is not valid`);
}
let row = await sails.models.setting.findOne({name: key});
if (row) {
row = await sails.models.setting.updateOne({id: row.id}).set({value});
} else {
row = await sails.models.setting.create({name: key, value}).fetch();
}
sails.helpers.audit.subject(req, 'setting', row);
return res.status(202).json({msg: 'Settings successfully stored!', title: 'Settings Update Success'});
}
};
5 changes: 4 additions & 1 deletion config/globals.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,10 @@ module.exports.globals = {
{link: '/pxemenus/create', text: 'Create New iPXE Menu'}
]
},
// The 1.6 "Logging" group (FOGPage.php:899-902). It sits after the planned
// The 1.6 "FOG Configuration" node (FOGConfigurationPage.php). A leaf to
// FOG Settings until a second sub-page exists.
{order: 150, text: 'FOG Configuration', link: '/about/settings', icon: 'fas fa-wrench'},
// The 1.6 "Logging" group (FOGPage.php:899-902). It sits after the
// FOG Configuration entry (150).
{
order: 170, text: 'Logging', icon: 'fas fa-scroll',
Expand Down
4 changes: 4 additions & 0 deletions config/policies.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ module.exports.policies = {
'agent/mint-token': ['isLoggedIn','isAuthenticated','apiCsrfGuard'],
'agent/revoke-token': ['isLoggedIn','isAuthenticated','apiCsrfGuard'],

// The FOG Settings save (checks setting.update itself). apiCsrfGuard: a
// cookie-authed mutation on CSRF-exempt /api/v1.
'setting/save': ['isLoggedIn','isAuthenticated','apiCsrfGuard'],

// Image Policies
'image/capture': ['isLoggedIn','isAuthenticated', 'image/capture'],
'image/deploy': ['isLoggedIn','isAuthenticated', 'image/deploy'],
Expand Down
10 changes: 10 additions & 0 deletions config/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,12 @@ module.exports.routes = {
// Global search (must precede the :model routes).
'GET /api/v1/search': {action: 'search', csrf: false},

// The FOG Settings page saves one setting per request (setting.update).
// Grouped above the :model routes with the other explicit /api/v1 routes.
// A cookie-authed mutation on CSRF-exempt /api/v1, so apiCsrfGuard guards
// it (config/policies.js).
'POST /api/v1/setting/save': {action: 'setting/save', csrf: false},

// General API elements.
'POST /api/v1/image/scan': {action: 'image/scan', csrf: false},
'POST /api/v1/:model': {action: 'general/create', csrf: false},
Expand Down Expand Up @@ -164,6 +170,10 @@ module.exports.routes = {
'GET /pxemenus/create': {action: 'pages/create/pxemenus'},
'POST /pxemenus/create': {action: 'general/save'},

// FOG Configuration Views, at the FOG 1.6 node and sub names
// (FOGConfigurationPage::settings, about&sub=settings)
'GET /about/settings': {action: 'pages/settings'},

// Edit Views (generic edit page + save)
'GET /hosts/edit/:id': {action: 'pages/edit'},
'POST /hosts/edit/:id': {action: 'general/save'},
Expand Down
10 changes: 10 additions & 0 deletions test/helpers/menu.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ describe('Sidebar menu helpers::', () => {
['Workflows', 'fas fa-diagram-project'],
['User Administration', 'fas fa-shield'],
['iPXE Menu', 'fas fa-list-ol'],
['FOG Configuration', 'fas fa-wrench'],
['Logging', 'fas fa-scroll']
]);
assert.deepStrictEqual(menu.filter((n) => n.pluginOption), []);
Expand Down Expand Up @@ -129,6 +130,15 @@ describe('Sidebar menu helpers::', () => {
assert.deepStrictEqual(entries(menu).filter((n) => n.active).map((n) => n.text), ['Hosts']);
});

// Issue #199: the FOG Configuration leaf opens FOG Settings.
it('on /about/settings, makes the FOG Configuration leaf the one active item', () => {
const menu = build('/about/settings');
const node = find(menu, 'FOG Configuration');
assert.strictEqual(node.type, 'leaf');
assert.strictEqual(node.link, '/about/settings');
assert.deepStrictEqual(entries(menu).filter((n) => n.active).map((n) => n.text), ['FOG Configuration']);
});

it('on /hosts, makes "List All Hosts" the active sub-link', () => {
assert.deepStrictEqual(activeSubs(build('/hosts')).map((s) => s.text), ['List All Hosts']);
});
Expand Down
Loading
Loading