feat: #7743, privileges

v1.18.x
Barış Soner Uşaklı 6 years ago
parent 627ecaf6bb
commit faccb191ec

@ -1,232 +1,164 @@
'use strict'; 'use strict';
var async = require('async'); const _ = require('lodash');
var _ = require('lodash');
var categories = require('../categories'); const categories = require('../categories');
var user = require('../user'); const user = require('../user');
var groups = require('../groups'); const groups = require('../groups');
var helpers = require('./helpers'); const helpers = require('./helpers');
var plugins = require('../plugins'); const plugins = require('../plugins');
const utils = require('../utils');
module.exports = function (privileges) { module.exports = function (privileges) {
privileges.categories = {}; privileges.categories = {};
privileges.categories.list = function (cid, callback) {
// Method used in admin/category controller to show all users/groups with privs in that given cid // Method used in admin/category controller to show all users/groups with privs in that given cid
async.waterfall([ privileges.categories.list = async function (cid) {
function (next) { async function getLabels() {
async.parallel({ return await utils.promiseParallel({
labels: function (next) { users: plugins.fireHook('filter:privileges.list_human', privileges.privilegeLabels.slice()),
async.parallel({ groups: plugins.fireHook('filter:privileges.groups.list_human', privileges.privilegeLabels.slice()),
users: async.apply(plugins.fireHook, 'filter:privileges.list_human', privileges.privilegeLabels.slice()), });
groups: async.apply(plugins.fireHook, 'filter:privileges.groups.list_human', privileges.privilegeLabels.slice()), }
}, next);
}, const payload = await utils.promiseParallel({
users: function (next) { labels: getLabels(),
helpers.getUserPrivileges(cid, 'filter:privileges.list', privileges.userPrivilegeList, next); users: helpers.getUserPrivileges(cid, 'filter:privileges.list', privileges.userPrivilegeList),
}, groups: helpers.getGroupPrivileges(cid, 'filter:privileges.groups.list', privileges.groupPrivilegeList),
groups: function (next) { });
helpers.getGroupPrivileges(cid, 'filter:privileges.groups.list', privileges.groupPrivilegeList, next);
},
}, next);
},
function (payload, next) {
// This is a hack because I can't do {labels.users.length} to echo the count in templates.js // This is a hack because I can't do {labels.users.length} to echo the count in templates.js
payload.columnCountUser = payload.labels.users.length + 2; payload.columnCountUser = payload.labels.users.length + 2;
payload.columnCountUserOther = payload.labels.users.length - privileges.privilegeLabels.length; payload.columnCountUserOther = payload.labels.users.length - privileges.privilegeLabels.length;
payload.columnCountGroup = payload.labels.groups.length + 2; payload.columnCountGroup = payload.labels.groups.length + 2;
payload.columnCountGroupOther = payload.labels.groups.length - privileges.privilegeLabels.length; payload.columnCountGroupOther = payload.labels.groups.length - privileges.privilegeLabels.length;
next(null, payload); return payload;
},
], callback);
}; };
privileges.categories.get = function (cid, uid, callback) { privileges.categories.get = async function (cid, uid) {
var privs = ['topics:create', 'topics:read', 'topics:tag', 'read']; const privs = ['topics:create', 'topics:read', 'topics:tag', 'read'];
async.waterfall([
function (next) { const [userPrivileges, isAdministrator, isModerator] = await Promise.all([
async.parallel({ helpers.isUserAllowedTo(privs, uid, cid),
privileges: function (next) { user.isAdministrator(uid),
helpers.isUserAllowedTo(privs, uid, cid, next); user.isModerator(uid, cid),
}, ]);
isAdministrator: function (next) {
user.isAdministrator(uid, next); const privData = _.zipObject(privs, userPrivileges);
}, const isAdminOrMod = isAdministrator || isModerator;
isModerator: function (next) {
user.isModerator(uid, cid, next); return await plugins.fireHook('filter:privileges.categories.get', {
}, 'topics:create': privData['topics:create'] || isAdministrator,
}, next); 'topics:read': privData['topics:read'] || isAdministrator,
}, 'topics:tag': privData['topics:tag'] || isAdministrator,
function (results, next) { read: privData.read || isAdministrator,
var privData = _.zipObject(privs, results.privileges);
var isAdminOrMod = results.isAdministrator || results.isModerator;
plugins.fireHook('filter:privileges.categories.get', {
'topics:create': privData['topics:create'] || results.isAdministrator,
'topics:read': privData['topics:read'] || results.isAdministrator,
'topics:tag': privData['topics:tag'] || results.isAdministrator,
read: privData.read || results.isAdministrator,
cid: cid, cid: cid,
uid: uid, uid: uid,
editable: isAdminOrMod, editable: isAdminOrMod,
view_deleted: isAdminOrMod, view_deleted: isAdminOrMod,
isAdminOrMod: isAdminOrMod, isAdminOrMod: isAdminOrMod,
}, next); });
},
], callback);
}; };
privileges.categories.isAdminOrMod = function (cid, uid, callback) { privileges.categories.isAdminOrMod = async function (cid, uid) {
if (parseInt(uid, 10) <= 0) { if (parseInt(uid, 10) <= 0) {
return setImmediate(callback, null, false); return false;
} }
helpers.some([ const [isAdmin, isMod] = await Promise.all([
function (next) { user.isAdministrator(uid),
user.isModerator(uid, cid, next); user.isModerator(uid, cid),
}, ]);
function (next) { return isAdmin || isMod;
user.isAdministrator(uid, next);
},
], callback);
}; };
privileges.categories.isUserAllowedTo = function (privilege, cid, uid, callback) { privileges.categories.isUserAllowedTo = async function (privilege, cid, uid) {
if (!cid) { if (!cid) {
return setImmediate(callback, null, false); return false;
} }
if (Array.isArray(cid)) { const results = await helpers.isUserAllowedTo(privilege, uid, Array.isArray(cid) ? cid : [cid]);
helpers.isUserAllowedTo(privilege, uid, cid, function (err, results) {
callback(err, Array.isArray(results) && results.length ? results : false); if (Array.isArray(results) && results.length) {
}); return Array.isArray(cid) ? results : results[0];
} else {
helpers.isUserAllowedTo(privilege, uid, [cid], function (err, results) {
callback(err, Array.isArray(results) && results.length ? results[0] : false);
});
} }
return false;
}; };
privileges.categories.can = function (privilege, cid, uid, callback) { privileges.categories.can = async function (privilege, cid, uid) {
if (!cid) { if (!cid) {
return setImmediate(callback, null, false); return false;
} }
async.waterfall([ const [disabled, isAdmin, isAllowed] = await Promise.all([
function (next) { categories.getCategoryField(cid, 'disabled'),
async.parallel({ user.isAdministrator(uid),
disabled: async.apply(categories.getCategoryField, cid, 'disabled'), privileges.categories.isUserAllowedTo(privilege, cid, uid),
isAdmin: async.apply(user.isAdministrator, uid), ]);
isAllowed: async.apply(privileges.categories.isUserAllowedTo, privilege, cid, uid), return !disabled && (isAllowed || isAdmin);
}, next);
},
function (results, next) {
next(null, !results.disabled && (results.isAllowed || results.isAdmin));
},
], callback);
}; };
privileges.categories.filterCids = function (privilege, cids, uid, callback) { privileges.categories.filterCids = async function (privilege, cids, uid) {
if (!Array.isArray(cids) || !cids.length) { if (!Array.isArray(cids) || !cids.length) {
return callback(null, []); return [];
} }
cids = _.uniq(cids); cids = _.uniq(cids);
const results = await privileges.categories.getBase(privilege, cids, uid);
async.waterfall([ return cids.filter(function (cid, index) {
function (next) { return !!cid && !results.categories[index].disabled && (results.allowedTo[index] || results.isAdmin);
privileges.categories.getBase(privilege, cids, uid, next);
},
function (results, next) {
cids = cids.filter(function (cid, index) {
return !results.categories[index].disabled &&
(results.allowedTo[index] || results.isAdmin);
}); });
next(null, cids.filter(Boolean));
},
], callback);
}; };
privileges.categories.getBase = function (privilege, cids, uid, callback) { privileges.categories.getBase = async function (privilege, cids, uid) {
async.parallel({ return await utils.promiseParallel({
categories: function (next) { categories: categories.getCategoriesFields(cids, ['disabled']),
categories.getCategoriesFields(cids, ['disabled'], next); allowedTo: helpers.isUserAllowedTo(privilege, uid, cids),
}, isAdmin: user.isAdministrator(uid),
allowedTo: function (next) { });
helpers.isUserAllowedTo(privilege, uid, cids, next);
},
isAdmin: function (next) {
user.isAdministrator(uid, next);
},
}, callback);
}; };
privileges.categories.filterUids = function (privilege, cid, uids, callback) { privileges.categories.filterUids = async function (privilege, cid, uids) {
if (!uids.length) { if (!uids.length) {
return setImmediate(callback, null, []); return [];
} }
uids = _.uniq(uids); uids = _.uniq(uids);
async.waterfall([ const [allowedTo, isAdmins] = await Promise.all([
function (next) { helpers.isUsersAllowedTo(privilege, uids, cid),
async.parallel({ user.isAdministrator(uids),
allowedTo: function (next) { ]);
helpers.isUsersAllowedTo(privilege, uids, cid, next); return uids.filter((uid, index) => allowedTo[index] || isAdmins[index]);
},
isAdmins: function (next) {
user.isAdministrator(uids, next);
},
}, next);
},
function (results, next) {
uids = uids.filter(function (uid, index) {
return results.allowedTo[index] || results.isAdmins[index];
});
next(null, uids);
},
], callback);
}; };
privileges.categories.give = function (privileges, cid, groupName, callback) { privileges.categories.give = async function (privileges, cid, groupName) {
helpers.giveOrRescind(groups.join, privileges, cid, groupName, callback); await helpers.giveOrRescind(groups.join, privileges, cid, groupName);
}; };
privileges.categories.rescind = function (privileges, cid, groupName, callback) { privileges.categories.rescind = async function (privileges, cid, groupName) {
helpers.giveOrRescind(groups.leave, privileges, cid, groupName, callback); await helpers.giveOrRescind(groups.leave, privileges, cid, groupName);
}; };
privileges.categories.canMoveAllTopics = function (currentCid, targetCid, uid, callback) { privileges.categories.canMoveAllTopics = async function (currentCid, targetCid, uid) {
async.waterfall([ const [isAdmin, isModerators] = await Promise.all([
function (next) { user.isAdministrator(uid),
async.parallel({ user.isModerator(uid, [currentCid, targetCid]),
isAdmin: async.apply(user.isAdministrator, uid), ]);
isModerators: async.apply(user.isModerator, uid, [currentCid, targetCid]), return isAdmin || !isModerators.includes(false);
}, next);
},
function (results, next) {
next(null, results.isAdmin || !results.isModerators.includes(false));
},
], callback);
}; };
privileges.categories.userPrivileges = function (cid, uid, callback) { privileges.categories.userPrivileges = async function (cid, uid) {
var tasks = {}; const tasks = {};
privileges.userPrivilegeList.forEach(function (privilege) { privileges.userPrivilegeList.forEach(function (privilege) {
tasks[privilege] = async.apply(groups.isMember, uid, 'cid:' + cid + ':privileges:' + privilege); tasks[privilege] = groups.isMember(uid, 'cid:' + cid + ':privileges:' + privilege);
}); });
return await utils.promiseParallel(tasks);
async.parallel(tasks, callback);
}; };
privileges.categories.groupPrivileges = function (cid, groupName, callback) { privileges.categories.groupPrivileges = async function (cid, groupName) {
var tasks = {}; const tasks = {};
privileges.groupPrivilegeList.forEach(function (privilege) { privileges.groupPrivilegeList.forEach(function (privilege) {
tasks[privilege] = async.apply(groups.isMember, groupName, 'cid:' + cid + ':privileges:' + privilege); tasks[privilege] = groups.isMember(groupName, 'cid:' + cid + ':privileges:' + privilege);
}); });
return await utils.promiseParallel(tasks);
async.parallel(tasks, callback);
}; };
}; };

