Skip to content

Node.js based forum software built for the modern web

feat(privileges): add "All Categories" aggregate view to admin privileges page (#14303)

palmoni57156e7347428
diff --git a/public/language/en-GB/admin/manage/privileges.json b/public/language/en-GB/admin/manage/privileges.json
index bb4b33494f..00cd429380 100644
--- a/public/language/en-GB/admin/manage/privileges.json
+++ b/public/language/en-GB/admin/manage/privileges.json
@@ -3,6 +3,7 @@
"discard-changes": "Discard changes",
"global": "Global",
"admin": "Admin",
+ "all-categories": "All Categories",
"group-privileges": "Group Privileges",
"user-privileges": "User Privileges",
"edit-privileges": "Edit Privileges",
@@ -55,6 +56,7 @@
"alert.confirm-save": "Please confirm your intention to save these privileges",
"alert.confirm-discard": "Are you sure you wish to discard your privilege changes?",
"alert.discarded": "Privilege changes discarded",
+ "alert.copy-disabled-all": "Copying privileges is not available while viewing all categories. Select a single category first.",
"alert.confirm-copyToAll": "Are you sure you wish to apply this set of <strong>%1</strong> to <strong>all categories</strong>?",
"alert.confirm-copyToAllGroup": "Are you sure you wish to apply this group's set of <strong>%1</strong> to <strong>all categories</strong>?",
"alert.confirm-copyToChildren": "Are you sure you wish to apply this set of <strong>%1</strong> to <strong>all descendant (child) categories</strong>?",
diff --git a/public/src/admin/manage/privileges.js b/public/src/admin/manage/privileges.js
index 97abb4b5bb..4356316838 100644
--- a/public/src/admin/manage/privileges.js
+++ b/public/src/admin/manage/privileges.js
@@ -18,15 +18,32 @@ define('admin/manage/privileges', [
let cid;
+ // Resolves the selector's raw cid value into the form used throughout this module:
+ // the string 'all' (every category), the string 'admin', or a numeric category id
+ // (0 = global). Anything non-numeric that isn't 'all' falls back to 'admin'.
+ function normalizeCid(rawCid) {
+ if (rawCid === 'all') {
+ return 'all';
+ }
+ const parsed = parseInt(rawCid, 10);
+ return isNaN(parsed) ? 'admin' : parsed;
+ }
+
+ // 'category' template applies when viewing a single real category OR the "all
+ // categories" aggregate; 'global' covers cid 0 (global) and the admin pseudo-cid.
+ function getPrivilegeTablePartial() {
+ const isCategoryView = cid === 'all' || parseInt(cid, 10);
+ return `admin/partials/privileges/${isCategoryView ? 'category' : 'global'}`;
+ }
+
Privileges.init = function () {
- cid = isNaN(parseInt(ajaxify.data.selectedCategory.cid, 10)) ? 'admin' : ajaxify.data.selectedCategory.cid;
+ cid = normalizeCid(ajaxify.data.selectedCategory.cid);
checkboxRowSelector.init('.privilege-table-container');
categorySelector.init($('[component="category-selector"]'), {
onSelect: function (category) {
- cid = parseInt(category.cid, 10);
- cid = isNaN(cid) ? 'admin' : cid;
+ cid = normalizeCid(category.cid);
Privileges.refreshPrivilegeTable();
ajaxify.updateHistory('admin/manage/privileges/' + (cid || ''));
},
@@ -56,7 +73,14 @@ define('admin/manage/privileges', [
const isGroup = $rowEl.attr('data-group-name') !== undefined;
const isBanned = (isGroup && $rowEl.attr('data-group-name') === 'banned-users') || $rowEl.attr('data-banned') !== undefined;
const sourceGroupName = isBanned ? 'banned-users' : 'registered-users';
- const delta = $checkboxEl.prop('checked') === ($wrapperEl.attr('data-value') === 'true') ? null : state;
+ const dataValue = $wrapperEl.attr('data-value');
+ // When viewing all categories at once a privilege may be granted in only some of
+ // them (data-value="mixed"); any deliberate click there is always a real change,
+ // applied to every category. Otherwise a click that returns to the original state
+ // is a no-op (delta = null).
+ const delta = dataValue === 'mixed' ?
+ state :
+ (state === (dataValue === 'true') ? null : state);
if (member) {
if (isGroup && privilege === 'groups:moderate' && !isPrivate && state) {
@@ -90,11 +114,22 @@ define('admin/manage/privileges', [
}
});
+ // Mixed states must be applied before assumed privileges, so that the inheritance
+ // pass (which reads the parent row) can treat an indeterminate parent as granted.
+ Privileges.exposeMixedPrivileges();
Privileges.exposeAssumedPrivileges();
checkboxRowSelector.updateAll();
Privileges.addEvents(); // events with confirmation modals
};
+ // In the "all categories" view, privileges granted in some but not all categories are
+ // rendered with data-value="mixed". Show them as indeterminate checkboxes.
+ Privileges.exposeMixedPrivileges = function () {
+ $('.privilege-table td[data-value="mixed"] input[type="checkbox"]').each(function () {
+ this.indeterminate = true;
+ });
+ };
+
Privileges.applyDeltaState = (checkboxEl, delta) => {
['bg-success', 'bg-opacity-75', 'border-success'].forEach((className) => {
checkboxEl.classList.toggle(className, delta === true);
@@ -199,12 +234,13 @@ define('admin/manage/privileges', [
Privileges.refreshPrivilegeTable = function (groupToHighlight) {
api.get(`/categories/${cid}/privileges`, {}).then((privileges) => {
ajaxify.data.privileges = { ...ajaxify.data.privileges, ...privileges };
- const tpl = parseInt(cid, 10) ? 'admin/partials/privileges/category' : 'admin/partials/privileges/global';
+ const tpl = getPrivilegeTablePartial();
const isAdminPriv = ajaxify.currentPage.endsWith('admin/manage/privileges/admin');
app.parseAndTranslate(tpl, { cid, privileges, isAdminPriv }).then((html) => {
// Get currently selected filters
const btnIndices = $('.privilege-filters button.btn-warning').map((idx, el) => $(el).index()).get();
$('.privilege-table-container').html(html);
+ Privileges.exposeMixedPrivileges();
Privileges.exposeAssumedPrivileges();
document.querySelectorAll('.privilege-filters').forEach((con, i) => {
const idx = btnIndices[i] === undefined ? 0 : btnIndices[i];
@@ -248,7 +284,10 @@ define('admin/manage/privileges', [
applyPrivilegesToColumn(inputSelectorFn, sourceChecked);
};
- Privileges.setPrivilege = (member, privilege, state) => api[state ? 'put' : 'del'](`/categories/${isNaN(cid) ? 0 : cid}/privileges/${encodeURIComponent(privilege)}`, { member });
+ Privileges.setPrivilege = (member, privilege, state) => {
+ const targetCid = cid === 'all' ? 'all' : (isNaN(cid) ? 0 : cid);
+ return api[state ? 'put' : 'del'](`/categories/${targetCid}/privileges/${encodeURIComponent(privilege)}`, { member });
+ };
Privileges.addUserToPrivilegeTable = async function () {
const modal = await modals.dialog({
@@ -295,6 +334,9 @@ define('admin/manage/privileges', [
};
Privileges.copyPrivilegesToChildren = function (cid, group) {
+ if (cid === 'all') {
+ return alerts.error('[[admin/manage/privileges:alert.copy-disabled-all]]');
+ }
const filter = getGroupPrivilegeFilter();
socket.emit('admin.categories.copyPrivilegesToChildren', { cid, group, filter }, function (err) {
if (err) {
@@ -305,6 +347,9 @@ define('admin/manage/privileges', [
};
Privileges.copyPrivilegesFromCategory = function (cid, group) {
+ if (cid === 'all') {
+ return alerts.error('[[admin/manage/privileges:alert.copy-disabled-all]]');
+ }
const privilegeSubset = getPrivilegeSubset();
const message = '<br>' +
(group ? `[[admin/manage/privileges:alert.copyPrivilegesFromGroup-warning, ${privilegeSubset}]]` :
@@ -332,6 +377,9 @@ define('admin/manage/privileges', [
};
Privileges.copyPrivilegesToAllCategories = function (cid, group) {
+ if (cid === 'all') {
+ return alerts.error('[[admin/manage/privileges:alert.copy-disabled-all]]');
+ }
const filter = getGroupPrivilegeFilter();
socket.emit('admin.categories.copyPrivilegesToAllCategories', { cid, group, filter }, function (err) {
if (err) {
@@ -346,7 +394,10 @@ define('admin/manage/privileges', [
$(`.privilege-table tr[data-group-name="${sourceGroupName}"] td input[type="checkbox"]:not(.checkbox-helper)`)
.parents('[data-privilege]')
.each(function (idx, el) {
- if ($(el).find('input').prop('checked')) {
+ // `indeterminate` covers the "all categories" mixed state: a source group that
+ // holds the privilege in only some categories still confers it to inheritors.
+ const input = $(el).find('input').get(0);
+ if (input && (input.checked || input.indeterminate)) {
privs.push(el.getAttribute('data-privilege'));
}
});
@@ -421,7 +472,7 @@ define('admin/manage/privileges', [
return memo;
}, {});
- app.parseAndTranslate('admin/partials/privileges/' + ((isNaN(cid) || cid === 0) ? 'global' : 'category'), 'privileges.groups', {
+ app.parseAndTranslate(getPrivilegeTablePartial(), 'privileges.groups', {
privileges: {
groups: [
{
@@ -459,7 +510,7 @@ define('admin/manage/privileges', [
return memo;
}, {});
- const html = await app.parseAndTranslate('admin/partials/privileges/' + (isNaN(cid) ? 'global' : 'category'), 'privileges.users', {
+ const html = await app.parseAndTranslate(getPrivilegeTablePartial(), 'privileges.users', {
privileges: {
users: [
{
diff --git a/public/src/modules/helpers.common.js b/public/src/modules/helpers.common.js
index e2774d8e41..b67956ac88 100644
--- a/public/src/modules/helpers.common.js
+++ b/public/src/modules/helpers.common.js
@@ -299,7 +299,7 @@ module.exports = function (utils, Benchpress, tx, relative_path) {
return `
<td data-privilege="${escape(priv.name)}" data-value="${escape(priv.state)}" data-type="${escape(priv.type)}">
<div class="form-check text-center">
- <input class="form-check-input float-none${(disabled ? ' d-none"' : '')}" autocomplete="off" type="checkbox"${(priv.state ? ' checked' : '')}${(disabled ? ' disabled="disabled" aria-diabled="true"' : '')} />
+ <input class="form-check-input float-none${(disabled ? ' d-none"' : '')}" autocomplete="off" type="checkbox"${(priv.state === true ? ' checked' : '')}${(disabled ? ' disabled="disabled" aria-diabled="true"' : '')} />
</div>
</td>
`;
diff --git a/src/api/categories.js b/src/api/categories.js
index 1c4074d38e..f7d1c6be93 100644
--- a/src/api/categories.js
+++ b/src/api/categories.js
@@ -188,6 +188,8 @@ categoriesAPI.getPrivileges = async (caller, { cid }) => {
if (cid === 'admin') {
responsePayload = await privileges.admin.list(caller.uid);
+ } else if (cid === 'all') {
+ responsePayload = await privileges.categories.listAll();
} else if (!parseInt(cid, 10)) {
responsePayload = await privileges.global.list();
} else {
@@ -213,7 +215,12 @@ categoriesAPI.setPrivilege = async (caller, data) => {
if (!privs.length) {
throw new Error('[[error:invalid-data]]');
}
- if (parseInt(data.cid, 10) === 0) {
+ if (data.cid === 'all') {
+ const cids = await categories.getAllCidsFromSet('categories:cid');
+ const categoryPrivList = await privileges.categories.getPrivilegeList();
+ const categoryPrivs = privs.filter(priv => categoryPrivList.includes(priv));
+ await privileges.categories[type](categoryPrivs, cids, data.member);
+ } else if (parseInt(data.cid, 10) === 0) {
const adminPrivList = await privileges.admin.getPrivilegeList();
const adminPrivs = privs.filter(priv => adminPrivList.includes(priv));
if (adminPrivs.length) {
diff --git a/src/categories/create.js b/src/categories/create.js
index 86e147176f..d366bc99cb 100644
--- a/src/categories/create.js
+++ b/src/categories/create.js
@@ -231,6 +231,12 @@ module.exports = function (Categories) {
}
Categories.copyPrivilegesFrom = async function (fromCid, toCid, group, filter) {
+ // Guard against a non-numeric source (e.g. the "all categories" pseudo-cid). Its
+ // privilege sets do not exist, so every privilege held by the target would be treated
+ // as "not in source" and rescinded — turning a copy into a bulk revoke.
+ if (!utils.isNumber(fromCid) || !utils.isNumber(toCid)) {
+ throw new Error('[[error:invalid-data]]');
+ }
group = group || '';
let privsToCopy = privileges.categories.getPrivilegesByFilter(filter);
diff --git a/src/controllers/admin/privileges.js b/src/controllers/admin/privileges.js
index 8a33fb4625..cb7745d91b 100644
--- a/src/controllers/admin/privileges.js
+++ b/src/controllers/admin/privileges.js
@@ -9,15 +9,22 @@ const privilegesController = module.exports;
privilegesController.get = async function (req, res) {
const cid = req.params.cid ? parseInt(req.params.cid, 10) || 0 : 0;
const isAdminPriv = req.params.cid === 'admin';
+ const isAllCategories = req.params.cid === 'all';
let privilegesData;
- if (cid === 0) {
+ if (isAllCategories) {
+ privilegesData = await privileges.categories.listAll();
+ } else if (cid === 0) {
privilegesData = await (isAdminPriv ? privileges.admin.list(req.uid) : privileges.global.list());
} else if (utils.isNumber(cid)) {
privilegesData = await privileges.categories.list(cid);
}
const categoriesData = [{
+ cid: 'all',
+ name: '[[admin/manage/privileges:all-categories]]',
+ icon: 'fa-list',
+ }, {
cid: 0,
name: '[[admin/manage/privileges:global]]',
icon: 'fa-list',
@@ -27,10 +34,17 @@ privilegesController.get = async function (req, res) {
icon: 'fa-lock',
}];
+ let selectedCid = cid;
+ if (isAdminPriv) {
+ selectedCid = 'admin';
+ } else if (isAllCategories) {
+ selectedCid = 'all';
+ }
+
let selectedCategory;
categoriesData.forEach((category) => {
if (category) {
- category.selected = category.cid === (!isAdminPriv ? cid : 'admin');
+ category.selected = category.cid === selectedCid;
if (category.selected) {
selectedCategory = category;
@@ -46,7 +60,7 @@ privilegesController.get = async function (req, res) {
privileges: privilegesData,
categories: categoriesData,
selectedCategory,
- cid,
+ cid: isAllCategories ? 'all' : cid,
group,
isAdminPriv,
});
diff --git a/src/privileges/categories.js b/src/privileges/categories.js
index 4680e4d042..3577baac7e 100644
--- a/src/privileges/categories.js
+++ b/src/privileges/categories.js
@@ -91,6 +91,28 @@ privsCategories.list = async function (cid) {
return payload;
};
+// Aggregated view across every category. Privileges granted in only some categories are
+// reported with the state 'mixed' so the admin UI can show an indeterminate checkbox.
+privsCategories.listAll = async function () {
+ const cids = await categories.getAllCidsFromSet('categories:cid');
+ const keys = await utils.promiseParallel({
+ users: privsCategories.getUserPrivilegeList(),
+ groups: privsCategories.getGroupPrivilegeList(),
+ });
+
+ const payload = await utils.promiseParallel({
+ labelData: Array.from(_privilegeMap.values()),
+ users: helpers.getUserPrivilegesAll(cids, keys.users),
+ groups: helpers.getGroupPrivilegesAll(cids, keys.groups),
+ });
+ payload.keys = keys;
+
+ payload.columnCountUserOther = payload.labelData.length - privsCategories._coreSize;
+ payload.columnCountGroupOther = payload.labelData.length - privsCategories._coreSize;
+
+ return payload;
+};
+
privsCategories.get = async function (cid, uid) {
const privs = [
'topics:create', 'topics:read', 'topics:schedule',
diff --git a/src/privileges/helpers.js b/src/privileges/helpers.js
index ce61d72c32..25d6cd416e 100644
--- a/src/privileges/helpers.js
+++ b/src/privileges/helpers.js
@@ -207,6 +207,109 @@ helpers.getGroupPrivileges = async function (cid, groupPrivileges) {
return memberData;
};
+// Aggregate group privileges across multiple categories. For each group/privilege the
+// resulting state is `true` (granted in every cid), `false` (granted in none), or the
+// string 'mixed' (granted in some but not all).
+helpers.getGroupPrivilegesAll = async function (cids, groupPrivileges) {
+ if (!cids.length) {
+ return [];
+ }
+ const keys = [];
+ groupPrivileges.forEach((privilege) => {
+ cids.forEach((cid) => {
+ keys.push(`cid:${cid}:privileges:${privilege}`);
+ });
+ });
+ const [memberSets, allGroupNames] = await Promise.all([
+ groups.getMembersOfGroups(keys),
+ groups.getAllGroupNames('groups:createtime'),
+ ]);
+
+ const uniqueGroups = _.uniq(_.flatten(memberSets));
+ let groupNames = allGroupNames.filter(groupName => !groupName.includes(':privileges:') && uniqueGroups.includes(groupName));
+
+ groupNames = groups.ephemeralGroups.concat(groupNames);
+ moveToFront(groupNames, groups.BANNED_USERS);
+ moveToFront(groupNames, 'Global Moderators');
+ moveToFront(groupNames, 'unverified-users');
+ moveToFront(groupNames, 'verified-users');
+ moveToFront(groupNames, 'registered-users');
+
+ const adminIndex = groupNames.indexOf('administrators');
+ if (adminIndex !== -1) {
+ groupNames.splice(adminIndex, 1);
+ }
+
+ const numCids = cids.length;
+ const groupData = await groups.getGroupsFields(groupNames, ['private', 'system']);
+ const memberData = groupNames.map((member, index) => {
+ const memberPrivs = {};
+ for (let x = 0, numPrivs = groupPrivileges.length; x < numPrivs; x += 1) {
+ memberPrivs[groupPrivileges[x]] = aggregateState(memberSets, x, numCids, member);
+ }
+ const types = {};
+ for (const [key] of Object.entries(memberPrivs)) {
+ types[key] = getType(key);
+ }
+ return {
+ name: member,
+ privileges: memberPrivs,
+ types: types,
+ isPrivate: groupData[index] && !!groupData[index].private,
+ isSystem: groupData[index] && !!groupData[index].system,
+ };
+ });
+ return memberData;
+};
+
+// Aggregate user privileges across multiple categories (see getGroupPrivilegesAll).
+helpers.getUserPrivilegesAll = async function (cids, userPrivileges) {
+ if (!cids.length) {
+ return [];
+ }
+ const keys = [];
+ userPrivileges.forEach((privilege) => {
+ cids.forEach((cid) => {
+ keys.push(`cid:${cid}:privileges:${privilege}`);
+ });
+ });
+ let memberSets = await groups.getMembersOfGroups(keys);
+ memberSets = memberSets.map(set => set.map(uid => parseInt(uid, 10)));
+
+ const members = _.uniq(_.flatten(memberSets));
+ const memberData = await user.getUsersFields(members, ['picture', 'username', 'banned']);
+ const numCids = cids.length;
+
+ memberData.forEach((member) => {
+ member.privileges = {};
+ for (let x = 0, numPrivs = userPrivileges.length; x < numPrivs; x += 1) {
+ member.privileges[userPrivileges[x]] = aggregateState(memberSets, x, numCids, parseInt(member.uid, 10));
+ }
+ const types = {};
+ for (const [key] of Object.entries(member.privileges)) {
+ types[key] = getType(key);
+ }
+ member.types = types;
+ });
+
+ return memberData;
+};
+
+// memberSets is ordered [priv0/cid0, priv0/cid1, ..., priv1/cid0, ...]. For privilege
+// index `privIndex`, count how many of the `numCids` consecutive sets contain `member`.
+function aggregateState(memberSets, privIndex, numCids, member) {
+ let count = 0;
+ for (let c = 0; c < numCids; c += 1) {
+ if (memberSets[(privIndex * numCids) + c].includes(member)) {
+ count += 1;
+ }
+ }
+ if (count === 0) {
+ return false;
+ }
+ return count === numCids ? true : 'mixed';
+}
+
function getType(privilege) {
privilege = privilege.replace(/^groups:/, '');
diff --git a/src/views/admin/partials/privileges/category.tpl b/src/views/admin/partials/privileges/category.tpl
index 34874acdc3..907f84967b 100644
--- a/src/views/admin/partials/privileges/category.tpl
+++ b/src/views/admin/partials/privileges/category.tpl
@@ -38,6 +38,7 @@
{privileges.groups.name}
</td>
<td>
+ {{{ if (cid != "all") }}}
<div class="dropdown">
<button class="btn btn-outline-secondary btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
<i class="fa fa-copy"></i>
@@ -48,6 +49,7 @@
<li data-action="copyPrivilegesFromGroup"><a class="dropdown-item" href="#" role="menuitem">{{tx("admin/manage/categories:privileges.copy-group-privileges-from")}}</a></li>
</ul>
</div>
+ {{{ end }}}
</td>
<td class="">
<div class="form-check text-center">
@@ -67,6 +69,7 @@
<i class="fa fa-users"></i>
{{tx("admin/manage/categories:privileges.search-group")}}
</button>
+ {{{ if (cid != "all") }}}
<button type="button" class="btn btn-sm btn-outline-secondary text-nowrap" data-ajaxify="false" data-action="copyPrivilegesFrom">
<i class="fa fa-copy"></i>
{{tx("admin/manage/categories:privileges.copy-from-category")}}
@@ -79,6 +82,7 @@
<i class="fa fa-copy"></i>
{{tx("admin/manage/categories:privileges.copy-privileges-to-all-categories")}}
</button>
+ {{{ end }}}
</div>
</td>
</tr>