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
24 changes: 24 additions & 0 deletions api/controllers/host/pending-approve.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* POST /api/v1/host/pending/approve
*
* Approve pending hosts: body {ids: [..]}. Each listed host that is pending
* gets `pending: false`, and nothing else changes; an approved or unknown id
* is skipped. Needs host.update. Answers {count}, the hosts approved. As in
* 1.6 (HostManagement.php:405) there is no "approve all".
*/
module.exports = {
friendlyName: 'Approve pending hosts',
description: 'Clear the pending flag of the listed pending hosts.',
fn: async function () {
const req = this.req;
const res = this.res;
if (!_.get(req, 'user.permissions.stock.host.update')) {
return res.forbidden();
}
const raw = _.get(req.body, 'ids');
const ids = (Array.isArray(raw) ? raw : [raw]).filter((id) => typeof id === 'string' && id !== '');
if (!ids.length) { return res.json({count: 0}); }
const approved = await sails.models.host.update({id: ids, pending: true}).set({pending: false}).fetch();
return res.json({count: approved.length});
}
};
50 changes: 50 additions & 0 deletions api/controllers/host/pending-datatable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* POST /api/v1/host/pending/datatable
*
* The rows of the Pending Hosts page (GET /hosts/pending): the hosts with
* `pending: true`, as DataTables server-side rows {id, name, mac, description},
* sorted by name. Needs host.read.
*
* Search: trim and lowercase the text. A row matches when its lowercased name
* contains the text, or when any entry of its `macs` (stored as 12 bare hex
* digits) contains the text with `:`, `-`, `.` and spaces removed. So `lab`
* finds LAB-01, and `00:11` finds 001122334455.
*/
module.exports = {
friendlyName: 'Pending hosts datatable',
description: 'The pending hosts, as DataTables server-side rows.',
fn: async function () {
const req = this.req;
const res = this.res;
if (!_.get(req, 'user.permissions.stock.host.read')) {
return res.forbidden();
}
const body = req.body || {};
const start = Math.max(0, parseInt(body.start, 10) || 0);
const length = parseInt(body.length, 10);
const text = String(_.get(body, 'search.value', '')).trim().toLowerCase();
const macText = text.replace(/[:\-. ]/g, '');

const pending = await sails.models.host.find({pending: true}).sort('name ASC');
const matches = (host) => {
if (text === '') { return true; }
if (String(host.name).toLowerCase().includes(text)) { return true; }
return macText !== '' && (Array.isArray(host.macs) ? host.macs : []).some((m) => String(m).toLowerCase().includes(macText));
};
const found = pending.filter(matches);
// length -1 (DataTables "All") and a missing length answer every row.
const page = length > 0 ? found.slice(start, start + length) : found.slice(start);

// The first MAC as aa:bb:cc:dd:ee:ff; a stored value that is not 12 hex digits shows as stored.
const show = (host) => {
const first = Array.isArray(host.macs) && host.macs.length ? String(host.macs[0]) : '';
return /^[0-9a-f]{12}$/i.test(first) ? first.toLowerCase().match(/../g).join(':') : first;
};
return res.json({
draw: parseInt(body.draw, 10) || 0,
recordsTotal: pending.length,
recordsFiltered: found.length,
data: page.map((host) => ({id: host.id, name: host.name, mac: show(host), description: host.description || ''}))
});
}
};
36 changes: 36 additions & 0 deletions api/controllers/host/pending-delete.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* DELETE /api/v1/host/pending
*
* Delete pending hosts: body {id: [..]}, the shape of the generic delete (the
* list's "Delete selected" sends it here, views/pages/list.ejs `deleteUrl`).
* Each listed host that is pending is destroyed, and the plugins remove the
* rows that link to it, as api/controllers/general/destroy.js does. An
* approved host is never destroyed here. The enrollment rows bound to a
* destroyed host get `host: ''`. Needs host.destroy. Answers {count}.
*/
module.exports = {
friendlyName: 'Delete pending hosts',
description: 'Destroy the listed pending hosts and unbind their enrollment rows.',
fn: async function () {
const req = this.req;
const res = this.res;
if (!_.get(req, 'user.permissions.stock.host.destroy')) {
return res.forbidden();
}
const raw = req.allParams().id;
const ids = (Array.isArray(raw) ? raw : [raw]).filter((id) => typeof id === 'string' && id !== '');
if (!ids.length) { return res.json({count: 0}); }
// pending in the criteria: an approved id is skipped, even if it races an approval.
const destroyed = await sails.models.host.destroy({id: ids, pending: true}).fetch();
const gone = destroyed.map((host) => host.id);
if (sails.plugins && sails.plugins.hostDestroy) {
for (const id of gone) {
await sails.plugins.hostDestroy(id);
}
}
if (gone.length) {
await sails.models.agentenrollment.update({host: gone}).set({host: ''});
}
return res.json({count: gone.length});
}
};
4 changes: 3 additions & 1 deletion api/controllers/pages/dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ module.exports = {

// The 1.6 pending-hosts callout: hosts awaiting approval.
let pendingHosts = await Host.count({ pending: true });
// And the fog-agent enrollments that wait for an admin (DashboardPage.php:200-228).
let pendingAgents = await sails.models.agentenrollment.count({ state: 'pending' });

let data = {
// The FOG 1.6 content header and tab title.
Expand All @@ -84,7 +86,7 @@ module.exports = {
free, used, size, legend,
webserver, loadaverage, uptime,
avail, staged, active,
pendingHosts
pendingHosts, pendingAgents
};
let partial = path.join(partialPath, `${data.model}.js`);
if (fs.existsSync(partial)) {
Expand Down
52 changes: 52 additions & 0 deletions api/controllers/pages/list/agent-tokens.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const path = require('path');
const partialPath = path.join(__dirname,'..','..','..','..','views','pages','partials','list');
// GET /hosts/agentTokens: the fog-agent enrollment tokens (1.6
// HostManagement::agentTokens, HostManagement.php:829). The rows come from
// GET /api/v1/agent/tokens. A token is minted and revoked, not deleted like a
// record, so the built-in "Delete selected" is hidden and the partial adds
// "Create token" and "Revoke selected".
module.exports = {
friendlyName: 'Agent tokens',
description: 'Agent enrollment tokens page.',
inputs: {
},
exits: {
error: {
responseType: 'serverError'
},
forbidden: {
responseType: 'forbidden'
},
success: {
viewTemplatePath: 'pages/list',
description: 'Successful'
}
},
fn: async function () {
if (!_.get(this.req, 'user.permissions.stock.host.read')) {
throw 'forbidden';
}
let data = {
theads: [
'Name',
'State',
'Uses left',
'Expires',
'Created by',
'Created'
],
model: 'host',
partialname: path.join(partialPath, 'agent-tokens.js')
};
Object.assign(data, await sails.helpers.listLocals.with({identity: data.model, base: '/hosts'}));
// The 1.6 title is not "All <plural>".
Object.assign(data, {
page: 'Agent Enrollment Tokens',
singular: 'token',
plural: 'tokens',
deleteButton: false
});
delete data.editBase;
return data;
}
};
53 changes: 53 additions & 0 deletions api/controllers/pages/list/pending-agents.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const path = require('path');
const partialPath = path.join(__dirname,'..','..','..','..','views','pages','partials','list');
// GET /hosts/pendingAgents: the fog-agent enrollments that wait for an admin
// (1.6 HostManagement::pendingAgents, HostManagement.php:650). The rows come
// from GET /api/v1/agent/enrollments. An enrollment is approved or denied,
// never deleted, so the page has no "Delete selected" button.
module.exports = {
friendlyName: 'Pending agents',
description: 'Pending agents page.',
inputs: {
},
exits: {
error: {
responseType: 'serverError'
},
forbidden: {
responseType: 'forbidden'
},
success: {
viewTemplatePath: 'pages/list',
description: 'Successful'
}
},
fn: async function () {
if (!_.get(this.req, 'user.permissions.stock.host.read')) {
throw 'forbidden';
}
let data = {
theads: [
'Host',
'Reason',
'Platform',
'Agent',
'From',
'Identity',
'Requested'
],
model: 'host',
partialname: path.join(partialPath, 'pending-agents.js')
};
Object.assign(data, await sails.helpers.listLocals.with({identity: data.model, base: '/hosts'}));
// A row is an enrollment, not a host: its own nouns, no edit link base
// for the first column (the partial links to the host itself), no delete.
Object.assign(data, {
page: 'All Pending Agents',
singular: 'agent',
plural: 'agents',
deleteButton: false
});
delete data.editBase;
return data;
}
};
44 changes: 44 additions & 0 deletions api/controllers/pages/list/pending-hosts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const path = require('path');
const partialPath = path.join(__dirname,'..','..','..','..','views','pages','partials','list');
// GET /hosts/pending: the hosts that wait for an admin to approve them (1.6
// HostManagement::pending, HostManagement.php:270). The rows come from
// POST /api/v1/host/pending/datatable. "Delete selected" goes to
// DELETE /api/v1/host/pending, so an approved host is never deleted here.
module.exports = {
friendlyName: 'Pending hosts',
description: 'Pending hosts page.',
inputs: {
},
exits: {
error: {
responseType: 'serverError'
},
forbidden: {
responseType: 'forbidden'
},
success: {
viewTemplatePath: 'pages/list',
description: 'Successful'
}
},
fn: async function () {
if (!_.get(this.req, 'user.permissions.stock.host.read')) {
throw 'forbidden';
}
let data = {
theads: [
'Host',
'Primary MAC',
'Description'
],
model: 'host',
partialname: path.join(partialPath, 'pending-hosts.js'),
deleteUrl: '/api/v1/host/pending'
};
// The nouns, the table settings and the edit link base
// (api/helpers/list-locals.js), then the 1.6 title of this page.
Object.assign(data, await sails.helpers.listLocals.with({identity: data.model, base: '/hosts'}));
data.page = 'All Pending Hosts';
return data;
}
};
53 changes: 52 additions & 1 deletion assets/fog/fog.common.js
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,56 @@ function fogEscape(s) {
return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', '\'': '&#39;'}[c]));
}

// A ms timestamp as the browser's local date and time ('' for none).
function fogWhen(ms) {
return ms ? new Date(ms).toLocaleString() : '';
}
window.fogWhen = fogWhen;

// DataTables column renders: a server value shows as text, never as markup; a
// ms timestamp shows as a local date and time. Sort and filter use the raw value.
window.fogTextCell = (data, type) => (type === 'display' ? fogEscape(data) : data);
window.fogWhenCell = (data, type) => (type === 'display' ? fogWhen(data) : data);

// The error of a failed $.ajax call: the body's `error` key, else the HTTP status.
function fogErrorOf(xhr) {
return (xhr.responseJSON && xhr.responseJSON.error) || ('HTTP ' + xhr.status);
}
window.fogErrorOf = fogErrorOf;

// Confirm, then one $.ajax per selected row in turn, then collect the failures,
// deselect, reload and toast. A list page uses it for an action on each row.
// dt the DataTables API of the list
// opts.confirm fogConfirm options, or a function of the row count
// opts.request function(id) -> $.ajax options (url, type)
// opts.verb 'decided' or 'revoked': the failure toast reads
// "N <verb>, M not: <id>: <error>; ..."
// opts.success {text, title}; opts.failTitle the failure toast title
window.fogRunEach = function(dt, opts) {
let ids = dt.rows({selected: true}).data().toArray().map((r) => r.id).filter(Boolean);
if (!ids.length) { return; }
let ask = typeof opts.confirm === 'function' ? opts.confirm(ids.length) : opts.confirm;
window.fogConfirm(ask).then(async (ok) => {
if (!ok) { return; }
let failed = [];
for (let id of ids) {
await new Promise((resolve) => {
$.ajax(opts.request(id)).done(() => resolve()).fail((xhr) => {
failed.push(id + ': ' + fogErrorOf(xhr));
resolve();
});
});
}
dt.rows({selected: true}).deselect();
dt.ajax.reload();
if (failed.length) {
window.fogToast('error', (ids.length - failed.length) + ' ' + opts.verb + ', ' + failed.length + ' not: ' + failed.join('; '), opts.failTitle);
return;
}
window.fogToast('success', opts.success.text, opts.success.title);
});
};

// Every list table, built like a FOG 1.6 grid (1.6 fog.common.js
// $.fn.registerTable, 4280-4720): the 1.6 toolbar, the column-search row,
// column show/hide, reorder and resize, the saved per-user layout, and the
Expand Down Expand Up @@ -549,7 +599,8 @@ function fogActionBox(node, table, opts) {
}).then((ok) => {
if (!ok) { return; }
$.ajax({
url: '/api/v1/' + encodeURIComponent(node.attr('data-model')),
// A page can send the delete elsewhere (list.ejs deleteUrl), for example the pending hosts.
url: node.attr('data-delete-url') || '/api/v1/' + encodeURIComponent(node.attr('data-model')),
type: 'DELETE',
contentType: 'application/json',
data: JSON.stringify({id: ids}),
Expand Down
2 changes: 2 additions & 0 deletions config/globals.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ module.exports.globals = {
{link: '/hosts/create', text: 'Create New Host'},
{link: '/hosts/pending', text: 'Pending Hosts'},
{link: '/hosts/pendingMacs', text: 'Pending MACs'},
{link: '/hosts/pendingAgents', text: 'Pending Agents'},
{link: '/hosts/agentTokens', text: 'Agent Tokens'},
{link: '/hosts/export', text: 'Export Hosts'},
{link: '/hosts/import', text: 'Import Hosts'}
]
Expand Down
5 changes: 5 additions & 0 deletions config/policies.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ module.exports.policies = {
'host/bulk': ['isLoggedIn','isAuthenticated','apiCsrfGuard'],
// Group name list (checks host read permission itself -- no :model param here)
'host/groups': ['isLoggedIn','isAuthenticated'],
// Pending hosts (each action checks its host permission itself). The datatable
// only reads; approve and delete mutate on CSRF-exempt /api/v1, so apiCsrfGuard.
'host/pending-datatable': ['isLoggedIn','isAuthenticated'],
'host/pending-approve': ['isLoggedIn','isAuthenticated','apiCsrfGuard'],
'host/pending-delete': ['isLoggedIn','isAuthenticated','apiCsrfGuard'],

// fog-agent enrollment admin routes (each action checks its host permission
// itself). apiCsrfGuard: a cookie-authed mutation on CSRF-exempt /api/v1.
Expand Down
9 changes: 9 additions & 0 deletions config/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ module.exports.routes = {
// by apiCsrfGuard instead (see config/policies.js).
'POST /api/v1/host/bulk': {action: 'host/bulk', csrf: false},
'GET /api/v1/host/groups': {action: 'host/groups', csrf: false},
// The Pending Hosts page (GET /hosts/pending). DELETE /api/v1/host/pending
// must precede DELETE /api/v1/:model/:id?, or it is read as :model=host/:id=pending.
'POST /api/v1/host/pending/datatable': {action: 'host/pending-datatable', csrf: false},
'POST /api/v1/host/pending/approve': {action: 'host/pending-approve', csrf: false},
'DELETE /api/v1/host/pending': {action: 'host/pending-delete', csrf: false},

// fog-agent enrollment admin API (host permissions; must precede the :model
// routes, or GET /api/v1/agent/tokens is read as :model=agent/:id=tokens).
Expand Down Expand Up @@ -115,6 +120,10 @@ module.exports.routes = {
'GET /hosts': {action: 'pages/list/hosts'},
'GET /hosts/create': {action: 'pages/create/hosts'},
'POST /hosts/create': {action: 'general/save'},
// fog-agent enrollment pages, at the FOG 1.6 sub names (HostManagement.php)
'GET /hosts/pending': {action: 'pages/list/pending-hosts'},
'GET /hosts/pendingAgents': {action: 'pages/list/pending-agents'},
'GET /hosts/agentTokens': {action: 'pages/list/agent-tokens'},

// Group Views
'GET /groups': {action: 'pages/list/groups'},
Expand Down
Loading
Loading