@ -1,13 +1,13 @@
'use strict'; 'use strict';
var async = require('async'); const _ = require('lodash');
var _ = require('lodash');
var user = require('../user'); const user = require('../user');
var groups = require('../groups'); const groups = require('../groups');
var helpers = require('./helpers'); const helpers = require('./helpers');
var plugins = require('../plugins'); const plugins = require('../plugins');
const utils = require('../utils');
module.exports = function (privileges) { module.exports = function (privileges) {
privileges.global = {}; privileges.global = {};
@ -44,108 +44,79 @@ module.exports = function (privileges) {
'group:create', 'group:create',
]; ];
privileges.global.groupPrivilegeList = privileges.global.userPrivilegeList.map(function (privilege) { privileges.global.groupPrivilegeList = privileges.global.userPrivilegeList.map(privilege => 'groups:' + privilege);
return 'groups:' + privilege;
});
privileges.global.list = function (callback) { privileges.global.list = async function () {
async.waterfall([ async function getLabels() {
function (next) { return await utils.promiseParallel({
async.parallel({ users: plugins.fireHook('filter:privileges.global.list_human', privileges.global.privilegeLabels.slice()),
labels: function (next) { groups: plugins.fireHook('filter:privileges.global.groups.list_human', privileges.global.privilegeLabels.slice()),
async.parallel({ });
users: async.apply(plugins.fireHook, 'filter:privileges.global.list_human', privileges.global.privilegeLabels.slice()), }
groups: async.apply(plugins.fireHook, 'filter:privileges.global.groups.list_human', privileges.global.privilegeLabels.slice()), const payload = await utils.promiseParallel({
}, next); labels: getLabels(),
}, users: helpers.getUserPrivileges(0, 'filter:privileges.global.list', privileges.global.userPrivilegeList),
users: function (next) { groups: helpers.getGroupPrivileges(0, 'filter:privileges.global.groups.list', privileges.global.groupPrivilegeList),
helpers.getUserPrivileges(0, 'filter:privileges.global.list', privileges.global.userPrivilegeList, next); });
},
groups: function (next) {
helpers.getGroupPrivileges(0, 'filter:privileges.global.groups.list', privileges.global.groupPrivilegeList, next);
},
}, next);
},
function (payload, next) {
// This is a hack because I can't do {labels.users.length} to echo the count in templates.js // This is a hack because I can't do {labels.users.length} to echo the count in templates.js
payload.columnCount = payload.labels.users.length + 2; payload.columnCount = payload.labels.users.length + 2;
next(null, payload); return payload;
},
], callback);
};
privileges.global.get = function (uid, callback) {
async.waterfall([
function (next) {
async.parallel({
privileges: function (next) {
helpers.isUserAllowedTo(privileges.global.userPrivilegeList, uid, 0, next);
},
isAdministrator: function (next) {
user.isAdministrator(uid, next);
},
}, next);
},
function (results, next) {
var privData = _.zipObject(privileges.global.userPrivilegeList, results.privileges);
plugins.fireHook('filter:privileges.global.get', {
chat: privData.chat || results.isAdministrator,
'upload:post:image': privData['upload:post:image'] || results.isAdministrator,
'upload:post:file': privData['upload:post:file'] || results.isAdministrator,
'search:content': privData['search:content'] || results.isAdministrator,
'search:users': privData['search:users'] || results.isAdministrator,
'search:tags': privData['search:tags'] || results.isAdministrator,
'view:users': privData['view:users'] || results.isAdministrator,
'view:tags': privData['view:tags'] || results.isAdministrator,
'view:groups': privData['view:groups'] || results.isAdministrator,
}, next);
},
], callback);
}; };
privileges.global.can = function (privilege, uid, callback) { privileges.global.get = async function (uid) {
helpers.some([ const [userPrivileges, isAdministrator] = await Promise.all([
function (next) { helpers.isUserAllowedTo(privileges.global.userPrivilegeList, uid, 0),
helpers.isUserAllowedTo(privilege, uid, [0], function (err, results) { user.isAdministrator(uid),
next(err, Array.isArray(results) && results.length ? results[0] : false); ]);
const privData = _.zipObject(privileges.global.userPrivilegeList, userPrivileges);
return await plugins.fireHook('filter:privileges.global.get', {
chat: privData.chat || isAdministrator,
'upload:post:image': privData['upload:post:image'] || isAdministrator,
'upload:post:file': privData['upload:post:file'] || isAdministrator,
'search:content': privData['search:content'] || isAdministrator,
'search:users': privData['search:users'] || isAdministrator,
'search:tags': privData['search:tags'] || isAdministrator,
'view:users': privData['view:users'] || isAdministrator,
'view:tags': privData['view:tags'] || isAdministrator,
'view:groups': privData['view:groups'] || isAdministrator,
}); });
},
function (next) {
user.isAdministrator(uid, next);
},
], callback);
}; };
privileges.global.canGroup = function (privilege, groupName, callback) { privileges.global.can = async function (privilege, uid) {
groups.isMember(groupName, 'cid:0:privileges:groups:' + privilege, callback); const [isAdministrator, isUserAllowedTo] = await Promise.all([
user.isAdministrator(uid),
helpers.isUserAllowedTo(privilege, uid, [0]),
]);
return isAdministrator || isUserAllowedTo[0];
}; };
privileges.global.give = function (privileges, groupName, callback) { privileges.global.canGroup = async function (privilege, groupName) {
helpers.giveOrRescind(groups.join, privileges, 0, groupName, callback); return await groups.isMember(groupName, 'cid:0:privileges:groups:' + privilege);
}; };
privileges.global.rescind = function (privileges, groupName, callback) { privileges.global.give = async function (privileges, groupName) {
helpers.giveOrRescind(groups.leave, privileges, 0, groupName, callback); await helpers.giveOrRescind(groups.join, privileges, 0, groupName);
}; };
privileges.global.userPrivileges = function (uid, callback) { privileges.global.rescind = async function (privileges, groupName) {
var tasks = {}; await helpers.giveOrRescind(groups.leave, privileges, 0, groupName);
};
privileges.global.userPrivileges = async function (uid) {
const tasks = {};
privileges.global.userPrivilegeList.forEach(function (privilege) { privileges.global.userPrivilegeList.forEach(function (privilege) {
tasks[privilege] = async.apply(groups.isMember, uid, 'cid:0:privileges:' + privilege); tasks[privilege] = groups.isMember(uid, 'cid:0:privileges:' + privilege);
}); });
return await utils.promiseParallel(tasks);
async.parallel(tasks, callback);
}; };
privileges.global.groupPrivileges = function (groupName, callback) { privileges.global.groupPrivileges = async function (groupName) {
var tasks = {}; const tasks = {};
privileges.global.groupPrivilegeList.forEach(function (privilege) { privileges.global.groupPrivilegeList.forEach(function (privilege) {
tasks[privilege] = async.apply(groups.isMember, groupName, 'cid:0:privileges:' + privilege); tasks[privilege] = groups.isMember(groupName, 'cid:0:privileges:' + privilege);
}); });
return await utils.promiseParallel(tasks);
async.parallel(tasks, callback);
}; };
}; };

