Node.js based forum software built for the modern web
feat: allow granting post edit permission to groups (#14625)
palmoni5f5f9439ee713
diff --git a/public/language/en-GB/topic.json b/public/language/en-GB/topic.jsonindex 52808ea5bd..5df6f69189 100644--- a/public/language/en-GB/topic.json+++ b/public/language/en-GB/topic.json@@ -189,7 +189,7 @@"move-posts-instruction": "Click the posts you want to move then enter a topic ID or go to the target topic","move-topic-instruction": "Select the target category and then click move","change-owner-instruction": "Click the posts you want to assign to another user",- "manage-editors-instruction": "Manage the users who can edit this post below.",+ "manage-editors-instruction": "Manage the users and groups who can edit this post below.","crossposts.instructions": "Select one or more categories to cross-post to. Topic(s) will be accessible from the original category and all cross-posted categories.","crossposts.listing": "This topic has been cross-posted to the following local categories:",diff --git a/public/src/client/topic/manage-editors.js b/public/src/client/topic/manage-editors.jsindex 2d874f31ba..b66aade964 100644--- a/public/src/client/topic/manage-editors.js+++ b/public/src/client/topic/manage-editors.js@@ -15,9 +15,12 @@ define('forum/topic/manage-editors', [}const pid = postEl.attr('data-pid');- let editors = await socket.emit('posts.getEditors', { pid: pid });+ const { users, groups } = await socket.emit('posts.getEditors', { pid: pid });+ let editors = users;+ let editorGroups = groups;app.parseAndTranslate('modals/manage-editors', {editors: editors,+ editorGroups: editorGroups,}, function (html) {modal = html;@@ -44,20 +47,41 @@ define('forum/topic/manage-editors', [}});+ autocomplete.group(modal.find('#editor-group-search'), function (ev, ui) {+ if (!editorGroups.includes(ui.item.group.name)) {+ editorGroups.push(ui.item.group.name);+ app.parseAndTranslate('modals/manage-editors', 'editorGroups', {+ editorGroups: editorGroups,+ }, function (html) {+ modal.find('[component="topic/editor-groups"]').html(html);+ modal.find('#editor-group-search').val('');+ });+ }+ });+modal.on('click', 'button.remove-user-icon', function () {const el = $(this).parents('[data-uid]');const uid = el.attr('data-uid');editors = editors.filter(e => String(e.uid) !== String(uid));el.remove();});++ modal.on('click', 'button.remove-group-icon', function () {+ const el = $(this).parents('[data-name]');+ const name = el.attr('data-name');+ editorGroups = editorGroups.filter(g => g !== name);+ el.remove();+ });});};function saveEditors(pid) {const uids = modal.find('[component="topic/editors"]>[data-uid]').map((i, el) => $(el).attr('data-uid')).get();+ const groups = modal.find('[component="topic/editor-groups"]>[data-name]')+ .map((i, el) => $(el).attr('data-name')).get();- socket.emit('posts.saveEditors', { pid: pid, uids: uids }, function (err) {+ socket.emit('posts.saveEditors', { pid: pid, uids: uids, groups: groups }, function (err) {if (err) {return alerts.error(err);}diff --git a/public/src/modules/autocomplete.js b/public/src/modules/autocomplete.jsindex 6a5dfc6165..6fa872eabf 100644--- a/public/src/modules/autocomplete.js+++ b/public/src/modules/autocomplete.js@@ -77,14 +77,14 @@ define('autocomplete', [input,onSelect,source: (request, response) => {- socket.emit('groups.search', {+ api.get('/groups', {query: request.term,- }, function (err, results) {+ }, function (err, result) {if (err) {return alerts.error(err);}- if (results && results.length) {- const names = results.map(function (group) {+ if (result && result.groups.length) {+ const names = result.groups.map(function (group) {return group && {label: group.name,value: group.name,diff --git a/src/groups/delete.js b/src/groups/delete.jsindex 0ded077de2..e737f3480c 100644--- a/src/groups/delete.js+++ b/src/groups/delete.js@@ -25,7 +25,8 @@ module.exports = function (Groups) {`group:${groupName}:pending`,`group:${groupName}:invited`,`group:${groupName}:owners`,- `group:${groupName}:member:pids`+ `group:${groupName}:member:pids`,+ `group:${groupName}:editor:pids`);});const sets = groupNames.map(groupName => `${groupName.toLowerCase()}:${groupName}`);@@ -34,6 +35,7 @@ module.exports = function (Groups) {.map(groupName => slugify(groupName));await removeGroupsFromPrivilegeGroups(groupNames);+ await removeGroupsFromPostEditors(groupNames);await Promise.all([db.deleteAll(keys),db.sortedSetRemove([@@ -52,6 +54,14 @@ module.exports = function (Groups) {plugins.hooks.fire('action:groups.destroy', { groups: groupsData });};+ async function removeGroupsFromPostEditors(groupNames) {+ await Promise.all(groupNames.map(+ groupName => batch.processSortedSet(`group:${groupName}:editor:pids`, async (pids) => {+ await db.setsRemove(pids.map(pid => `pid:${pid}:editors:groups`), groupName);+ }, { batch: 500 })+ ));+ }+async function removeGroupsFromPrivilegeGroups(groupNames) {await batch.processSortedSet('groups:createtime', async (otherGroups) => {const privilegeGroups = otherGroups.filter(Groups.isPrivilegeGroup);diff --git a/src/groups/update.js b/src/groups/update.jsindex 9dfa61f07f..a30b9faef3 100644--- a/src/groups/update.js+++ b/src/groups/update.js@@ -222,6 +222,7 @@ module.exports = function (Groups) {await db.rename(`group:${oldName}:pending`, `group:${newName}:pending`);await db.rename(`group:${oldName}:invited`, `group:${newName}:invited`);await db.rename(`group:${oldName}:member:pids`, `group:${newName}:member:pids`);+ await updatePostEditorGroups(oldName, newName);await renameGroupsMember(['groups:createtime', 'groups:visible:createtime', 'groups:visible:memberCount'], oldName, newName);await renameGroupsMember(['groups:visible:name'], `${oldName.toLowerCase()}:${oldName}`, `${newName.toLowerCase()}:${newName}`);@@ -246,6 +247,15 @@ module.exports = function (Groups) {}, {});}+ async function updatePostEditorGroups(oldName, newName) {+ await batch.processSortedSet(`group:${oldName}:editor:pids`, async (pids) => {+ const keys = pids.map(pid => `pid:${pid}:editors:groups`);+ await db.setsRemove(keys, oldName);+ await db.setsAdd(keys, newName);+ }, { batch: 500 });+ await db.rename(`group:${oldName}:editor:pids`, `group:${newName}:editor:pids`);+ }+async function renameGroupsMember(keys, oldName, newName) {const isMembers = await db.isMemberOfSortedSets(keys, oldName);keys = keys.filter((key, index) => isMembers[index]);diff --git a/src/posts/delete.js b/src/posts/delete.jsindex 9235f37111..86da19421b 100644--- a/src/posts/delete.js+++ b/src/posts/delete.js@@ -84,7 +84,7 @@ module.exports = function (Posts) {], pids),Posts.attachments.empty(pids),activitypub.notes.delete(pids),- db.deleteAll(pids.map(pid => `pid:${pid}:editors`)),+ deleteFromEditors(pids),]);await resolveFlags(postData, uid);@@ -224,6 +224,21 @@ module.exports = function (Posts) {await db.setObjectBulk(parentPids.map((pid, index) => [`post:${pid}`, { replies: counts[index] }]));}+ async function deleteFromEditors(pids) {+ const groupNames = await db.getSetsMembers(pids.map(pid => `pid:${pid}:editors:groups`));+ const bulkRemove = [];+ pids.forEach((pid, index) => {+ groupNames[index].forEach((groupName) => {+ bulkRemove.push([`group:${groupName}:editor:pids`, pid]);+ });+ });+ await db.sortedSetRemoveBulk(bulkRemove);+ await db.deleteAll([+ ...pids.map(pid => `pid:${pid}:editors`),+ ...pids.map(pid => `pid:${pid}:editors:groups`),+ ]);+ }+async function deleteFromGroups(pids) {const groupNames = await db.getSortedSetMembers('groups:visible:createtime');const keys = groupNames.map(groupName => `group:${groupName}:member:pids`);diff --git a/src/privileges/posts.js b/src/privileges/posts.jsindex 84baf64b6c..d1d3034d83 100644--- a/src/privileges/posts.js+++ b/src/privileges/posts.js@@ -8,6 +8,7 @@ const meta = require('../meta');const posts = require('../posts');const topics = require('../topics');const categories = require('../categories');+const groups = require('../groups');const user = require('../user');const activitypub = require('../activitypub');const helpers = require('./helpers');@@ -145,6 +146,7 @@ privsPosts.canEdit = async function (pid, uid) {isMod: posts.isModerator([pid], uid),isOwner: posts.isOwner(pid, uid),isEditor: db.isSetMember(`pid:${pid}:editors`, uid),+ isGroupEditor: isGroupEditor(pid, uid),edit: privsPosts.can('posts:edit', pid, uid),postData: posts.getPostFields(pid, ['tid', 'timestamp', 'deleted', 'deleterUid']),userData: user.getUserFields(uid, ['reputation']),@@ -187,11 +189,19 @@ privsPosts.canEdit = async function (pid, uid) {const result = await plugins.hooks.fire('filter:privileges.posts.edit', results);return {- flag: result.edit && (result.isOwner || result.isEditor || result.isMod),+ flag: result.edit && (result.isOwner || result.isEditor || result.isGroupEditor || result.isMod),message: '[[error:no-privileges]]',};};+async function isGroupEditor(pid, uid) {+ const groupNames = await db.getSetMembers(`pid:${pid}:editors:groups`);+ if (!groupNames.length) {+ return false;+ }+ return await groups.isMemberOfAny(uid, groupNames);+}+privsPosts.canDelete = async function (pid, uid) {const postData = await posts.getPostFields(pid, ['uid', 'tid', 'timestamp', 'deleterUid']);const results = await utils.promiseParallel({diff --git a/src/socket.io/posts/tools.js b/src/socket.io/posts/tools.jsindex e51494f7fa..97de85d4ce 100644--- a/src/socket.io/posts/tools.js+++ b/src/socket.io/posts/tools.js@@ -1,10 +1,12 @@'use strict';const nconf = require('nconf');+const _ = require('lodash');const db = require('../../database');const posts = require('../../posts');const flags = require('../../flags');+const groups = require('../../groups');const privileges = require('../../privileges');const plugins = require('../../plugins');const social = require('../../social');@@ -90,20 +92,49 @@ module.exports = function (SocketPosts) {throw new Error('[[error:invalid-data]]');}await checkEditorPrivilege(socket.uid, data.pid);- const editorUids = await db.getSetMembers(`pid:${data.pid}:editors`);- const userData = await user.getUsersFields(editorUids, ['username', 'userslug', 'picture']);- return userData;+ const [editorUids, groupNames] = await Promise.all([+ db.getSetMembers(`pid:${data.pid}:editors`),+ db.getSetMembers(`pid:${data.pid}:editors:groups`),+ ]);+ const users = await user.getUsersFields(editorUids, ['username', 'userslug', 'picture']);+ return { users: users, groups: groupNames.sort() };};SocketPosts.saveEditors = async function (socket, data) {- if (!data || !data.pid || !Array.isArray(data.uids)) {+ if (!data || !data.pid || !Array.isArray(data.uids) || (data.groups !== undefined && !Array.isArray(data.groups))) {throw new Error('[[error:invalid-data]]');}await checkEditorPrivilege(socket.uid, data.pid);- await db.delete(`pid:${data.pid}:editors`);- await db.setAdd(`pid:${data.pid}:editors`, data.uids);+ const groupNames = await filterEditorGroups(data.groups || []);+ const currentGroups = await db.getSetMembers(`pid:${data.pid}:editors:groups`);+ const addedGroups = groupNames.filter(name => !currentGroups.includes(name));+ const removedGroups = currentGroups.filter(name => !groupNames.includes(name));++ await Promise.all([+ db.delete(`pid:${data.pid}:editors`),+ db.delete(`pid:${data.pid}:editors:groups`),+ db.sortedSetRemove(removedGroups.map(name => `group:${name}:editor:pids`), data.pid),+ ]);+ await Promise.all([+ db.setAdd(`pid:${data.pid}:editors`, data.uids),+ db.setAdd(`pid:${data.pid}:editors:groups`, groupNames),+ db.sortedSetAddBulk(addedGroups.map(name => [`group:${name}:editor:pids`, Date.now(), data.pid])),+ ]);};+ async function filterEditorGroups(groupNames) {+ groupNames = _.uniq(groupNames.filter(+ name => name && typeof name === 'string' &&+ !groups.isPrivilegeGroup(name) &&+ !groups.ephemeralGroups.includes(name)+ ));+ if (!groupNames.length) {+ return [];+ }+ const exists = await groups.exists(groupNames);+ return groupNames.filter((name, index) => exists[index]);+ }+async function checkEditorPrivilege(uid, pid) {const cid = await posts.getCidByPid(pid);const [isAdminOrMod, owner] = await Promise.all([diff --git a/src/views/modals/manage-editors.tpl b/src/views/modals/manage-editors.tplindex 66af94fca9..d61c70bd55 100644--- a/src/views/modals/manage-editors.tpl+++ b/src/views/modals/manage-editors.tpl@@ -13,7 +13,7 @@</span></div></div>- <div class="d-flex flex-wrap" component="topic/editors">+ <div class="d-flex flex-wrap mb-3" component="topic/editors">{{{ each editors }}}<div class="badge text-bg-light m-1 p-1 border d-inline-flex gap-1 align-items-center" data-uid="{./uid}">{{buildAvatar(@value, "24px", true)}}@@ -24,6 +24,26 @@</div>{{{ end }}}</div>+ <div class="mb-3">+ <label class="form-label" for="editor-group-search"><strong>{{tx("groups:groups")}}</strong></label>+ <div class="input-group">+ <input id="editor-group-search" type="text" class="form-control" name="editor-group-search">+ <span class="input-group-text" type="button">+ <i class="fa fa-search"></i>+ </span>+ </div>+ </div>+ <div class="d-flex flex-wrap" component="topic/editor-groups">+ {{{ each editorGroups }}}+ <div class="badge text-bg-light m-1 p-1 border d-inline-flex gap-1 align-items-center" data-name="{@value}">+ <i class="fa fa-fw fa-users text-muted"></i>+ <span>{@value}</span>+ <button class="btn btn-ghost btn-sm p-0 remove-group-icon">+ <i class="fa fa-fw fa-times"></i>+ </button>+ </div>+ {{{ end }}}+ </div></div><div class="card-footer text-end"><button class="btn btn-link btn-sm" id="manage_editors_cancel">{{tx("global:buttons.close")}}</button>diff --git a/test/posts.js b/test/posts.jsindex 222b628c80..32e1ede9ab 100644--- a/test/posts.js+++ b/test/posts.js@@ -1228,8 +1228,8 @@ describe('Post\'s', () => {uids: [editorUid],});- const userData = await socketPosts.getEditors({ uid: ownerUid }, { pid: pid });- assert.strictEqual(userData[0].username, 'editor user');+ const { users } = await socketPosts.getEditors({ uid: ownerUid }, { pid: pid });+ assert.strictEqual(users[0].username, 'editor user');const result = await apiPosts.edit({ uid: editorUid }, { pid, content: 'edited by editor' });assert.strictEqual(Object.hasOwn(result, 'ip'), false);@@ -1238,6 +1238,133 @@ describe('Post\'s', () => {meta.config.trackIpPerPost = oldValue;});++ it('should allow members of an editor group to edit the post', async () => {+ const ownerUid = await user.create({ username: 'group owner user' });+ const memberUid = await user.create({ username: 'group editor user' });+ const outsiderUid = await user.create({ username: 'not a group member' });+ await groups.create({ name: 'editors-test-group' });+ await groups.join('editors-test-group', memberUid);++ const topic = await topics.post({+ uid: ownerUid,+ cid,+ title: 'a topic for group editor testing',+ content: 'Some text here for the OP',+ });+ const { pid } = topic.postData;+ await socketPosts.saveEditors({ uid: ownerUid }, {+ pid: pid,+ uids: [],+ groups: ['editors-test-group'],+ });++ const { groups: groupNames } = await socketPosts.getEditors({ uid: ownerUid }, { pid: pid });+ assert.deepStrictEqual(groupNames, ['editors-test-group']);+ assert(await db.isSortedSetMember('group:editors-test-group:editor:pids', pid));++ await apiPosts.edit({ uid: memberUid }, { pid, content: 'edited by group member' });+ assert.strictEqual(await posts.getPostField(pid, 'content'), 'edited by group member');++ const canEdit = await privileges.posts.canEdit(pid, outsiderUid);+ assert.strictEqual(canEdit.flag, false);+ });++ it('should keep group editors working when the group is renamed', async () => {+ const ownerUid = await user.create({ username: 'rename owner user' });+ const memberUid = await user.create({ username: 'rename editor user' });+ await groups.create({ name: 'editors-rename-group' });+ await groups.join('editors-rename-group', memberUid);++ const topic = await topics.post({+ uid: ownerUid,+ cid,+ title: 'a topic for group rename testing',+ content: 'Some text here for the OP',+ });+ const { pid } = topic.postData;+ await socketPosts.saveEditors({ uid: ownerUid }, {+ pid: pid,+ uids: [],+ groups: ['editors-rename-group'],+ });++ await groups.update('editors-rename-group', { name: 'editors-renamed-group' });++ const { groups: groupNames } = await socketPosts.getEditors({ uid: ownerUid }, { pid: pid });+ assert.deepStrictEqual(groupNames, ['editors-renamed-group']);+ assert(await db.isSortedSetMember('group:editors-renamed-group:editor:pids', pid));+ assert(!await db.exists('group:editors-rename-group:editor:pids'));++ const canEdit = await privileges.posts.canEdit(pid, memberUid);+ assert.strictEqual(canEdit.flag, true);+ });++ it('should remove group from post editors when the group is deleted', async () => {+ const ownerUid = await user.create({ username: 'delete owner user' });+ await groups.create({ name: 'editors-delete-group' });++ const topic = await topics.post({+ uid: ownerUid,+ cid,+ title: 'a topic for group delete testing',+ content: 'Some text here for the OP',+ });+ const { pid } = topic.postData;+ await socketPosts.saveEditors({ uid: ownerUid }, {+ pid: pid,+ uids: [],+ groups: ['editors-delete-group'],+ });++ await groups.destroy('editors-delete-group');++ const { groups: groupNames } = await socketPosts.getEditors({ uid: ownerUid }, { pid: pid });+ assert.deepStrictEqual(groupNames, []);+ assert(!await db.exists('group:editors-delete-group:editor:pids'));+ });++ it('should clean up editor groups when the post is purged', async () => {+ const ownerUid = await user.create({ username: 'purge owner user' });+ await groups.create({ name: 'editors-purge-group' });++ const topic = await topics.post({+ uid: ownerUid,+ cid,+ title: 'a topic for group purge testing',+ content: 'Some text here for the OP',+ });+ const { pid } = topic.postData;+ await socketPosts.saveEditors({ uid: ownerUid }, {+ pid: pid,+ uids: [],+ groups: ['editors-purge-group'],+ });++ await posts.purge([pid], ownerUid);++ assert(!await db.exists(`pid:${pid}:editors:groups`));+ assert(!await db.isSortedSetMember('group:editors-purge-group:editor:pids', pid));+ });++ it('should not save privilege or non-existent groups as editors', async () => {+ const ownerUid = await user.create({ username: 'filter owner user' });+ const topic = await topics.post({+ uid: ownerUid,+ cid,+ title: 'a topic for group filter testing',+ content: 'Some text here for the OP',+ });+ const { pid } = topic.postData;+ await socketPosts.saveEditors({ uid: ownerUid }, {+ pid: pid,+ uids: [],+ groups: ['cid:0:privileges:admin:admincp', 'guests', 'does-not-exist-group'],+ });++ const { groups: groupNames } = await socketPosts.getEditors({ uid: ownerUid }, { pid: pid });+ assert.deepStrictEqual(groupNames, []);+ });});describe('Topic Backlinks', () => {