@ -1,139 +1,94 @@
'use strict'; 'use strict';
var async = require('async'); const _ = require('lodash');
var _ = require('lodash');
var groups = require('../groups'); const groups = require('../groups');
var user = require('../user'); const user = require('../user');
var plugins = require('../plugins'); const plugins = require('../plugins');
var helpers = module.exports; const helpers = module.exports;
var uidToSystemGroup = { const uidToSystemGroup = {
0: 'guests', 0: 'guests',
'-1': 'spiders', '-1': 'spiders',
}; };
helpers.some = function (tasks, callback) { helpers.isUserAllowedTo = async function (privilege, uid, cid) {
async.some(tasks, function (task, next) {
task(next);
}, callback);
};
helpers.isUserAllowedTo = function (privilege, uid, cid, callback) {
if (Array.isArray(privilege) && !Array.isArray(cid)) { if (Array.isArray(privilege) && !Array.isArray(cid)) {
isUserAllowedToPrivileges(privilege, uid, cid, callback); return await isUserAllowedToPrivileges(privilege, uid, cid);
} else if (Array.isArray(cid) && !Array.isArray(privilege)) { } else if (Array.isArray(cid) && !Array.isArray(privilege)) {
isUserAllowedToCids(privilege, uid, cid, callback); return await isUserAllowedToCids(privilege, uid, cid);
} else {
return callback(new Error('[[error:invalid-data]]'));
} }
throw new Error('[[error:invalid-data]]');
}; };
function isUserAllowedToCids(privilege, uid, cids, callback) { async function isUserAllowedToCids(privilege, uid, cids) {
if (parseInt(uid, 10) <= 0) { if (parseInt(uid, 10) <= 0) {
return isSystemGroupAllowedToCids(privilege, uid, cids, callback); return await isSystemGroupAllowedToCids(privilege, uid, cids);
} }
var userKeys = []; const userKeys = [];
var groupKeys = []; const groupKeys = [];
cids.forEach(function (cid) { cids.forEach(function (cid) {
userKeys.push('cid:' + cid + ':privileges:' + privilege); userKeys.push('cid:' + cid + ':privileges:' + privilege);
groupKeys.push('cid:' + cid + ':privileges:groups:' + privilege); groupKeys.push('cid:' + cid + ':privileges:groups:' + privilege);
}); });
checkIfAllowed(uid, userKeys, groupKeys, callback); return await checkIfAllowed(uid, userKeys, groupKeys);
} }
function isUserAllowedToPrivileges(privileges, uid, cid, callback) { async function isUserAllowedToPrivileges(privileges, uid, cid) {
if (parseInt(uid, 10) <= 0) { if (parseInt(uid, 10) <= 0) {
return isSystemGroupAllowedToPrivileges(privileges, uid, cid, callback); return await isSystemGroupAllowedToPrivileges(privileges, uid, cid);
} }
var userKeys = []; const userKeys = [];
var groupKeys = []; const groupKeys = [];
privileges.forEach(function (privilege) { privileges.forEach(function (privilege) {
userKeys.push('cid:' + cid + ':privileges:' + privilege); userKeys.push('cid:' + cid + ':privileges:' + privilege);
groupKeys.push('cid:' + cid + ':privileges:groups:' + privilege); groupKeys.push('cid:' + cid + ':privileges:groups:' + privilege);
}); });
checkIfAllowed(uid, userKeys, groupKeys, callback); return await checkIfAllowed(uid, userKeys, groupKeys);
} }
function checkIfAllowed(uid, userKeys, groupKeys, callback) { async function checkIfAllowed(uid, userKeys, groupKeys) {
async.waterfall([ const [hasUserPrivilege, hasGroupPrivilege] = await Promise.all([
function (next) { groups.isMemberOfGroups(uid, userKeys),
async.parallel({ groups.isMemberOfGroupsList(uid, groupKeys),
hasUserPrivilege: function (next) { ]);
groups.isMemberOfGroups(uid, userKeys, next); return userKeys.map((key, index) => hasUserPrivilege[index] || hasGroupPrivilege[index]);
},
hasGroupPrivilege: function (next) {
groups.isMemberOfGroupsList(uid, groupKeys, next);
},
}, next);
},
function (results, next) {
var result = userKeys.map(function (key, index) {
return results.hasUserPrivilege[index] || results.hasGroupPrivilege[index];
});
next(null, result);
},
], callback);
} }
helpers.isUsersAllowedTo = function (privilege, uids, cid, callback) { helpers.isUsersAllowedTo = async function (privilege, uids, cid) {
async.waterfall([ const [hasUserPrivilege, hasGroupPrivilege] = await Promise.all([
function (next) { groups.isMembers(uids, 'cid:' + cid + ':privileges:' + privilege),
async.parallel({ groups.isMembersOfGroupList(uids, 'cid:' + cid + ':privileges:groups:' + privilege),
hasUserPrivilege: function (next) { ]);
groups.isMembers(uids, 'cid:' + cid + ':privileges:' + privilege, next); return uids.map((uid, index) => hasUserPrivilege[index] || hasGroupPrivilege[index]);
},
hasGroupPrivilege: function (next) {
groups.isMembersOfGroupList(uids, 'cid:' + cid + ':privileges:groups:' + privilege, next);
},
}, next);
},
function (results, next) {
var result = uids.map(function (uid, index) {
return results.hasUserPrivilege[index] || results.hasGroupPrivilege[index];
});
next(null, result);
},
], callback);
}; };
function isSystemGroupAllowedToCids(privilege, uid, cids, callback) { async function isSystemGroupAllowedToCids(privilege, uid, cids) {
const groupKeys = cids.map(cid => 'cid:' + cid + ':privileges:groups:' + privilege); const groupKeys = cids.map(cid => 'cid:' + cid + ':privileges:groups:' + privilege);
groups.isMemberOfGroups(uidToSystemGroup[uid], groupKeys, callback); return await groups.isMemberOfGroups(uidToSystemGroup[uid], groupKeys);
} }
function isSystemGroupAllowedToPrivileges(privileges, uid, cid, callback) { async function isSystemGroupAllowedToPrivileges(privileges, uid, cid) {
const groupKeys = privileges.map(privilege => 'cid:' + cid + ':privileges:groups:' + privilege); const groupKeys = privileges.map(privilege => 'cid:' + cid + ':privileges:groups:' + privilege);
groups.isMemberOfGroups(uidToSystemGroup[uid], groupKeys, callback); return await groups.isMemberOfGroups(uidToSystemGroup[uid], groupKeys);
} }
helpers.getUserPrivileges = function (cid, hookName, userPrivilegeList, callback) { helpers.getUserPrivileges = async function (cid, hookName, userPrivilegeList) {
var userPrivileges; const userPrivileges = await plugins.fireHook(hookName, userPrivilegeList.slice());
var memberSets; let memberSets = await groups.getMembersOfGroups(userPrivileges.map(privilege => 'cid:' + cid + ':privileges:' + privilege));
async.waterfall([ memberSets = memberSets.map(function (set) {
async.apply(plugins.fireHook, hookName, userPrivilegeList.slice()),
function (_privs, next) {
userPrivileges = _privs;
groups.getMembersOfGroups(userPrivileges.map(privilege => 'cid:' + cid + ':privileges:' + privilege), next);
},
function (_memberSets, next) {
memberSets = _memberSets.map(function (set) {
return set.map(uid => parseInt(uid, 10)); return set.map(uid => parseInt(uid, 10));
}); });
var members = _.uniq(_.flatten(memberSets)); const members = _.uniq(_.flatten(memberSets));
const memberData = await user.getUsersFields(members, ['picture', 'username']);
user.getUsersFields(members, ['picture', 'username'], next);
},
function (memberData, next) {
memberData.forEach(function (member) { memberData.forEach(function (member) {
member.privileges = {}; member.privileges = {};
for (var x = 0, numPrivs = userPrivileges.length; x < numPrivs; x += 1) { for (var x = 0, numPrivs = userPrivileges.length; x < numPrivs; x += 1) {
@ -141,45 +96,31 @@ helpers.getUserPrivileges = function (cid, hookName, userPrivilegeList, callback
} }
}); });
next(null, memberData); return memberData;
},
], callback);
}; };
helpers.getGroupPrivileges = function (cid, hookName, groupPrivilegeList, callback) { helpers.getGroupPrivileges = async function (cid, hookName, groupPrivilegeList) {
var groupPrivileges; const groupPrivileges = await plugins.fireHook(hookName, groupPrivilegeList.slice());
async.waterfall([ const [memberSets, allGroupNames] = await Promise.all([
async.apply(plugins.fireHook, hookName, groupPrivilegeList.slice()), groups.getMembersOfGroups(groupPrivileges.map(privilege => 'cid:' + cid + ':privileges:' + privilege)),
function (_privs, next) { groups.getGroups('groups:createtime', 0, -1),
groupPrivileges = _privs; ]);
async.parallel({
memberSets: function (next) { const uniqueGroups = _.uniq(_.flatten(memberSets));
groups.getMembersOfGroups(groupPrivileges.map(privilege => 'cid:' + cid + ':privileges:' + privilege), next);
}, let groupNames = allGroupNames.filter(groupName => !groupName.includes(':privileges:') && uniqueGroups.includes(groupName));
groupNames: function (next) {
groups.getGroups('groups:createtime', 0, -1, next);
},
}, next);
},
function (results, next) {
var memberSets = results.memberSets;
var uniqueGroups = _.uniq(_.flatten(memberSets));
var groupNames = results.groupNames.filter(groupName => !groupName.includes(':privileges:') && uniqueGroups.includes(groupName));
groupNames = groups.ephemeralGroups.concat(groupNames); groupNames = groups.ephemeralGroups.concat(groupNames);
moveToFront(groupNames, 'Global Moderators'); moveToFront(groupNames, 'Global Moderators');
moveToFront(groupNames, 'registered-users'); moveToFront(groupNames, 'registered-users');
var adminIndex = groupNames.indexOf('administrators'); const adminIndex = groupNames.indexOf('administrators');
if (adminIndex !== -1) { if (adminIndex !== -1) {
groupNames.splice(adminIndex, 1); groupNames.splice(adminIndex, 1);
} }
const groupData = await groups.getGroupsFields(groupNames, ['private']);
var memberPrivs; const memberData = groupNames.map(function (member, index) {
const memberPrivs = {};
var memberData = groupNames.map(function (member) {
memberPrivs = {};
for (var x = 0, numPrivs = groupPrivileges.length; x < numPrivs; x += 1) { for (var x = 0, numPrivs = groupPrivileges.length; x < numPrivs; x += 1) {
memberPrivs[groupPrivileges[x]] = memberSets[x].includes(member); memberPrivs[groupPrivileges[x]] = memberSets[x].includes(member);
@ -187,26 +128,10 @@ helpers.getGroupPrivileges = function (cid, hookName, groupPrivilegeList, callba
return { return {
name: member, name: member,
privileges: memberPrivs, privileges: memberPrivs,
isPrivate: groupData[index] && !!groupData[index].private,
}; };
}); });
return memberData;
next(null, memberData);
},
function (memberData, next) {
// Grab privacy info for the groups as well
async.map(memberData, function (member, next) {
async.waterfall([
function (next) {
groups.isPrivate(member.name, next);
},
function (isPrivate, next) {
member.isPrivate = isPrivate;
next(null, member);
},
], next);
}, next);
},
], callback);
}; };
function moveToFront(groupNames, groupToMove) { function moveToFront(groupNames, groupToMove) {
@ -218,16 +143,19 @@ function moveToFront(groupNames, groupToMove) {
} }
} }
helpers.giveOrRescind = function (method, privileges, cids, groupNames, callback) { helpers.giveOrRescind = async function (method, privileges, cids, groupNames) {
groupNames = Array.isArray(groupNames) ? groupNames : [groupNames]; groupNames = Array.isArray(groupNames) ? groupNames : [groupNames];
cids = Array.isArray(cids) ? cids : [cids]; cids = Array.isArray(cids) ? cids : [cids];
async.eachSeries(groupNames, function (groupName, next) { for (const groupName of groupNames) {
var groupKeys = []; const groupKeys = [];
cids.forEach((cid) => { cids.forEach((cid) => {
privileges.forEach((privilege) => { privileges.forEach((privilege) => {
groupKeys.push('cid:' + cid + ':privileges:groups:' + privilege); groupKeys.push('cid:' + cid + ':privileges:groups:' + privilege);
}); });
}); });
method(groupKeys, groupName, next); /* eslint-disable no-await-in-loop */
}, callback); await method(groupKeys, groupName);
}
}; };
require('../promisify')(helpers);

@ -38,9 +38,7 @@ privileges.userPrivilegeList = [
'moderate', 'moderate',
]; ];
privileges.groupPrivilegeList = privileges.userPrivilegeList.map(function (privilege) { privileges.groupPrivilegeList = privileges.userPrivilegeList.map(privilege => 'groups:' + privilege);
return 'groups:' + privilege;
});
privileges.privilegeList = privileges.userPrivilegeList.concat(privileges.groupPrivilegeList); privileges.privilegeList = privileges.userPrivilegeList.concat(privileges.groupPrivilegeList);

@ -1,44 +1,37 @@
'use strict'; 'use strict';
var async = require('async'); const _ = require('lodash');
var _ = require('lodash');
var meta = require('../meta'); const meta = require('../meta');
var posts = require('../posts'); const posts = require('../posts');
var topics = require('../topics'); const topics = require('../topics');
var user = require('../user'); const user = require('../user');
var helpers = require('./helpers'); const helpers = require('./helpers');
var plugins = require('../plugins'); const plugins = require('../plugins');
const utils = require('../utils');
module.exports = function (privileges) { module.exports = function (privileges) {
privileges.posts = {}; privileges.posts = {};
privileges.posts.get = function (pids, uid, callback) { privileges.posts.get = async function (pids, uid) {
if (!Array.isArray(pids) || !pids.length) { if (!Array.isArray(pids) || !pids.length) {
return setImmediate(callback, null, []); return [];
} }
let uniqueCids; const cids = await posts.getCidsByPids(pids);
let cids; const uniqueCids = _.uniq(cids);
async.waterfall([
function (next) { const results = await utils.promiseParallel({
posts.getCidsByPids(pids, next); isAdmin: user.isAdministrator(uid),
}, isModerator: user.isModerator(uid, uniqueCids),
function (_cids, next) { isOwner: posts.isOwner(pids, uid),
cids = _cids; 'topics:read': helpers.isUserAllowedTo('topics:read', uid, uniqueCids),
uniqueCids = _.uniq(cids); read: helpers.isUserAllowedTo('read', uid, uniqueCids),
async.parallel({ 'posts:edit': helpers.isUserAllowedTo('posts:edit', uid, uniqueCids),
isAdmin: async.apply(user.isAdministrator, uid), 'posts:history': helpers.isUserAllowedTo('posts:history', uid, uniqueCids),
isModerator: async.apply(user.isModerator, uid, uniqueCids), 'posts:view_deleted': helpers.isUserAllowedTo('posts:view_deleted', uid, uniqueCids),
isOwner: async.apply(posts.isOwner, pids, uid), });
'topics:read': async.apply(helpers.isUserAllowedTo, 'topics:read', uid, uniqueCids),
read: async.apply(helpers.isUserAllowedTo, 'read', uid, uniqueCids),
'posts:edit': async.apply(helpers.isUserAllowedTo, 'posts:edit', uid, uniqueCids),
'posts:history': async.apply(helpers.isUserAllowedTo, 'posts:history', uid, uniqueCids),
'posts:view_deleted': async.apply(helpers.isUserAllowedTo, 'posts:view_deleted', uid, uniqueCids),
}, next);
},
function (results, next) {
const isModerator = _.zipObject(uniqueCids, results.isModerator); const isModerator = _.zipObject(uniqueCids, results.isModerator);
const privData = {}; const privData = {};
privData['topics:read'] = _.zipObject(uniqueCids, results['topics:read']); privData['topics:read'] = _.zipObject(uniqueCids, results['topics:read']);
@ -47,11 +40,11 @@ module.exports = function (privileges) {
privData['posts:history'] = _.zipObject(uniqueCids, results['posts:history']); privData['posts:history'] = _.zipObject(uniqueCids, results['posts:history']);
privData['posts:view_deleted'] = _.zipObject(uniqueCids, results['posts:view_deleted']); privData['posts:view_deleted'] = _.zipObject(uniqueCids, results['posts:view_deleted']);
var privileges = cids.map(function (cid, i) { const privileges = cids.map(function (cid, i) {
var isAdminOrMod = results.isAdmin || isModerator[cid]; const isAdminOrMod = results.isAdmin || isModerator[cid];
var editable = (privData['posts:edit'][cid] && (results.isOwner[i] || results.isModerator)) || results.isAdmin; const editable = (privData['posts:edit'][cid] && (results.isOwner[i] || results.isModerator)) || results.isAdmin;
var viewDeletedPosts = results.isOwner[i] || privData['posts:view_deleted'][cid] || results.isAdmin; const viewDeletedPosts = results.isOwner[i] || privData['posts:view_deleted'][cid] || results.isAdmin;
var viewHistory = results.isOwner[i] || privData['posts:history'][cid] || results.isAdmin; const viewHistory = results.isOwner[i] || privData['posts:history'][cid] || results.isAdmin;
return { return {
editable: editable, editable: editable,
@ -64,52 +57,27 @@ module.exports = function (privileges) {
}; };
}); });
next(null, privileges); return privileges;
},
], callback);
}; };
privileges.posts.can = function (privilege, pid, uid, callback) { privileges.posts.can = async function (privilege, pid, uid) {
async.waterfall([ const cid = await posts.getCidByPid(pid);
function (next) { return await privileges.categories.can(privilege, cid, uid);
posts.getCidByPid(pid, next);
},
function (cid, next) {
privileges.categories.can(privilege, cid, uid, next);
},
], callback);
}; };
privileges.posts.filter = function (privilege, pids, uid, callback) { privileges.posts.filter = async function (privilege, pids, uid) {
if (!Array.isArray(pids) || !pids.length) { if (!Array.isArray(pids) || !pids.length) {
return setImmediate(callback, null, []); return [];
} }
var cids;
var postData;
var tids;
var tidToTopic = {};
pids = _.uniq(pids); pids = _.uniq(pids);
const postData = await posts.getPostsFields(pids, ['uid', 'tid', 'deleted']);
const tids = _.uniq(postData.map(post => post && post.tid).filter(Boolean));
const topicData = await topics.getTopicsFields(tids, ['deleted', 'cid']);
async.waterfall([ const tidToTopic = _.zipObject(tids, topicData);
function (next) {
posts.getPostsFields(pids, ['uid', 'tid', 'deleted'], next);
},
function (_posts, next) {
postData = _posts;
tids = _.uniq(_posts.map(post => post && post.tid).filter(Boolean));
topics.getTopicsFields(tids, ['deleted', 'cid'], next);
},
function (topicData, next) {
topicData.forEach(function (topic, index) {
if (topic) {
tidToTopic[tids[index]] = topic;
}
});
cids = postData.map(function (post, index) { let cids = postData.map(function (post, index) {
if (post) { if (post) {
post.pid = pids[index]; post.pid = pids[index];
post.topic = tidToTopic[post.tid]; post.topic = tidToTopic[post.tid];
@ -119,9 +87,7 @@ module.exports = function (privileges) {
cids = _.uniq(cids); cids = _.uniq(cids);
privileges.categories.getBase(privilege, cids, uid, next); const results = await privileges.categories.getBase(privilege, cids, uid);
},
function (results, next) {
cids = cids.filter(function (cid, index) { cids = cids.filter(function (cid, index) {
return !results.categories[index].disabled && return !results.categories[index].disabled &&
(results.allowedTo[index] || results.isAdmin); (results.allowedTo[index] || results.isAdmin);
@ -134,167 +100,114 @@ module.exports = function (privileges) {
((!post.topic.deleted && !post.deleted) || results.isAdmin); ((!post.topic.deleted && !post.deleted) || results.isAdmin);
}).map(post => post.pid); }).map(post => post.pid);
plugins.fireHook('filter:privileges.posts.filter', { const data = await plugins.fireHook('filter:privileges.posts.filter', {
privilege: privilege, privilege: privilege,
uid: uid, uid: uid,
pids: pids, pids: pids,
}, function (err, data) {
next(err, data ? data.pids : null);
}); });
},
], callback); return data ? data.pids : null;
}; };
privileges.posts.canEdit = function (pid, uid, callback) { privileges.posts.canEdit = async function (pid, uid) {
let results; const results = await utils.promiseParallel({
async.waterfall([ isAdmin: privileges.users.isAdministrator(uid),
function (next) { isMod: posts.isModerator([pid], uid),
async.parallel({ owner: posts.isOwner(pid, uid),
isAdmin: async.apply(privileges.users.isAdministrator, uid), edit: privileges.posts.can('posts:edit', pid, uid),
isMod: async.apply(posts.isModerator, [pid], uid), postData: posts.getPostFields(pid, ['tid', 'timestamp', 'deleted', 'deleterUid']),
owner: async.apply(posts.isOwner, pid, uid), userData: user.getUserFields(uid, ['reputation']),
edit: async.apply(privileges.posts.can, 'posts:edit', pid, uid), });
postData: async.apply(posts.getPostFields, pid, ['tid', 'timestamp', 'deleted', 'deleterUid']),
userData: async.apply(user.getUserFields, uid, ['reputation']),
}, next);
},
function (_results, next) {
results = _results;
results.isMod = results.isMod[0]; results.isMod = results.isMod[0];
if (results.isAdmin) { if (results.isAdmin) {
return callback(null, { flag: true }); return { flag: true };
} }
if (!results.isMod && meta.config.postEditDuration && (Date.now() - results.postData.timestamp > meta.config.postEditDuration * 1000)) { if (!results.isMod && meta.config.postEditDuration && (Date.now() - results.postData.timestamp > meta.config.postEditDuration * 1000)) {
return callback(null, { flag: false, message: '[[error:post-edit-duration-expired, ' + meta.config.postEditDuration + ']]' }); return { flag: false, message: '[[error:post-edit-duration-expired, ' + meta.config.postEditDuration + ']]' };
} }
if (!results.isMod && meta.config.newbiePostEditDuration > 0 && meta.config.newbiePostDelayThreshold > _results.userData.reputation && Date.now() - _results.postData.timestamp > meta.config.newbiePostEditDuration * 1000) { if (!results.isMod && meta.config.newbiePostEditDuration > 0 && meta.config.newbiePostDelayThreshold > results.userData.reputation && Date.now() - results.postData.timestamp > meta.config.newbiePostEditDuration * 1000) {
return callback(null, { flag: false, message: '[[error:post-edit-duration-expired, ' + meta.config.newbiePostEditDuration + ']]' }); return { flag: false, message: '[[error:post-edit-duration-expired, ' + meta.config.newbiePostEditDuration + ']]' };
} }
topics.isLocked(results.postData.tid, next); const isLocked = await topics.isLocked(results.postData.tid);
},
function (isLocked, next) {
if (!results.isMod && isLocked) { if (!results.isMod && isLocked) {
return callback(null, { flag: false, message: '[[error:topic-locked]]' }); return { flag: false, message: '[[error:topic-locked]]' };
} }
if (!results.isMod && results.postData.deleted && parseInt(uid, 10) !== parseInt(results.postData.deleterUid, 10)) { if (!results.isMod && results.postData.deleted && parseInt(uid, 10) !== parseInt(results.postData.deleterUid, 10)) {
return callback(null, { flag: false, message: '[[error:post-deleted]]' }); return { flag: false, message: '[[error:post-deleted]]' };
} }
results.pid = parseInt(pid, 10); results.pid = parseInt(pid, 10);
results.uid = uid; results.uid = uid;
plugins.fireHook('filter:privileges.posts.edit', results, next); const result = await plugins.fireHook('filter:privileges.posts.edit', results);
}, return { flag: result.edit && (result.owner || result.isMod), message: '[[error:no-privileges]]' };
function (result, next) {
next(null, { flag: result.edit && (result.owner || result.isMod), message: '[[error:no-privileges]]' });
},
], callback);
}; };
privileges.posts.canDelete = function (pid, uid, callback) { privileges.posts.canDelete = async function (pid, uid) {
var postData; const postData = await posts.getPostFields(pid, ['uid', 'tid', 'timestamp', 'deleterUid']);
async.waterfall([ const results = await utils.promiseParallel({
function (next) { isAdmin: privileges.users.isAdministrator(uid),
posts.getPostFields(pid, ['uid', 'tid', 'timestamp', 'deleterUid'], next); isMod: posts.isModerator([pid], uid),
}, isLocked: topics.isLocked(postData.tid),
function (_postData, next) { isOwner: posts.isOwner(pid, uid),
postData = _postData; 'posts:delete': privileges.posts.can('posts:delete', pid, uid),
async.parallel({ });
isAdmin: async.apply(privileges.users.isAdministrator, uid),
isMod: async.apply(posts.isModerator, [pid], uid),
isLocked: async.apply(topics.isLocked, postData.tid),
isOwner: async.apply(posts.isOwner, pid, uid),
'posts:delete': async.apply(privileges.posts.can, 'posts:delete', pid, uid),
}, next);
},
function (results, next) {
results.isMod = results.isMod[0]; results.isMod = results.isMod[0];
if (results.isAdmin) { if (results.isAdmin) {
return next(null, { flag: true }); return { flag: true };
} }
if (!results.isMod && results.isLocked) { if (!results.isMod && results.isLocked) {
return next(null, { flag: false, message: '[[error:topic-locked]]' }); return { flag: false, message: '[[error:topic-locked]]' };
} }
var postDeleteDuration = meta.config.postDeleteDuration; var postDeleteDuration = meta.config.postDeleteDuration;
if (!results.isMod && postDeleteDuration && (Date.now() - postData.timestamp > postDeleteDuration * 1000)) { if (!results.isMod && postDeleteDuration && (Date.now() - postData.timestamp > postDeleteDuration * 1000)) {
return next(null, { flag: false, message: '[[error:post-delete-duration-expired, ' + meta.config.postDeleteDuration + ']]' }); return { flag: false, message: '[[error:post-delete-duration-expired, ' + meta.config.postDeleteDuration + ']]' };
} }
var deleterUid = postData.deleterUid; var deleterUid = postData.deleterUid;
var flag = results['posts:delete'] && ((results.isOwner && (deleterUid === 0 || deleterUid === postData.uid)) || results.isMod); var flag = results['posts:delete'] && ((results.isOwner && (deleterUid === 0 || deleterUid === postData.uid)) || results.isMod);
next(null, { flag: flag, message: '[[error:no-privileges]]' }); return { flag: flag, message: '[[error:no-privileges]]' };
},
], callback);
}; };
privileges.posts.canFlag = function (pid, uid, callback) { privileges.posts.canFlag = async function (pid, uid) {
async.waterfall([ const [userReputation, isAdminOrModerator] = await Promise.all([
function (next) { user.getUserField(uid, 'reputation'),
async.parallel({ isAdminOrMod(pid, uid),
userReputation: async.apply(user.getUserField, uid, 'reputation'), ]);
isAdminOrMod: async.apply(isAdminOrMod, pid, uid), const minimumReputation = meta.config['min:rep:flag'];
}, next); const canFlag = isAdminOrModerator || (userReputation >= minimumReputation);
}, return { flag: canFlag };
function (results, next) {
var minimumReputation = meta.config['min:rep:flag'];
var canFlag = results.isAdminOrMod || (results.userReputation >= minimumReputation);
next(null, { flag: canFlag });
},
], callback);
}; };
privileges.posts.canMove = function (pid, uid, callback) { privileges.posts.canMove = async function (pid, uid) {
async.waterfall([ const isMain = await posts.isMain(pid);
function (next) {
posts.isMain(pid, next);
},
function (isMain, next) {
if (isMain) { if (isMain) {
return next(new Error('[[error:cant-move-mainpost]]')); throw new Error('[[error:cant-move-mainpost]]');
} }
isAdminOrMod(pid, uid, next); return await isAdminOrMod(pid, uid);
},
], callback);
}; };
privileges.posts.canPurge = function (pid, uid, callback) { privileges.posts.canPurge = async function (pid, uid) {
async.waterfall([ const cid = await posts.getCidByPid(pid);
function (next) { const results = await utils.promiseParallel({
posts.getCidByPid(pid, next); purge: privileges.categories.isUserAllowedTo('purge', cid, uid),
}, owner: posts.isOwner(pid, uid),
function (cid, next) { isAdmin: privileges.users.isAdministrator(uid),
async.parallel({ isModerator: privileges.users.isModerator(uid, cid),
purge: async.apply(privileges.categories.isUserAllowedTo, 'purge', cid, uid), });
owner: async.apply(posts.isOwner, pid, uid), return (results.purge && (results.owner || results.isModerator)) || results.isAdmin;
isAdmin: async.apply(privileges.users.isAdministrator, uid),
isModerator: async.apply(privileges.users.isModerator, uid, cid),
}, next);
},
function (results, next) {
next(null, (results.purge && (results.owner || results.isModerator)) || results.isAdmin);
},
], callback);
}; };
function isAdminOrMod(pid, uid, callback) { async function isAdminOrMod(pid, uid) {
helpers.some([ if (parseInt(uid, 10) <= 0) {
function (next) { return false;
async.waterfall([ }
function (next) { const cid = await posts.getCidByPid(pid);
posts.getCidByPid(pid, next); return await privileges.categories.isAdminOrMod(cid, uid);
},
function (cid, next) {
user.isModerator(uid, cid, next);
},
], next);
},
function (next) {
user.isAdministrator(uid, next);
},
], callback);
} }
}; };

@ -1,98 +1,76 @@
'use strict'; 'use strict';
var async = require('async'); const _ = require('lodash');
var _ = require('lodash');
var meta = require('../meta'); const meta = require('../meta');
var topics = require('../topics'); const topics = require('../topics');
var user = require('../user'); const user = require('../user');
var helpers = require('./helpers'); const helpers = require('./helpers');
var categories = require('../categories'); const categories = require('../categories');
var plugins = require('../plugins'); const plugins = require('../plugins');
module.exports = function (privileges) { module.exports = function (privileges) {
privileges.topics = {}; privileges.topics = {};
privileges.topics.get = function (tid, uid, callback) { privileges.topics.get = async function (tid, uid) {
uid = parseInt(uid, 10); uid = parseInt(uid, 10);
var topic;
var privs = [ const privs = [
'topics:reply', 'topics:read', 'topics:tag', 'topics:reply', 'topics:read', 'topics:tag',
'topics:delete', 'posts:edit', 'posts:history', 'topics:delete', 'posts:edit', 'posts:history',
'posts:delete', 'posts:view_deleted', 'read', 'purge', 'posts:delete', 'posts:view_deleted', 'read', 'purge',
]; ];
async.waterfall([ const topicData = await topics.getTopicFields(tid, ['cid', 'uid', 'locked', 'deleted']);
async.apply(topics.getTopicFields, tid, ['cid', 'uid', 'locked', 'deleted']), const [userPrivileges, isAdministrator, isModerator, disabled] = await Promise.all([
function (_topic, next) { helpers.isUserAllowedTo(privs, uid, topicData.cid),
topic = _topic; user.isAdministrator(uid),
async.parallel({ user.isModerator(uid, topicData.cid),
privileges: async.apply(helpers.isUserAllowedTo, privs, uid, topic.cid), categories.getCategoryField(topicData.cid, 'disabled'),
isAdministrator: async.apply(user.isAdministrator, uid), ]);
isModerator: async.apply(user.isModerator, uid, topic.cid), const privData = _.zipObject(privs, userPrivileges);
disabled: async.apply(categories.getCategoryField, topic.cid, 'disabled'), const isOwner = uid > 0 && uid === topicData.uid;
}, next); const isAdminOrMod = isAdministrator || isModerator;
}, const editable = isAdminOrMod;
function (results, next) { const deletable = (privData['topics:delete'] && (isOwner || isModerator)) || isAdministrator;
var privData = _.zipObject(privs, results.privileges);
var isOwner = uid > 0 && uid === topic.uid; return await plugins.fireHook('filter:privileges.topics.get', {
var isAdminOrMod = results.isAdministrator || results.isModerator; 'topics:reply': (privData['topics:reply'] && ((!topicData.locked && !topicData.deleted) || isModerator)) || isAdministrator,
var editable = isAdminOrMod; 'topics:read': privData['topics:read'] || isAdministrator,
var deletable = (privData['topics:delete'] && (isOwner || results.isModerator)) || results.isAdministrator; 'topics:tag': privData['topics:tag'] || isAdministrator,
'topics:delete': (privData['topics:delete'] && (isOwner || isModerator)) || isAdministrator,
plugins.fireHook('filter:privileges.topics.get', { 'posts:edit': (privData['posts:edit'] && (!topicData.locked || isModerator)) || isAdministrator,
'topics:reply': (privData['topics:reply'] && ((!topic.locked && !topic.deleted) || results.isModerator)) || results.isAdministrator, 'posts:history': privData['posts:history'] || isAdministrator,
'topics:read': privData['topics:read'] || results.isAdministrator, 'posts:delete': (privData['posts:delete'] && (!topicData.locked || isModerator)) || isAdministrator,
'topics:tag': privData['topics:tag'] || results.isAdministrator, 'posts:view_deleted': privData['posts:view_deleted'] || isAdministrator,
'topics:delete': (privData['topics:delete'] && (isOwner || results.isModerator)) || results.isAdministrator, read: privData.read || isAdministrator,
'posts:edit': (privData['posts:edit'] && (!topic.locked || results.isModerator)) || results.isAdministrator, purge: (privData.purge && (isOwner || isModerator)) || isAdministrator,
'posts:history': privData['posts:history'] || results.isAdministrator,
'posts:delete': (privData['posts:delete'] && (!topic.locked || results.isModerator)) || results.isAdministrator,
'posts:view_deleted': privData['posts:view_deleted'] || results.isAdministrator,
read: privData.read || results.isAdministrator,
purge: (privData.purge && (isOwner || results.isModerator)) || results.isAdministrator,
view_thread_tools: editable || deletable, view_thread_tools: editable || deletable,
editable: editable, editable: editable,
deletable: deletable, deletable: deletable,
view_deleted: isAdminOrMod || isOwner, view_deleted: isAdminOrMod || isOwner,
isAdminOrMod: isAdminOrMod, isAdminOrMod: isAdminOrMod,
disabled: results.disabled, disabled: disabled,
tid: tid, tid: tid,
uid: uid, uid: uid,
}, next); });
},
], callback);
}; };
privileges.topics.can = function (privilege, tid, uid, callback) { privileges.topics.can = async function (privilege, tid, uid) {
async.waterfall([ const cid = await topics.getTopicField(tid, 'cid');
function (next) { return await privileges.categories.can(privilege, cid, uid);
topics.getTopicField(tid, 'cid', next);
},
function (cid, next) {
privileges.categories.can(privilege, cid, uid, next);
},
], callback);
}; };
privileges.topics.filterTids = function (privilege, tids, uid, callback) { privileges.topics.filterTids = async function (privilege, tids, uid) {
if (!Array.isArray(tids) || !tids.length) { if (!Array.isArray(tids) || !tids.length) {
return callback(null, []); return [];
} }
var cids;
var topicsData; const topicsData = await topics.getTopicsFields(tids, ['tid', 'cid', 'deleted']);
async.waterfall([ let cids = _.uniq(topicsData.map(topic => topic.cid));
function (next) { const results = await privileges.categories.getBase(privilege, cids, uid);
topics.getTopicsFields(tids, ['tid', 'cid', 'deleted'], next);
},
function (_topicsData, next) {
topicsData = _topicsData;
cids = _.uniq(topicsData.map(topic => topic.cid));
privileges.categories.getBase(privilege, cids, uid, next);
},
function (results, next) {
cids = cids.filter(function (cid, index) { cids = cids.filter(function (cid, index) {
return !results.categories[index].disabled && return !results.categories[index].disabled &&
(results.allowedTo[index] || results.isAdmin); (results.allowedTo[index] || results.isAdmin);
@ -100,140 +78,86 @@ module.exports = function (privileges) {
const cidsSet = new Set(cids); const cidsSet = new Set(cids);
tids = topicsData.filter(function (topic) { tids = topicsData.filter(t => cidsSet.has(t.cid) && (!t.deleted || results.isAdmin)).map(t => t.tid);
return cidsSet.has(topic.cid) &&
(!topic.deleted || results.isAdmin);
}).map(topic => topic.tid);
plugins.fireHook('filter:privileges.topics.filter', { const data = await plugins.fireHook('filter:privileges.topics.filter', {
privilege: privilege, privilege: privilege,
uid: uid, uid: uid,
tids: tids, tids: tids,
}, function (err, data) {
next(err, data ? data.tids : null);
}); });
}, return data ? data.tids : [];
], callback);
}; };
privileges.topics.filterUids = function (privilege, tid, uids, callback) { privileges.topics.filterUids = async function (privilege, tid, uids) {
if (!Array.isArray(uids) || !uids.length) { if (!Array.isArray(uids) || !uids.length) {
return setImmediate(callback, null, []); return [];
} }
uids = _.uniq(uids); uids = _.uniq(uids);
var topicData; const topicData = await topics.getTopicFields(tid, ['tid', 'cid', 'deleted']);
async.waterfall([ const [disabled, allowedTo, isAdmins] = await Promise.all([
function (next) { categories.getCategoryField(topicData.cid, 'disabled'),
topics.getTopicFields(tid, ['tid', 'cid', 'deleted'], next); helpers.isUsersAllowedTo(privilege, uids, topicData.cid),
}, user.isAdministrator(uids),
function (_topicData, next) { ]);
topicData = _topicData; return uids.filter(function (uid, index) {
async.parallel({ return !disabled &&
disabled: function (next) { ((allowedTo[index] && !topicData.deleted) || isAdmins[index]);
categories.getCategoryField(topicData.cid, 'disabled', next);
},
allowedTo: function (next) {
helpers.isUsersAllowedTo(privilege, uids, topicData.cid, next);
},
isAdmins: function (next) {
user.isAdministrator(uids, next);
},
}, next);
},
function (results, next) {
uids = uids.filter(function (uid, index) {
return !results.disabled &&
((results.allowedTo[index] && !topicData.deleted) || results.isAdmins[index]);
}); });
next(null, uids);
},
], callback);
}; };
privileges.topics.canPurge = function (tid, uid, callback) { privileges.topics.canPurge = async function (tid, uid) {
async.waterfall([ const cid = await topics.getTopicField(tid, 'cid');
function (next) { const [purge, owner, isAdmin, isModerator] = await Promise.all([
topics.getTopicField(tid, 'cid', next); privileges.categories.isUserAllowedTo('purge', cid, uid),
}, topics.isOwner(tid, uid),
function (cid, next) { privileges.users.isAdministrator(uid),
async.parallel({ privileges.users.isModerator(uid, cid),
purge: async.apply(privileges.categories.isUserAllowedTo, 'purge', cid, uid), ]);
owner: async.apply(topics.isOwner, tid, uid), return (purge && (owner || isModerator)) || isAdmin;
isAdmin: async.apply(privileges.users.isAdministrator, uid),
isModerator: async.apply(privileges.users.isModerator, uid, cid),
}, next);
},
function (results, next) {
next(null, (results.purge && (results.owner || results.isModerator)) || results.isAdmin);
},
], callback);
}; };
privileges.topics.canDelete = function (tid, uid, callback) { privileges.topics.canDelete = async function (tid, uid) {
var topicData; const topicData = await topics.getTopicFields(tid, ['cid', 'postcount']);
async.waterfall([ const [isModerator, isAdministrator, isOwner, allowedTo] = await Promise.all([
function (next) { user.isModerator(uid, topicData.cid),
topics.getTopicFields(tid, ['cid', 'postcount'], next); user.isAdministrator(uid),
}, topics.isOwner(tid, uid),
function (_topicData, next) { helpers.isUserAllowedTo('topics:delete', uid, [topicData.cid]),
topicData = _topicData; ]);
async.parallel({
isModerator: async.apply(user.isModerator, uid, topicData.cid), if (isAdministrator) {
isAdministrator: async.apply(user.isAdministrator, uid), return true;
isOwner: async.apply(topics.isOwner, tid, uid),
'topics:delete': async.apply(helpers.isUserAllowedTo, 'topics:delete', uid, [topicData.cid]),
}, next);
},
function (results, next) {
if (results.isAdministrator) {
return next(null, true);
} }
var preventTopicDeleteAfterReplies = meta.config.preventTopicDeleteAfterReplies; const preventTopicDeleteAfterReplies = meta.config.preventTopicDeleteAfterReplies;
if (!results.isModerator && preventTopicDeleteAfterReplies && (topicData.postcount - 1) >= preventTopicDeleteAfterReplies) { if (!isModerator && preventTopicDeleteAfterReplies && (topicData.postcount - 1) >= preventTopicDeleteAfterReplies) {
var langKey = preventTopicDeleteAfterReplies > 1 ? const langKey = preventTopicDeleteAfterReplies > 1 ?
'[[error:cant-delete-topic-has-replies, ' + meta.config.preventTopicDeleteAfterReplies + ']]' : '[[error:cant-delete-topic-has-replies, ' + meta.config.preventTopicDeleteAfterReplies + ']]' :
'[[error:cant-delete-topic-has-reply]]'; '[[error:cant-delete-topic-has-reply]]';
return next(new Error(langKey)); throw new Error(langKey);
} }
next(null, results['topics:delete'][0] && (results.isOwner || results.isModerator)); return allowedTo[0] && (isOwner || isModerator);
},
], callback);
}; };
privileges.topics.canEdit = function (tid, uid, callback) { privileges.topics.canEdit = async function (tid, uid) {
privileges.topics.isOwnerOrAdminOrMod(tid, uid, callback); return await privileges.topics.isOwnerOrAdminOrMod(tid, uid);
}; };
privileges.topics.isOwnerOrAdminOrMod = function (tid, uid, callback) { privileges.topics.isOwnerOrAdminOrMod = async function (tid, uid) {
helpers.some([ const [isOwner, isAdminOrMod] = await Promise.all([
function (next) { topics.isOwner(tid, uid),
topics.isOwner(tid, uid, next); privileges.topics.isAdminOrMod(tid, uid),
}, ]);
function (next) { return isOwner || isAdminOrMod;
privileges.topics.isAdminOrMod(tid, uid, next);
},
], callback);
}; };
privileges.topics.isAdminOrMod = function (tid, uid, callback) { privileges.topics.isAdminOrMod = async function (tid, uid) {
helpers.some([ if (parseInt(uid, 10) <= 0) {
function (next) { return false;
async.waterfall([ }
function (next) { const cid = await topics.getTopicField(tid, 'cid');
topics.getTopicField(tid, 'cid', next); return await privileges.categories.isAdminOrMod(cid, uid);
},
function (cid, next) {
user.isModerator(uid, cid, next);
},
], next);
},
function (next) {
user.isAdministrator(uid, next);
},
], callback);
}; };
}; };

@ -1,189 +1,118 @@
'use strict'; 'use strict';
var async = require('async'); const _ = require('lodash');
var _ = require('lodash');
var groups = require('../groups'); const groups = require('../groups');
var plugins = require('../plugins'); const plugins = require('../plugins');
var helpers = require('./helpers'); const helpers = require('./helpers');
module.exports = function (privileges) { module.exports = function (privileges) {
privileges.users = {}; privileges.users = {};
privileges.users.isAdministrator = function (uid, callback) { privileges.users.isAdministrator = async function (uid) {
if (Array.isArray(uid)) { return await isGroupMember(uid, 'administrators');
groups.isMembers(uid, 'administrators', callback);
} else {
groups.isMember(uid, 'administrators', callback);
}
}; };
privileges.users.isGlobalModerator = function (uid, callback) { privileges.users.isGlobalModerator = async function (uid) {
if (Array.isArray(uid)) { return await isGroupMember(uid, 'Global Moderators');
groups.isMembers(uid, 'Global Moderators', callback);
} else {
groups.isMember(uid, 'Global Moderators', callback);
}
}; };
privileges.users.isModerator = function (uid, cid, callback) { async function isGroupMember(uid, groupName) {
return await groups[Array.isArray(uid) ? 'isMembers' : 'isMember'](uid, groupName);
}
privileges.users.isModerator = async function (uid, cid) {
if (Array.isArray(cid)) { if (Array.isArray(cid)) {
isModeratorOfCategories(cid, uid, callback); return await isModeratorOfCategories(cid, uid);
} else if (Array.isArray(uid)) { } else if (Array.isArray(uid)) {
isModeratorsOfCategory(cid, uid, callback); return await isModeratorsOfCategory(cid, uid);
} else {
isModeratorOfCategory(cid, uid, callback);
} }
return await isModeratorOfCategory(cid, uid);
}; };
function isModeratorOfCategories(cids, uid, callback) { async function isModeratorOfCategories(cids, uid) {
if (parseInt(uid, 10) <= 0) { if (parseInt(uid, 10) <= 0) {
return filterIsModerator(cids, uid, cids.map(() => false), callback); return await filterIsModerator(cids, uid, cids.map(() => false));
} }
var uniqueCids;
async.waterfall([ const isGlobalModerator = await privileges.users.isGlobalModerator(uid);
function (next) {
privileges.users.isGlobalModerator(uid, next);
},
function (isGlobalModerator, next) {
if (isGlobalModerator) { if (isGlobalModerator) {
return filterIsModerator(cids, uid, cids.map(() => true), callback); return await filterIsModerator(cids, uid, cids.map(() => true));
} }
const uniqueCids = _.uniq(cids);
const isAllowed = await helpers.isUserAllowedTo('moderate', uid, uniqueCids);
uniqueCids = _.uniq(cids); const cidToIsAllowed = _.zipObject(uniqueCids, isAllowed);
const isModerator = cids.map(cid => cidToIsAllowed[cid]);
helpers.isUserAllowedTo('moderate', uid, uniqueCids, next); return await filterIsModerator(cids, uid, isModerator);
},
function (isAllowed, next) {
const map = _.zipObject(uniqueCids, isAllowed);
const isModerator = cids.map(cid => map[cid]);
filterIsModerator(cids, uid, isModerator, next);
},
], callback);
} }
function isModeratorsOfCategory(cid, uids, callback) { async function isModeratorsOfCategory(cid, uids) {
async.waterfall([ const [check1, check2, check3] = await Promise.all([
function (next) { privileges.users.isGlobalModerator(uids),
async.parallel([ groups.isMembers(uids, 'cid:' + cid + ':privileges:moderate'),
async.apply(privileges.users.isGlobalModerator, uids), groups.isMembersOfGroupList(uids, 'cid:' + cid + ':privileges:groups:moderate'),
async.apply(groups.isMembers, uids, 'cid:' + cid + ':privileges:moderate'), ]);
async.apply(groups.isMembersOfGroupList, uids, 'cid:' + cid + ':privileges:groups:moderate'), const isModerator = uids.map((uid, idx) => check1[idx] || check2[idx] || check3[idx]);
], next); return await filterIsModerator(cid, uids, isModerator);
},
function (checks, next) {
var isModerator = checks[0].map(function (isMember, idx) {
return isMember || checks[1][idx] || checks[2][idx];
});
filterIsModerator(cid, uids, isModerator, next);
},
], callback);
} }
function isModeratorOfCategory(cid, uid, callback) { async function isModeratorOfCategory(cid, uid) {
if (parseInt(uid, 10) <= 0) { const result = await isModeratorOfCategories([cid], uid);
return filterIsModerator(cid, uid, false, callback); return result ? result[0] : false;
}
async.waterfall([
function (next) {
async.parallel([
async.apply(privileges.users.isGlobalModerator, uid),
async.apply(groups.isMember, uid, 'cid:' + cid + ':privileges:moderate'),
async.apply(groups.isMemberOfGroupList, uid, 'cid:' + cid + ':privileges:groups:moderate'),
], next);
},
function (checks, next) {
var isModerator = checks[0] || checks[1] || checks[2];
filterIsModerator(cid, uid, isModerator, next);
},
], callback);
} }
function filterIsModerator(cid, uid, isModerator, callback) { async function filterIsModerator(cid, uid, isModerator) {
async.waterfall([ const data = await plugins.fireHook('filter:user.isModerator', { uid: uid, cid: cid, isModerator: isModerator });
function (next) {
plugins.fireHook('filter:user.isModerator', { uid: uid, cid: cid, isModerator: isModerator }, next);
},
function (data, next) {
if ((Array.isArray(uid) || Array.isArray(cid)) && !Array.isArray(data.isModerator)) { if ((Array.isArray(uid) || Array.isArray(cid)) && !Array.isArray(data.isModerator)) {
return callback(new Error('filter:user.isModerator - i/o mismatch')); throw new Error('filter:user.isModerator - i/o mismatch');
} }
next(null, data.isModerator); return data.isModerator;
},
], callback);
} }
privileges.users.canEdit = function (callerUid, uid, callback) { privileges.users.canEdit = async function (callerUid, uid) {
if (parseInt(callerUid, 10) === parseInt(uid, 10)) { if (parseInt(callerUid, 10) === parseInt(uid, 10)) {
return process.nextTick(callback, null, true); return true;
} }
async.waterfall([ const [isAdmin, isGlobalMod, isTargetAdmin] = await Promise.all([
function (next) { privileges.users.isAdministrator(callerUid),
async.parallel({ privileges.users.isGlobalModerator(callerUid),
isAdmin: function (next) { privileges.users.isAdministrator(uid),
privileges.users.isAdministrator(callerUid, next); ]);
},
isGlobalMod: function (next) { const data = await plugins.fireHook('filter:user.canEdit', {
privileges.users.isGlobalModerator(callerUid, next); isAdmin: isAdmin,
}, isGlobalMod: isGlobalMod,
isTargetAdmin: function (next) { isTargetAdmin: isTargetAdmin,
privileges.users.isAdministrator(uid, next); canEdit: isAdmin || (isGlobalMod && !isTargetAdmin),
}, callerUid: callerUid,
}, next); uid: uid,
}, });
function (results, next) { return data.canEdit;
results.canEdit = results.isAdmin || (results.isGlobalMod && !results.isTargetAdmin);
results.callerUid = callerUid;
results.uid = uid;
plugins.fireHook('filter:user.canEdit', results, next);
},
function (data, next) {
next(null, data.canEdit);
},
], callback);
}; };
privileges.users.canBanUser = function (callerUid, uid, callback) { privileges.users.canBanUser = async function (callerUid, uid) {
async.waterfall([ const [canBan, isTargetAdmin] = await Promise.all([
function (next) { privileges.global.can('ban', callerUid),
async.parallel({ privileges.users.isAdministrator(uid),
canBan: function (next) { ]);
privileges.global.can('ban', callerUid, next);
}, const data = await plugins.fireHook('filter:user.canBanUser', {
isTargetAdmin: function (next) { canBan: canBan && !isTargetAdmin,
privileges.users.isAdministrator(uid, next); callerUid: callerUid,
}, uid: uid,
}, next); });
}, return data.canBan;
function (results, next) {
results.canBan = !results.isTargetAdmin && results.canBan;
results.callerUid = callerUid;
results.uid = uid;
plugins.fireHook('filter:user.canBanUser', results, next);
},
function (data, next) {
next(null, data.canBan);
},
], callback);
}; };
privileges.users.hasBanPrivilege = function (uid, callback) { privileges.users.hasBanPrivilege = async function (uid) {
async.waterfall([ const canBan = await privileges.global.can('ban', uid);
function (next) { const data = await plugins.fireHook('filter:user.hasBanPrivilege', {
privileges.global.can('ban', uid, next);
},
function (canBan, next) {
plugins.fireHook('filter:user.hasBanPrivilege', {
uid: uid, uid: uid,
canBan: canBan, canBan: canBan,
}, next); });
}, return data.canBan;
function (data, next) {
next(null, data.canBan);
},
], callback);
}; };
}; };

Loading…
Cancel
Save