refactor: async/await socket.io

v1.18.x
Barış Soner Uşaklı 6 years ago
parent 9d41955bca
commit a7d2b8a1fe

@ -218,7 +218,7 @@ Emailer.send = function (template, uid, params, callback) {
}); });
}, },
], function (err) { ], function (err) {
return callback(err); callback(err);
}); });
}; };

@ -2,16 +2,16 @@
const _ = require('lodash'); const _ = require('lodash');
var db = require('../database'); const db = require('../database');
var user = require('../user'); const user = require('../user');
var meta = require('../meta'); const meta = require('../meta');
var groups = require('../groups'); const groups = require('../groups');
var topics = require('../topics'); const topics = require('../topics');
var categories = require('../categories'); const categories = require('../categories');
var notifications = require('../notifications'); const notifications = require('../notifications');
var privileges = require('../privileges'); const privileges = require('../privileges');
var plugins = require('../plugins'); const plugins = require('../plugins');
var socketHelpers = require('../socket.io/helpers'); const socketHelpers = require('../socket.io/helpers');
module.exports = function (Posts) { module.exports = function (Posts) {
Posts.shouldQueue = async function (uid, data) { Posts.shouldQueue = async function (uid, data) {

@ -1,22 +1,20 @@
'use strict'; 'use strict';
var async = require('async'); const _ = require('lodash');
var winston = require('winston');
var _ = require('lodash'); const db = require('../database');
const websockets = require('./index');
var db = require('../database'); const user = require('../user');
var websockets = require('./index'); const posts = require('../posts');
var user = require('../user'); const topics = require('../topics');
var posts = require('../posts'); const categories = require('../categories');
var topics = require('../topics'); const privileges = require('../privileges');
var categories = require('../categories'); const notifications = require('../notifications');
var privileges = require('../privileges'); const plugins = require('../plugins');
var notifications = require('../notifications'); const utils = require('../utils');
var plugins = require('../plugins'); const batch = require('../batch');
var utils = require('../utils');
var batch = require('../batch'); const SocketHelpers = module.exports;
var SocketHelpers = module.exports;
SocketHelpers.setDefaultPostData = function (data, socket) { SocketHelpers.setDefaultPostData = function (data, socket) {
data.uid = socket.uid; data.uid = socket.uid;
@ -25,81 +23,50 @@ SocketHelpers.setDefaultPostData = function (data, socket) {
data.fromQueue = false; data.fromQueue = false;
}; };
SocketHelpers.notifyNew = function (uid, type, result) { SocketHelpers.notifyNew = async function (uid, type, result) {
async.waterfall([ let uids = await user.getUidsFromSet('users:online', 0, -1);
function (next) { uids = uids.filter(toUid => parseInt(toUid, 10) !== uid);
user.getUidsFromSet('users:online', 0, -1, next); await batch.processArray(uids, async function (uids) {
}, await notifyUids(uid, uids, type, result);
function (uids, next) { }, {
uids = uids.filter(toUid => parseInt(toUid, 10) !== uid); interval: 1000,
batch.processArray(uids, function (uids, next) {
notifyUids(uid, uids, type, result, next);
}, {
interval: 1000,
}, next);
},
], function (err) {
if (err) {
return winston.error(err.stack);
}
}); });
}; };
function notifyUids(uid, uids, type, result, callback) { async function notifyUids(uid, uids, type, result) {
let watchStateUids;
let categoryWatchStates;
let topicFollowState;
const post = result.posts[0]; const post = result.posts[0];
const tid = post.topic.tid; const tid = post.topic.tid;
const cid = post.topic.cid; const cid = post.topic.cid;
async.waterfall([ uids = await privileges.topics.filterUids('topics:read', tid, uids);
function (next) { const watchStateUids = uids;
privileges.topics.filterUids('topics:read', tid, uids, next);
}, const watchStates = await getWatchStates(watchStateUids, tid, cid);
function (uids, next) {
watchStateUids = uids; const categoryWatchStates = _.zipObject(watchStateUids, watchStates.categoryWatchStates);
getWatchStates(watchStateUids, tid, cid, next); const topicFollowState = _.zipObject(watchStateUids, watchStates.topicFollowed);
}, uids = filterTidCidIgnorers(watchStateUids, watchStates);
function (watchStates, next) { uids = await user.blocks.filterUids(uid, uids);
categoryWatchStates = _.zipObject(watchStateUids, watchStates.categoryWatchStates); uids = await user.blocks.filterUids(post.topic.uid, uids);
topicFollowState = _.zipObject(watchStateUids, watchStates.topicFollowed); const data = await plugins.fireHook('filter:sockets.sendNewPostToUids', { uidsTo: uids, uidFrom: uid, type: type });
const uids = filterTidCidIgnorers(watchStateUids, watchStates);
user.blocks.filterUids(uid, uids, next); post.ip = undefined;
},
function (uids, next) { data.uidsTo.forEach(function (toUid) {
user.blocks.filterUids(post.topic.uid, uids, next); post.categoryWatchState = categoryWatchStates[toUid];
}, post.topic.isFollowing = topicFollowState[toUid];
function (uids, next) { websockets.in('uid_' + toUid).emit('event:new_post', result);
plugins.fireHook('filter:sockets.sendNewPostToUids', { uidsTo: uids, uidFrom: uid, type: type }, next); if (result.topic && type === 'newTopic') {
}, websockets.in('uid_' + toUid).emit('event:new_topic', result.topic);
function (data, next) { }
post.ip = undefined; });
data.uidsTo.forEach(function (toUid) {
post.categoryWatchState = categoryWatchStates[toUid];
post.topic.isFollowing = topicFollowState[toUid];
websockets.in('uid_' + toUid).emit('event:new_post', result);
if (result.topic && type === 'newTopic') {
websockets.in('uid_' + toUid).emit('event:new_topic', result.topic);
}
});
setImmediate(next);
},
], callback);
} }
function getWatchStates(uids, tid, cid, callback) { async function getWatchStates(uids, tid, cid) {
async.parallel({ return await utils.promiseParallel({
topicFollowed: function (next) { topicFollowed: db.isSetMembers('tid:' + tid + ':followers', uids),
db.isSetMembers('tid:' + tid + ':followers', uids, next); topicIgnored: db.isSetMembers('tid:' + tid + ':ignorers', uids),
}, categoryWatchStates: categories.getUidsWatchStates(cid, uids),
topicIgnored: function (next) { });
db.isSetMembers('tid:' + tid + ':ignorers', uids, next);
},
categoryWatchStates: function (next) {
categories.getUidsWatchStates(cid, uids, next);
},
}, callback);
} }
function filterTidCidIgnorers(uids, watchStates) { function filterTidCidIgnorers(uids, watchStates) {
@ -109,112 +76,87 @@ function filterTidCidIgnorers(uids, watchStates) {
}); });
} }
SocketHelpers.sendNotificationToPostOwner = function (pid, fromuid, command, notification) { SocketHelpers.sendNotificationToPostOwner = async function (pid, fromuid, command, notification) {
if (!pid || !fromuid || !notification) { if (!pid || !fromuid || !notification) {
return; return;
} }
fromuid = parseInt(fromuid, 10); fromuid = parseInt(fromuid, 10);
var postData; const postData = await posts.getPostFields(pid, ['tid', 'uid', 'content']);
async.waterfall([ const [canRead, isIgnoring] = await Promise.all([
function (next) { privileges.posts.can('topics:read', pid, postData.uid),
posts.getPostFields(pid, ['tid', 'uid', 'content'], next); topics.isIgnoring([postData.tid], postData.uid),
}, ]);
function (_postData, next) { if (!canRead || isIgnoring[0] || !postData.uid || fromuid === postData.uid) {
postData = _postData; return;
async.parallel({ }
canRead: async.apply(privileges.posts.can, 'topics:read', pid, postData.uid), const [username, topicTitle, postObj] = await Promise.all([
isIgnoring: async.apply(topics.isIgnoring, [postData.tid], postData.uid), user.getUserField(fromuid, 'username'),
}, next); topics.getTopicField(postData.tid, 'title'),
}, posts.parsePost(postData),
function (results, next) { ]);
if (!results.canRead || results.isIgnoring[0] || !postData.uid || fromuid === postData.uid) {
return; const title = utils.decodeHTMLEntities(topicTitle);
} const titleEscaped = title.replace(/%/g, '%').replace(/,/g, ',');
async.parallel({
username: async.apply(user.getUserField, fromuid, 'username'), const notifObj = await notifications.create({
topicTitle: async.apply(topics.getTopicField, postData.tid, 'title'), type: command,
postObj: async.apply(posts.parsePost, postData), bodyShort: '[[' + notification + ', ' + username + ', ' + titleEscaped + ']]',
}, next); bodyLong: postObj.content,
}, pid: pid,
function (results, next) { tid: postData.tid,
var title = utils.decodeHTMLEntities(results.topicTitle); path: '/post/' + pid,
var titleEscaped = title.replace(/%/g, '%').replace(/,/g, ','); nid: command + ':post:' + pid + ':uid:' + fromuid,
from: fromuid,
notifications.create({ mergeId: notification + '|' + pid,
type: command, topicTitle: topicTitle,
bodyShort: '[[' + notification + ', ' + results.username + ', ' + titleEscaped + ']]',
bodyLong: results.postObj.content,
pid: pid,
tid: postData.tid,
path: '/post/' + pid,
nid: command + ':post:' + pid + ':uid:' + fromuid,
from: fromuid,
mergeId: notification + '|' + pid,
topicTitle: results.topicTitle,
}, next);
},
], function (err, notification) {
if (err) {
return winston.error(err);
}
if (notification) {
notifications.push(notification, [postData.uid]);
}
}); });
notifications.push(notifObj, [postData.uid]);
}; };
SocketHelpers.sendNotificationToTopicOwner = function (tid, fromuid, command, notification) { SocketHelpers.sendNotificationToTopicOwner = async function (tid, fromuid, command, notification) {
if (!tid || !fromuid || !notification) { if (!tid || !fromuid || !notification) {
return; return;
} }
fromuid = parseInt(fromuid, 10); fromuid = parseInt(fromuid, 10);
var ownerUid; const [username, topicData] = await Promise.all([
async.waterfall([ user.getUserField(fromuid, 'username'),
function (next) { topics.getTopicFields(tid, ['uid', 'slug', 'title']),
async.parallel({ ]);
username: async.apply(user.getUserField, fromuid, 'username'),
topicData: async.apply(topics.getTopicFields, tid, ['uid', 'slug', 'title']),
}, next);
},
function (results, next) {
if (fromuid === results.topicData.uid) {
return;
}
ownerUid = results.topicData.uid;
var title = utils.decodeHTMLEntities(results.topicData.title);
var titleEscaped = title.replace(/%/g, '%').replace(/,/g, ',');
notifications.create({ if (fromuid === topicData.uid) {
bodyShort: '[[' + notification + ', ' + results.username + ', ' + titleEscaped + ']]', return;
path: '/topic/' + results.topicData.slug, }
nid: command + ':tid:' + tid + ':uid:' + fromuid, const ownerUid = topicData.uid;
from: fromuid, const title = utils.decodeHTMLEntities(topicData.title);
}, next); const titleEscaped = title.replace(/%/g, '%').replace(/,/g, ',');
},
], function (err, notification) { const notifObj = await notifications.create({
if (err) { bodyShort: '[[' + notification + ', ' + username + ', ' + titleEscaped + ']]',
return winston.error(err); path: '/topic/' + topicData.slug,
} nid: command + ':tid:' + tid + ':uid:' + fromuid,
if (notification && ownerUid) { from: fromuid,
notifications.push(notification, [ownerUid]);
}
}); });
if (ownerUid) {
notifications.push(notifObj, [ownerUid]);
}
}; };
SocketHelpers.upvote = function (data, notification) { SocketHelpers.upvote = async function (data, notification) {
if (!data || !data.post || !data.post.uid || !data.post.votes || !data.post.pid || !data.fromuid) { if (!data || !data.post || !data.post.uid || !data.post.votes || !data.post.pid || !data.fromuid) {
return; return;
} }
var votes = data.post.votes; const votes = data.post.votes;
var touid = data.post.uid; const touid = data.post.uid;
var fromuid = data.fromuid; const fromuid = data.fromuid;
var pid = data.post.pid; const pid = data.post.pid;
var shouldNotify = { const shouldNotify = {
all: function () { all: function () {
return votes > 0; return votes > 0;
}, },
@ -234,52 +176,24 @@ SocketHelpers.upvote = function (data, notification) {
return false; return false;
}, },
}; };
const settings = await user.getSettings(touid);
const should = shouldNotify[settings.upvoteNotifFreq] || shouldNotify.all;
async.waterfall([ if (should()) {
function (next) { SocketHelpers.sendNotificationToPostOwner(pid, fromuid, 'upvote', notification);
user.getSettings(touid, next); }
},
function (settings, next) {
var should = shouldNotify[settings.upvoteNotifFreq] || shouldNotify.all;
if (should()) {
SocketHelpers.sendNotificationToPostOwner(pid, fromuid, 'upvote', notification);
}
next();
},
], function (err) {
if (err) {
winston.error(err);
}
});
}; };
SocketHelpers.rescindUpvoteNotification = function (pid, fromuid) { SocketHelpers.rescindUpvoteNotification = async function (pid, fromuid) {
var uid; await notifications.rescind('upvote:post:' + pid + ':uid:' + fromuid);
async.waterfall([ const uid = await posts.getPostField(pid, 'uid');
function (next) { const count = await user.notifications.getUnreadCount(uid);
notifications.rescind('upvote:post:' + pid + ':uid:' + fromuid, next); websockets.in('uid_' + uid).emit('event:notifications.updateCount', count);
},
function (next) {
posts.getPostField(pid, 'uid', next);
},
function (_uid, next) {
uid = _uid;
user.notifications.getUnreadCount(uid, next);
},
function (count, next) {
websockets.in('uid_' + uid).emit('event:notifications.updateCount', count);
next();
},
], function (err) {
if (err) {
winston.error(err);
}
});
}; };
SocketHelpers.emitToTopicAndCategory = function (event, data) { SocketHelpers.emitToTopicAndCategory = function (event, data) {
websockets.in('topic_' + data.tid).emit(event, data); websockets.in('topic_' + data.tid).emit(event, data);
websockets.in('category_' + data.cid).emit(event, data); websockets.in('category_' + data.cid).emit(event, data);
}; };
require('../promisify')(SocketHelpers);

@ -1,19 +1,18 @@
'use strict'; 'use strict';
var async = require('async'); const validator = require('validator');
var validator = require('validator');
var db = require('../database'); const db = require('../database');
var meta = require('../meta'); const meta = require('../meta');
var notifications = require('../notifications'); const notifications = require('../notifications');
var plugins = require('../plugins'); const plugins = require('../plugins');
var Messaging = require('../messaging'); const Messaging = require('../messaging');
var utils = require('../utils'); const utils = require('../utils');
var server = require('./'); const server = require('./');
var user = require('../user'); const user = require('../user');
var privileges = require('../privileges'); const privileges = require('../privileges');
var SocketModules = module.exports; const SocketModules = module.exports;
SocketModules.chats = {}; SocketModules.chats = {};
SocketModules.sounds = {}; SocketModules.sounds = {};
@ -21,403 +20,276 @@ SocketModules.settings = {};
/* Chat */ /* Chat */
SocketModules.chats.getRaw = function (socket, data, callback) { SocketModules.chats.getRaw = async function (socket, data) {
if (!data || !data.hasOwnProperty('mid')) { if (!data || !data.hasOwnProperty('mid')) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
async.waterfall([ const roomId = await Messaging.getMessageField(data.mid, 'roomId');
function (next) { const [isAdmin, hasMessage, inRoom] = await Promise.all([
Messaging.getMessageField(data.mid, 'roomId', next); user.isAdministrator(socket.uid),
}, db.isSortedSetMember('uid:' + socket.uid + ':chat:room:' + roomId + ':mids', data.mid),
function (roomId, next) { Messaging.isUserInRoom(socket.uid, roomId),
async.parallel({ ]);
isAdmin: function (next) {
user.isAdministrator(socket.uid, next); if (!isAdmin && (!inRoom || !hasMessage)) {
}, throw new Error('[[error:not-allowed]]');
hasMessage: function (next) { }
db.isSortedSetMember('uid:' + socket.uid + ':chat:room:' + roomId + ':mids', data.mid, next);
}, return await Messaging.getMessageField(data.mid, 'content');
inRoom: function (next) {
Messaging.isUserInRoom(socket.uid, roomId, next);
},
}, next);
},
function (results, next) {
if (!results.isAdmin && (!results.inRoom || !results.hasMessage)) {
return next(new Error('[[error:not-allowed]]'));
}
Messaging.getMessageField(data.mid, 'content', next);
},
], callback);
}; };
SocketModules.chats.isDnD = function (socket, uid, callback) { SocketModules.chats.isDnD = async function (socket, uid) {
async.waterfall([ const status = await db.getObjectField('user:' + uid, 'status');
function (next) { return status === 'dnd';
db.getObjectField('user:' + uid, 'status', next);
},
function (status, next) {
next(null, status === 'dnd');
},
], callback);
}; };
SocketModules.chats.newRoom = function (socket, data, callback) { SocketModules.chats.newRoom = async function (socket, data) {
if (!data) { if (!data) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
if (rateLimitExceeded(socket)) { if (rateLimitExceeded(socket)) {
return callback(new Error('[[error:too-many-messages]]')); throw new Error('[[error:too-many-messages]]');
} }
async.waterfall([ const canChat = await privileges.global.can('chat', socket.uid);
function (next) { if (!canChat) {
privileges.global.can('chat', socket.uid, next); throw new Error('[[error:no-privileges]]');
}, }
function (canChat, next) { await Messaging.canMessageUser(socket.uid, data.touid);
if (!canChat) { return await Messaging.newRoom(socket.uid, [data.touid]);
return next(new Error('[[error:no-privileges]]'));
}
Messaging.canMessageUser(socket.uid, data.touid, next);
},
function (next) {
Messaging.newRoom(socket.uid, [data.touid], next);
},
], callback);
}; };
SocketModules.chats.send = function (socket, data, callback) { SocketModules.chats.send = async function (socket, data) {
if (!data || !data.roomId || !socket.uid) { if (!data || !data.roomId || !socket.uid) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
if (rateLimitExceeded(socket)) { if (rateLimitExceeded(socket)) {
return callback(new Error('[[error:too-many-messages]]')); throw new Error('[[error:too-many-messages]]');
} }
const canChat = await privileges.global.can('chat', socket.uid);
if (!canChat) {
throw new Error('[[error:no-privileges]]');
}
const results = await plugins.fireHook('filter:messaging.send', {
data: data,
uid: socket.uid,
});
data = results.data;
async.waterfall([ await Messaging.canMessageRoom(socket.uid, data.roomId);
function (next) { const message = await Messaging.sendMessage({
privileges.global.can('chat', socket.uid, next); uid: socket.uid,
}, roomId: data.roomId,
function (canChat, next) { content: data.message,
if (!canChat) { timestamp: Date.now(),
return next(new Error('[[error:no-privileges]]')); ip: socket.ip,
} });
Messaging.notifyUsersInRoom(socket.uid, data.roomId, message);
plugins.fireHook('filter:messaging.send', { user.updateOnlineUsers(socket.uid);
data: data, return message;
uid: socket.uid,
}, function (err, results) {
data = results.data;
next(err);
});
},
function (next) {
Messaging.canMessageRoom(socket.uid, data.roomId, next);
},
function (next) {
Messaging.sendMessage({
uid: socket.uid,
roomId: data.roomId,
content: data.message,
timestamp: Date.now(),
ip: socket.ip,
}, next);
},
function (message, next) {
Messaging.notifyUsersInRoom(socket.uid, data.roomId, message);
user.updateOnlineUsers(socket.uid);
next(null, message);
},
], callback);
}; };
function rateLimitExceeded(socket) { function rateLimitExceeded(socket) {
var now = Date.now(); const now = Date.now();
socket.lastChatMessageTime = socket.lastChatMessageTime || 0; socket.lastChatMessageTime = socket.lastChatMessageTime || 0;
if (now - socket.lastChatMessageTime < meta.config.chatMessageDelay) { if (now - socket.lastChatMessageTime < meta.config.chatMessageDelay) {
return true; return true;
} }
socket.lastChatMessageTime = now; socket.lastChatMessageTime = now;
return false; return false;
} }
SocketModules.chats.loadRoom = function (socket, data, callback) { SocketModules.chats.loadRoom = async function (socket, data) {
if (!data || !data.roomId) { if (!data || !data.roomId) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
Messaging.loadRoom(socket.uid, data, callback); return await Messaging.loadRoom(socket.uid, data);
}; };
SocketModules.chats.getUsersInRoom = function (socket, data, callback) { SocketModules.chats.getUsersInRoom = async function (socket, data) {
if (!data || !data.roomId) { if (!data || !data.roomId) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
const [userData, isOwner] = await Promise.all([
Messaging.getUsersInRoom(data.roomId, 0, -1),
Messaging.isRoomOwner(socket.uid, data.roomId),
]);
async.parallel({ userData.forEach((user) => {
users: async.apply(Messaging.getUsersInRoom, data.roomId, 0, -1), user.canKick = (parseInt(user.uid, 10) !== parseInt(socket.uid, 10)) && isOwner;
isOwner: async.apply(Messaging.isRoomOwner, socket.uid, data.roomId),
}, function (err, payload) {
if (err) {
return callback(err);
}
payload.users = payload.users.map((user) => {
user.canKick = (parseInt(user.uid, 10) !== parseInt(socket.uid, 10)) && payload.isOwner;
return user;
});
callback(null, payload.users);
}); });
return userData;
}; };
SocketModules.chats.addUserToRoom = function (socket, data, callback) { SocketModules.chats.addUserToRoom = async function (socket, data) {
if (!data || !data.roomId || !data.username) { if (!data || !data.roomId || !data.username) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
}
const canChat = await privileges.global.can('chat', socket.uid);
if (!canChat) {
throw new Error('[[error:no-privileges]]');
}
const userCount = await Messaging.getUserCountInRoom(data.roomId);
const maxUsers = meta.config.maximumUsersInChatRoom;
if (maxUsers && userCount >= maxUsers) {
throw new Error('[[error:cant-add-more-users-to-chat-room]]');
}
const uid = await user.getUidByUsername(data.username);
if (!uid) {
throw new Error('[[error:no-user]]');
}
if (socket.uid === parseInt(uid, 10)) {
throw new Error('[[error:cant-chat-with-yourself]]');
}
const [settings, isAdminOrGlobalMod, isFollowing] = await Promise.all([
user.getSettings(uid),
user.isAdminOrGlobalMod(socket.uid),
user.isFollowing(uid, socket.uid),
]);
if (settings.restrictChat && !isAdminOrGlobalMod && !isFollowing) {
throw new Error('[[error:chat-restricted]]');
} }
var uid;
async.waterfall([ await Messaging.addUsersToRoom(socket.uid, [uid], data.roomId);
function (next) {
privileges.global.can('chat', socket.uid, next);
},
function (canChat, next) {
if (!canChat) {
return next(new Error('[[error:no-privileges]]'));
}
Messaging.getUserCountInRoom(data.roomId, next);
},
function (userCount, next) {
var maxUsers = meta.config.maximumUsersInChatRoom;
if (maxUsers && userCount >= maxUsers) {
return next(new Error('[[error:cant-add-more-users-to-chat-room]]'));
}
next();
},
function (next) {
user.getUidByUsername(data.username, next);
},
function (_uid, next) {
uid = _uid;
if (!uid) {
return next(new Error('[[error:no-user]]'));
}
if (socket.uid === parseInt(uid, 10)) {
return next(new Error('[[error:cant-chat-with-yourself]]'));
}
async.parallel({
settings: async.apply(user.getSettings, uid),
isAdminOrGlobalMod: async.apply(user.isAdminOrGlobalMod, socket.uid),
isFollowing: async.apply(user.isFollowing, uid, socket.uid),
}, next);
},
function (results, next) {
if (results.settings.restrictChat && !results.isAdminOrGlobalMod && !results.isFollowing) {
return next(new Error('[[error:chat-restricted]]'));
}
Messaging.addUsersToRoom(socket.uid, [uid], data.roomId, next);
},
], callback);
}; };
SocketModules.chats.removeUserFromRoom = function (socket, data, callback) { SocketModules.chats.removeUserFromRoom = async function (socket, data) {
if (!data || !data.roomId) { if (!data || !data.roomId) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
}
const exists = await user.exists(data.uid);
if (!exists) {
throw new Error('[[error:no-user]]');
} }
async.waterfall([ await Messaging.removeUsersFromRoom(socket.uid, [data.uid], data.roomId);
function (next) {
user.exists(data.uid, next);
},
function (exists, next) {
if (!exists) {
return next(new Error('[[error:no-user]]'));
}
Messaging.removeUsersFromRoom(socket.uid, [data.uid], data.roomId, next);
},
], callback);
}; };
SocketModules.chats.leave = function (socket, roomid, callback) { SocketModules.chats.leave = async function (socket, roomid) {
if (!socket.uid || !roomid) { if (!socket.uid || !roomid) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
Messaging.leaveRoom([socket.uid], roomid, callback); await Messaging.leaveRoom([socket.uid], roomid);
}; };
SocketModules.chats.edit = async function (socket, data) {
SocketModules.chats.edit = function (socket, data, callback) {
if (!data || !data.roomId || !data.message) { if (!data || !data.roomId || !data.message) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
await Messaging.canEdit(data.mid, socket.uid);
async.waterfall([ await Messaging.editMessage(socket.uid, data.mid, data.roomId, data.message);
function (next) {
Messaging.canEdit(data.mid, socket.uid, next);
},
function (next) {
Messaging.editMessage(socket.uid, data.mid, data.roomId, data.message, next);
},
], callback);
}; };
SocketModules.chats.delete = function (socket, data, callback) { SocketModules.chats.delete = async function (socket, data) {
if (!data || !data.roomId || !data.messageId) { if (!data || !data.roomId || !data.messageId) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
await Messaging.canDelete(data.messageId, socket.uid);
async.waterfall([ await Messaging.deleteMessage(data.messageId);
function (next) {
Messaging.canDelete(data.messageId, socket.uid, next);
},
function (next) {
Messaging.deleteMessage(data.messageId, next);
},
], callback);
}; };
SocketModules.chats.restore = function (socket, data, callback) { SocketModules.chats.restore = async function (socket, data) {
if (!data || !data.roomId || !data.messageId) { if (!data || !data.roomId || !data.messageId) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
await Messaging.canDelete(data.messageId, socket.uid);
async.waterfall([ await Messaging.restoreMessage(data.messageId);
function (next) {
Messaging.canDelete(data.messageId, socket.uid, next);
},
function (next) {
Messaging.restoreMessage(data.messageId, next);
},
], callback);
}; };
SocketModules.chats.canMessage = function (socket, roomId, callback) { SocketModules.chats.canMessage = async function (socket, roomId) {
Messaging.canMessageRoom(socket.uid, roomId, callback); await Messaging.canMessageRoom(socket.uid, roomId);
}; };
SocketModules.chats.markRead = function (socket, roomId, callback) { SocketModules.chats.markRead = async function (socket, roomId) {
if (!socket.uid || !roomId) { if (!socket.uid || !roomId) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
}
const [uidsInRoom] = await Promise.all([
Messaging.getUidsInRoom(roomId, 0, -1),
Messaging.markRead(socket.uid, roomId),
]);
Messaging.pushUnreadCount(socket.uid);
server.in('uid_' + socket.uid).emit('event:chats.markedAsRead', { roomId: roomId });
if (!uidsInRoom.includes(String(socket.uid))) {
return;
} }
async.waterfall([
function (next) { // Mark notification read
async.parallel({ const nids = uidsInRoom.filter(uid => parseInt(uid, 10) !== socket.uid)
uidsInRoom: async.apply(Messaging.getUidsInRoom, roomId, 0, -1), .map(uid => 'chat_' + uid + '_' + roomId);
markRead: async.apply(Messaging.markRead, socket.uid, roomId),
}, next); await notifications.markReadMultiple(nids, socket.uid);
}, await user.notifications.pushCount(socket.uid);
function (results, next) {
Messaging.pushUnreadCount(socket.uid);
server.in('uid_' + socket.uid).emit('event:chats.markedAsRead', { roomId: roomId });
if (!results.uidsInRoom.includes(String(socket.uid))) {
return callback();
}
// Mark notification read
var nids = results.uidsInRoom.filter(function (uid) {
return parseInt(uid, 10) !== socket.uid;
}).map(function (uid) {
return 'chat_' + uid + '_' + roomId;
});
notifications.markReadMultiple(nids, socket.uid, function () {
user.notifications.pushCount(socket.uid);
});
next();
},
], callback);
}; };
SocketModules.chats.markAllRead = function (socket, data, callback) { SocketModules.chats.markAllRead = async function (socket) {
async.waterfall([ await Messaging.markAllRead(socket.uid);
function (next) { Messaging.pushUnreadCount(socket.uid);
Messaging.markAllRead(socket.uid, next);
},
function (next) {
Messaging.pushUnreadCount(socket.uid);
next();
},
], callback);
}; };
SocketModules.chats.renameRoom = function (socket, data, callback) { SocketModules.chats.renameRoom = async function (socket, data) {
if (!data || !data.roomId || !data.newName) { if (!data || !data.roomId || !data.newName) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
await Messaging.renameRoom(socket.uid, data.roomId, data.newName);
async.waterfall([ const uids = await Messaging.getUidsInRoom(data.roomId, 0, -1);
function (next) { const eventData = { roomId: data.roomId, newName: validator.escape(String(data.newName)) };
Messaging.renameRoom(socket.uid, data.roomId, data.newName, next); uids.forEach(function (uid) {
}, server.in('uid_' + uid).emit('event:chats.roomRename', eventData);
function (next) { });
Messaging.getUidsInRoom(data.roomId, 0, -1, next);
},
function (uids, next) {
var eventData = { roomId: data.roomId, newName: validator.escape(String(data.newName)) };
uids.forEach(function (uid) {
server.in('uid_' + uid).emit('event:chats.roomRename', eventData);
});
next();
},
], callback);
}; };
SocketModules.chats.getRecentChats = function (socket, data, callback) { SocketModules.chats.getRecentChats = async function (socket, data) {
if (!data || !utils.isNumber(data.after) || !utils.isNumber(data.uid)) { if (!data || !utils.isNumber(data.after) || !utils.isNumber(data.uid)) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
var start = parseInt(data.after, 10); const start = parseInt(data.after, 10);
var stop = start + 9; const stop = start + 9;
Messaging.getRecentChats(socket.uid, data.uid, start, stop, callback); return await Messaging.getRecentChats(socket.uid, data.uid, start, stop);
}; };
SocketModules.chats.hasPrivateChat = function (socket, uid, callback) { SocketModules.chats.hasPrivateChat = async function (socket, uid) {
if (socket.uid <= 0 || uid <= 0) { if (socket.uid <= 0 || uid <= 0) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
Messaging.hasPrivateChat(socket.uid, uid, callback); return await Messaging.hasPrivateChat(socket.uid, uid);
}; };
SocketModules.chats.getMessages = function (socket, data, callback) { SocketModules.chats.getMessages = async function (socket, data) {
if (!socket.uid || !data || !data.uid || !data.roomId) { if (!socket.uid || !data || !data.uid || !data.roomId) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
var params = { return await Messaging.getMessages({
callerUid: socket.uid, callerUid: socket.uid,
uid: data.uid, uid: data.uid,
roomId: data.roomId, roomId: data.roomId,
start: parseInt(data.start, 10) || 0, start: parseInt(data.start, 10) || 0,
count: 50, count: 50,
}; });
Messaging.getMessages(params, callback);
}; };
SocketModules.chats.getIP = function (socket, mid, callback) { SocketModules.chats.getIP = async function (socket, mid) {
async.waterfall([ const allowed = await user.isAdminOrGlobalMod(socket.uid);
function (next) { if (!allowed) {
user.isAdminOrGlobalMod(socket.uid, next); throw new Error('[[error:no-privilege]]');
}, }
function (allowed, next) { return await Messaging.getMessageField(mid, 'ip');
if (!allowed) {
return next(new Error('[[error:no-privilege]]'));
}
Messaging.getMessageField(mid, 'ip', next);
},
], callback);
}; };
/* Sounds */ /* Sounds */
SocketModules.sounds.getUserSoundMap = function getUserSoundMap(socket, data, callback) { SocketModules.sounds.getUserSoundMap = async function getUserSoundMap(socket) {
meta.sounds.getUserSoundMap(socket.uid, callback); return await meta.sounds.getUserSoundMap(socket.uid);
}; };
require('../promisify')(SocketModules);

@ -1,63 +1,41 @@
'use strict'; 'use strict';
var async = require('async'); const user = require('../user');
const notifications = require('../notifications');
const SocketNotifs = module.exports;
var user = require('../user'); SocketNotifs.get = async function (socket, data) {
var notifications = require('../notifications');
var SocketNotifs = module.exports;
SocketNotifs.get = function (socket, data, callback) {
if (data && Array.isArray(data.nids) && socket.uid) { if (data && Array.isArray(data.nids) && socket.uid) {
user.notifications.getNotifications(data.nids, socket.uid, callback); return await user.notifications.getNotifications(data.nids, socket.uid);
} else {
user.notifications.get(socket.uid, callback);
} }
return await user.notifications.get(socket.uid);
}; };
SocketNotifs.getCount = function (socket, data, callback) { SocketNotifs.getCount = async function (socket) {
user.notifications.getUnreadCount(socket.uid, callback); return await user.notifications.getUnreadCount(socket.uid);
}; };
SocketNotifs.deleteAll = function (socket, data, callback) { SocketNotifs.deleteAll = async function (socket) {
if (!socket.uid) { if (!socket.uid) {
return callback(new Error('[[error:no-privileges]]')); throw new Error('[[error:no-privileges]]');
} }
user.notifications.deleteAll(socket.uid, callback); await user.notifications.deleteAll(socket.uid);
}; };
SocketNotifs.markRead = function (socket, nid, callback) { SocketNotifs.markRead = async function (socket, nid) {
async.waterfall([ await notifications.markRead(nid, socket.uid);
function (next) { user.notifications.pushCount(socket.uid);
notifications.markRead(nid, socket.uid, next);
},
function (next) {
user.notifications.pushCount(socket.uid);
next();
},
], callback);
}; };
SocketNotifs.markUnread = function (socket, nid, callback) { SocketNotifs.markUnread = async function (socket, nid) {
async.waterfall([ await notifications.markUnread(nid, socket.uid);
function (next) { user.notifications.pushCount(socket.uid);
notifications.markUnread(nid, socket.uid, next);
},
function (next) {
user.notifications.pushCount(socket.uid);
next();
},
], callback);
}; };
SocketNotifs.markAllRead = function (socket, data, callback) { SocketNotifs.markAllRead = async function (socket) {
async.waterfall([ await notifications.markAllRead(socket.uid);
function (next) { user.notifications.pushCount(socket.uid);
notifications.markAllRead(socket.uid, next);
},
function (next) {
user.notifications.pushCount(socket.uid);
next();
},
], callback);
}; };
require('../promisify')(SocketNotifs);

@ -1,20 +1,24 @@
'use strict'; 'use strict';
var async = require('async'); const async = require('async');
var user = require('../user'); const util = require('util');
var topics = require('../topics'); const sleep = util.promisify(setTimeout);
var notifications = require('../notifications');
var messaging = require('../messaging'); const user = require('../user');
var plugins = require('../plugins'); const topics = require('../topics');
var meta = require('../meta'); const notifications = require('../notifications');
var events = require('../events'); const messaging = require('../messaging');
var emailer = require('../emailer'); const plugins = require('../plugins');
var db = require('../database'); const meta = require('../meta');
var userController = require('../controllers/user'); const events = require('../events');
var privileges = require('../privileges'); const emailer = require('../emailer');
const db = require('../database');
var SocketUser = module.exports; const userController = require('../controllers/user');
const privileges = require('../privileges');
const utils = require('../utils');
const SocketUser = module.exports;
require('./user/profile')(SocketUser); require('./user/profile')(SocketUser);
require('./user/search')(SocketUser); require('./user/search')(SocketUser);
@ -23,375 +27,296 @@ require('./user/picture')(SocketUser);
require('./user/ban')(SocketUser); require('./user/ban')(SocketUser);
require('./user/registration')(SocketUser); require('./user/registration')(SocketUser);
SocketUser.exists = function (socket, data, callback) { SocketUser.exists = async function (socket, data) {
if (!data || !data.username) { if (!data || !data.username) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
meta.userOrGroupExists(data.username, callback); return await meta.userOrGroupExists(data.username);
}; };
SocketUser.deleteAccount = function (socket, data, callback) { SocketUser.deleteAccount = async function (socket, data) {
if (!socket.uid) { if (!socket.uid) {
return callback(new Error('[[error:no-privileges]]')); throw new Error('[[error:no-privileges]]');
} }
const hasPassword = await user.hasPassword(socket.uid);
if (hasPassword) {
const ok = await user.isPasswordCorrect(socket.uid, data.password, socket.ip);
if (!ok) {
throw new Error('[[error:invalid-password]]');
}
}
const isAdmin = await user.isAdministrator(socket.uid);
if (isAdmin) {
throw new Error('[[error:cant-delete-admin]]');
}
const userData = await user.deleteAccount(socket.uid);
require('./index').server.sockets.emit('event:user_status_change', { uid: socket.uid, status: 'offline' });
async.waterfall([ await events.log({
function (next) { type: 'user-delete',
user.hasPassword(socket.uid, next); uid: socket.uid,
}, targetUid: socket.uid,
function (hasPassword, next) { ip: socket.ip,
if (!hasPassword) { username: userData.username,
return next(); email: userData.email,
} });
user.isPasswordCorrect(socket.uid, data.password, socket.ip, function (err, ok) {
next(err || (!ok ? new Error('[[error:invalid-password]]') : undefined));
});
},
function (next) {
user.isAdministrator(socket.uid, next);
},
function (isAdmin, next) {
if (isAdmin) {
return next(new Error('[[error:cant-delete-admin]]'));
}
user.deleteAccount(socket.uid, next);
},
function (userData, next) {
require('./index').server.sockets.emit('event:user_status_change', { uid: socket.uid, status: 'offline' });
events.log({
type: 'user-delete',
uid: socket.uid,
targetUid: socket.uid,
ip: socket.ip,
username: userData.username,
email: userData.email,
});
next();
},
], callback);
}; };
SocketUser.emailExists = function (socket, data, callback) { SocketUser.emailExists = async function (socket, data) {
if (!data || !data.email) { if (!data || !data.email) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
user.email.exists(data.email, callback); return await user.email.exists(data.email);
}; };
SocketUser.emailConfirm = function (socket, data, callback) { SocketUser.emailConfirm = async function (socket) {
if (!socket.uid) { if (!socket.uid) {
return callback(new Error('[[error:no-privileges]]')); throw new Error('[[error:no-privileges]]');
} }
if (!meta.config.requireEmailConfirmation) { if (!meta.config.requireEmailConfirmation) {
return callback(new Error('[[error:email-confirmations-are-disabled]]')); throw new Error('[[error:email-confirmations-are-disabled]]');
} }
user.email.sendValidationEmail(socket.uid, callback); return await user.email.sendValidationEmail(socket.uid);
}; };
// Password Reset // Password Reset
SocketUser.reset = {}; SocketUser.reset = {};
SocketUser.reset.send = function (socket, email, callback) { SocketUser.reset.send = async function (socket, email) {
if (!email) { if (!email) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
if (meta.config['password:disableEdit']) { if (meta.config['password:disableEdit']) {
return callback(new Error('[[error:no-privileges]]')); throw new Error('[[error:no-privileges]]');
} }
async function logEvent(text) {
user.reset.send(email, function (err) { await events.log({
events.log({
type: 'password-reset', type: 'password-reset',
text: err ? err.message : '[[success:success]]', text: text,
ip: socket.ip, ip: socket.ip,
uid: socket.uid, uid: socket.uid,
email: email, email: email,
}); });
}
try {
await user.reset.send(email);
await logEvent('[[success:success]]');
await sleep(2500);
} catch (err) {
await logEvent(err.message);
const internalErrors = ['[[error:invalid-email]]', '[[error:reset-rate-limited]]']; const internalErrors = ['[[error:invalid-email]]', '[[error:reset-rate-limited]]'];
if (err && internalErrors.includes(err.message)) { if (!internalErrors.includes(err.message)) {
err = null; throw err;
} }
}
setTimeout(callback.bind(err), 2500);
});
}; };
SocketUser.reset.commit = function (socket, data, callback) { SocketUser.reset.commit = async function (socket, data) {
if (!data || !data.code || !data.password) { if (!data || !data.code || !data.password) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
var uid; const [uid] = await Promise.all([
async.waterfall([ db.getObjectField('reset:uid', data.code),
function (next) { user.reset.commit(data.code, data.password),
async.parallel({ plugins.fireHook('action:password.reset', { uid: socket.uid }),
uid: async.apply(db.getObjectField, 'reset:uid', data.code), ]);
reset: async.apply(user.reset.commit, data.code, data.password),
hook: async.apply(plugins.fireHook, 'action:password.reset', { uid: socket.uid }), await events.log({
}, next); type: 'password-reset',
}, uid: uid,
function (results, next) { ip: socket.ip,
uid = results.uid; });
events.log({
type: 'password-reset', const username = await user.getUserField(uid, 'username');
uid: uid, const now = new Date();
ip: socket.ip, const parsedDate = now.getFullYear() + '/' + (now.getMonth() + 1) + '/' + now.getDate();
}); emailer.send('reset_notify', uid, {
username: username,
user.getUserField(uid, 'username', next); date: parsedDate,
}, subject: '[[email:reset.notify.subject]]',
function (username, next) { });
var now = new Date();
var parsedDate = now.getFullYear() + '/' + (now.getMonth() + 1) + '/' + now.getDate();
emailer.send('reset_notify', uid, {
username: username,
date: parsedDate,
subject: '[[email:reset.notify.subject]]',
});
next();
},
], callback);
}; };
SocketUser.isFollowing = function (socket, data, callback) { SocketUser.isFollowing = async function (socket, data) {
if (!socket.uid || !data.uid) { if (!socket.uid || !data.uid) {
return callback(null, false); return false;
} }
user.isFollowing(socket.uid, data.uid, callback); return await user.isFollowing(socket.uid, data.uid);
}; };
SocketUser.follow = function (socket, data, callback) { SocketUser.follow = async function (socket, data) {
if (!socket.uid || !data) { if (!socket.uid || !data) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
}
await toggleFollow('follow', socket.uid, data.uid);
const userData = await user.getUserFields(socket.uid, ['username', 'userslug']);
const notifObj = await notifications.create({
type: 'follow',
bodyShort: '[[notifications:user_started_following_you, ' + userData.username + ']]',
nid: 'follow:' + data.uid + ':uid:' + socket.uid,
from: socket.uid,
path: '/uid/' + data.uid + '/followers',
mergeId: 'notifications:user_started_following_you',
});
if (!notifObj) {
return;
} }
var userData; notifObj.user = userData;
async.waterfall([ await notifications.push(notifObj, [data.uid]);
function (next) {
toggleFollow('follow', socket.uid, data.uid, next);
},
function (next) {
user.getUserFields(socket.uid, ['username', 'userslug'], next);
},
function (_userData, next) {
userData = _userData;
notifications.create({
type: 'follow',
bodyShort: '[[notifications:user_started_following_you, ' + userData.username + ']]',
nid: 'follow:' + data.uid + ':uid:' + socket.uid,
from: socket.uid,
path: '/uid/' + data.uid + '/followers',
mergeId: 'notifications:user_started_following_you',
}, next);
},
function (notification, next) {
if (!notification) {
return next();
}
notification.user = userData;
notifications.push(notification, [data.uid], next);
},
], callback);
}; };
SocketUser.unfollow = function (socket, data, callback) { SocketUser.unfollow = async function (socket, data) {
if (!socket.uid || !data) { if (!socket.uid || !data) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
toggleFollow('unfollow', socket.uid, data.uid, callback); await toggleFollow('unfollow', socket.uid, data.uid);
}; };
function toggleFollow(method, uid, theiruid, callback) { async function toggleFollow(method, uid, theiruid) {
async.waterfall([ await user[method](uid, theiruid);
function (next) { plugins.fireHook('action:user.' + method, {
user[method](uid, theiruid, next); fromUid: uid,
}, toUid: theiruid,
function (next) { });
plugins.fireHook('action:user.' + method, {
fromUid: uid,
toUid: theiruid,
});
next();
},
], callback);
} }
SocketUser.saveSettings = function (socket, data, callback) { SocketUser.saveSettings = async function (socket, data) {
if (!socket.uid || !data || !data.settings) { if (!socket.uid || !data || !data.settings) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
const canEdit = await privileges.users.canEdit(socket.uid, data.uid);
async.waterfall([ if (!canEdit) {
function (next) { throw new Error('[[error:no-privileges]]');
privileges.users.canEdit(socket.uid, data.uid, next); }
}, return await user.saveSettings(data.uid, data.settings);
function (allowed, next) {
if (!allowed) {
return next(new Error('[[error:no-privileges]]'));
}
user.saveSettings(data.uid, data.settings, next);
},
], callback);
}; };
SocketUser.setTopicSort = function (socket, sort, callback) { SocketUser.setTopicSort = async function (socket, sort) {
user.setSetting(socket.uid, 'topicPostSort', sort, callback); await user.setSetting(socket.uid, 'topicPostSort', sort);
}; };
SocketUser.setCategorySort = function (socket, sort, callback) { SocketUser.setCategorySort = async function (socket, sort) {
user.setSetting(socket.uid, 'categoryTopicSort', sort, callback); await user.setSetting(socket.uid, 'categoryTopicSort', sort);
}; };
SocketUser.getUnreadCount = function (socket, data, callback) { SocketUser.getUnreadCount = async function (socket) {
if (!socket.uid) { if (!socket.uid) {
return callback(null, 0); return 0;
} }
topics.getTotalUnread(socket.uid, '', callback); return await topics.getTotalUnread(socket.uid, '');
}; };
SocketUser.getUnreadChatCount = function (socket, data, callback) { SocketUser.getUnreadChatCount = async function (socket) {
if (!socket.uid) { if (!socket.uid) {
return callback(null, 0); return 0;
} }
messaging.getUnreadCount(socket.uid, callback); return await messaging.getUnreadCount(socket.uid);
}; };
SocketUser.getUnreadCounts = function (socket, data, callback) { SocketUser.getUnreadCounts = async function (socket) {
if (!socket.uid) { if (!socket.uid) {
return callback(null, {}); return {};
} }
async.parallel({ const results = await utils.promiseParallel({
unreadCounts: async.apply(topics.getUnreadTids, { uid: socket.uid, count: true }), unreadCounts: topics.getUnreadTids({ uid: socket.uid, count: true }),
unreadChatCount: async.apply(messaging.getUnreadCount, socket.uid), unreadChatCount: messaging.getUnreadCount(socket.uid),
unreadNotificationCount: async.apply(user.notifications.getUnreadCount, socket.uid), unreadNotificationCount: user.notifications.getUnreadCount(socket.uid),
}, function (err, results) {
if (err) {
return callback(err);
}
results.unreadTopicCount = results.unreadCounts[''];
results.unreadNewTopicCount = results.unreadCounts.new;
results.unreadWatchedTopicCount = results.unreadCounts.watched;
results.unreadUnrepliedTopicCount = results.unreadCounts.unreplied;
callback(null, results);
}); });
results.unreadTopicCount = results.unreadCounts[''];
results.unreadNewTopicCount = results.unreadCounts.new;
results.unreadWatchedTopicCount = results.unreadCounts.watched;
results.unreadUnrepliedTopicCount = results.unreadCounts.unreplied;
return results;
}; };
SocketUser.invite = function (socket, email, callback) { SocketUser.invite = async function (socket, email) {
if (!email || !socket.uid) { if (!email || !socket.uid) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
var registrationType = meta.config.registrationType; const registrationType = meta.config.registrationType;
if (registrationType !== 'invite-only' && registrationType !== 'admin-invite-only') { if (registrationType !== 'invite-only' && registrationType !== 'admin-invite-only') {
return callback(new Error('[[error:forum-not-invite-only]]')); throw new Error('[[error:forum-not-invite-only]]');
}
const isAdmin = await user.isAdministrator(socket.uid);
if (registrationType === 'admin-invite-only' && !isAdmin) {
throw new Error('[[error:no-privileges]]');
} }
async.waterfall([ const max = meta.config.maximumInvites;
function (next) { email = email.split(',').map(email => email.trim()).filter(Boolean);
user.isAdministrator(socket.uid, next);
}, await async.eachSeries(email, async function (email) {
function (isAdmin, next) { let invites = 0;
if (registrationType === 'admin-invite-only' && !isAdmin) { if (max) {
return next(new Error('[[error:no-privileges]]')); invites = await user.getInvitesNumber(socket.uid);
} }
var max = meta.config.maximumInvites; if (!isAdmin && max && invites >= max) {
email = email.split(',').map(email => email.trim()).filter(Boolean); throw new Error('[[error:invite-maximum-met, ' + invites + ', ' + max + ']]');
async.eachSeries(email, function (email, next) { }
async.waterfall([
function (next) { await user.sendInvitationEmail(socket.uid, email);
if (max) { });
user.getInvitesNumber(socket.uid, next);
} else {
next(null, 0);
}
},
function (invites, next) {
if (!isAdmin && max && invites >= max) {
return next(new Error('[[error:invite-maximum-met, ' + invites + ', ' + max + ']]'));
}
user.sendInvitationEmail(socket.uid, email, next);
},
], next);
}, next);
},
], callback);
}; };
SocketUser.getUserByUID = function (socket, uid, callback) { SocketUser.getUserByUID = async function (socket, uid) {
userController.getUserDataByField(socket.uid, 'uid', uid, callback); return await userController.getUserDataByField(socket.uid, 'uid', uid);
}; };
SocketUser.getUserByUsername = function (socket, username, callback) { SocketUser.getUserByUsername = async function (socket, username) {
userController.getUserDataByField(socket.uid, 'username', username, callback); return await userController.getUserDataByField(socket.uid, 'username', username);
}; };
SocketUser.getUserByEmail = function (socket, email, callback) { SocketUser.getUserByEmail = async function (socket, email) {
userController.getUserDataByField(socket.uid, 'email', email, callback); return await userController.getUserDataByField(socket.uid, 'email', email);
}; };
SocketUser.setModerationNote = function (socket, data, callback) { SocketUser.setModerationNote = async function (socket, data) {
if (!socket.uid || !data || !data.uid || !data.note) { if (!socket.uid || !data || !data.uid || !data.note) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
const noteData = { const noteData = {
uid: socket.uid, uid: socket.uid,
note: data.note, note: data.note,
timestamp: Date.now(), timestamp: Date.now(),
}; };
async.waterfall([ let canEdit = await privileges.users.canEdit(socket.uid, data.uid);
function (next) { if (!canEdit) {
privileges.users.canEdit(socket.uid, data.uid, next); canEdit = await user.isModeratorOfAnyCategory(socket.uid);
}, }
function (allowed, next) { if (!canEdit) {
if (allowed) { throw new Error('[[error:no-privileges]]');
return setImmediate(next, null, allowed); }
} await db.sortedSetAdd('uid:' + data.uid + ':moderation:notes', noteData.timestamp, noteData.timestamp);
await db.setObject('uid:' + data.uid + ':moderation:note:' + noteData.timestamp, noteData);
user.isModeratorOfAnyCategory(socket.uid, next);
},
function (allowed, next) {
if (!allowed) {
return next(new Error('[[error:no-privileges]]'));
}
db.sortedSetAdd('uid:' + data.uid + ':moderation:notes', noteData.timestamp, noteData.timestamp, next);
},
function (next) {
db.setObject('uid:' + data.uid + ':moderation:note:' + noteData.timestamp, noteData, next);
},
], callback);
}; };
SocketUser.deleteUpload = function (socket, data, callback) { SocketUser.deleteUpload = async function (socket, data) {
if (!data || !data.name || !data.uid) { if (!data || !data.name || !data.uid) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
user.deleteUpload(socket.uid, data.uid, data.name, callback); await user.deleteUpload(socket.uid, data.uid, data.name);
}; };
SocketUser.gdpr = {}; SocketUser.gdpr = {};
SocketUser.gdpr.consent = function (socket, data, callback) { SocketUser.gdpr.consent = async function (socket) {
user.setUserField(socket.uid, 'gdpr_consent', 1, callback); await user.setUserField(socket.uid, 'gdpr_consent', 1);
}; };
SocketUser.gdpr.check = function (socket, data, callback) { SocketUser.gdpr.check = async function (socket, data) {
async.waterfall([ const isAdmin = await user.isAdministrator(socket.uid);
async.apply(user.isAdministrator, socket.uid), if (!isAdmin) {
function (isAdmin, next) { data.uid = socket.uid;
if (!isAdmin) { }
data.uid = socket.uid; return await db.getObjectField('user:' + data.uid, 'gdpr_consent');
}
db.getObjectField('user:' + data.uid, 'gdpr_consent', next);
},
], callback);
}; };
require('../promisify')(SocketUser);

@ -1,149 +1,101 @@
'use strict'; 'use strict';
var async = require('async'); const winston = require('winston');
var winston = require('winston');
var db = require('../../database'); const db = require('../../database');
var user = require('../../user'); const user = require('../../user');
var meta = require('../../meta'); const meta = require('../../meta');
var websockets = require('../index'); const websockets = require('../index');
var events = require('../../events'); const events = require('../../events');
var privileges = require('../../privileges'); const privileges = require('../../privileges');
var plugins = require('../../plugins'); const plugins = require('../../plugins');
var emailer = require('../../emailer'); const emailer = require('../../emailer');
var translator = require('../../translator'); const translator = require('../../translator');
var utils = require('../../../public/src/utils'); const utils = require('../../../public/src/utils');
module.exports = function (SocketUser) { module.exports = function (SocketUser) {
SocketUser.banUsers = function (socket, data, callback) { SocketUser.banUsers = async function (socket, data) {
if (!data || !Array.isArray(data.uids)) { if (!data || !Array.isArray(data.uids)) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
toggleBan(socket.uid, data.uids, function (uid, next) { await toggleBan(socket.uid, data.uids, async function (uid) {
async.waterfall([ await banUser(socket.uid, uid, data.until || 0, data.reason || '');
function (next) { await events.log({
banUser(socket.uid, uid, data.until || 0, data.reason || '', next); type: 'user-ban',
}, uid: socket.uid,
function (next) { targetUid: uid,
events.log({ ip: socket.ip,
type: 'user-ban', reason: data.reason || undefined,
uid: socket.uid, });
targetUid: uid, plugins.fireHook('action:user.banned', {
ip: socket.ip, callerUid: socket.uid,
reason: data.reason || undefined, ip: socket.ip,
}, next); uid: uid,
}, until: data.until > 0 ? data.until : undefined,
function (next) { reason: data.reason || undefined,
plugins.fireHook('action:user.banned', { });
callerUid: socket.uid, await user.auth.revokeAllSessions(uid);
ip: socket.ip, });
uid: uid,
until: data.until > 0 ? data.until : undefined,
reason: data.reason || undefined,
});
next();
},
function (next) {
user.auth.revokeAllSessions(uid, next);
},
], next);
}, callback);
}; };
SocketUser.unbanUsers = function (socket, uids, callback) { SocketUser.unbanUsers = async function (socket, uids) {
toggleBan(socket.uid, uids, function (uid, next) { await toggleBan(socket.uid, uids, async function (uid) {
async.waterfall([ await user.bans.unban(uid);
function (next) { await events.log({
user.bans.unban(uid, next); type: 'user-unban',
}, uid: socket.uid,
function (next) { targetUid: uid,
events.log({ ip: socket.ip,
type: 'user-unban', });
uid: socket.uid, plugins.fireHook('action:user.unbanned', {
targetUid: uid, callerUid: socket.uid,
ip: socket.ip, ip: socket.ip,
}, next); uid: uid,
}, });
function (next) { });
plugins.fireHook('action:user.unbanned', {
callerUid: socket.uid,
ip: socket.ip,
uid: uid,
});
next();
},
], next);
}, callback);
}; };
function toggleBan(uid, uids, method, callback) { async function toggleBan(uid, uids, method) {
if (!Array.isArray(uids)) { if (!Array.isArray(uids)) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
}
const hasBanPrivilege = await privileges.users.hasBanPrivilege(uid);
if (!hasBanPrivilege) {
throw new Error('[[error:no-privileges]]');
} }
async.waterfall([ await Promise.all(uids.map(uid => method(uid)));
function (next) {
privileges.users.hasBanPrivilege(uid, next);
},
function (hasBanPrivilege, next) {
if (!hasBanPrivilege) {
return next(new Error('[[error:no-privileges]]'));
}
async.each(uids, method, next);
},
], callback);
} }
function banUser(callerUid, uid, until, reason, callback) { async function banUser(callerUid, uid, until, reason) {
async.waterfall([ const isAdmin = await user.isAdministrator(uid);
function (next) { if (isAdmin) {
user.isAdministrator(uid, next); throw new Error('[[error:cant-ban-other-admins]]');
}, }
function (isAdmin, next) { const username = await user.getUserField(uid, 'username');
if (isAdmin) { const siteTitle = meta.config.title || 'NodeBB';
return next(new Error('[[error:cant-ban-other-admins]]')); const data = {
} subject: '[[email:banned.subject, ' + siteTitle + ']]',
username: username,
until: until ? utils.toISOString(until) : false,
reason: reason,
};
try {
await emailer.send('banned', uid, data);
} catch (err) {
winston.error('[emailer.send] ' + err.message);
}
const banData = await user.bans.ban(uid, until, reason);
await db.setObjectField('uid:' + uid + ':ban:' + banData.timestamp, 'fromUid', callerUid);
user.getUserField(uid, 'username', next); if (!reason) {
}, reason = await translator.translate('[[user:info.banned-no-reason]]');
function (username, next) { }
var siteTitle = meta.config.title || 'NodeBB';
var data = {
subject: '[[email:banned.subject, ' + siteTitle + ']]',
username: username,
until: until ? utils.toISOString(until) : false,
reason: reason,
};
emailer.send('banned', uid, data, function (err) { websockets.in('uid_' + uid).emit('event:banned', {
if (err) { until: until,
winston.error('[emailer.send] ' + err.message); reason: reason,
} });
next();
});
},
function (next) {
user.bans.ban(uid, until, reason, next);
},
function (banData, next) {
db.setObjectField('uid:' + uid + ':ban:' + banData.timestamp, 'fromUid', callerUid, next);
},
function (next) {
if (reason) {
return next(null, reason);
}
translator.translate('[[user:info.banned-no-reason]]', function (translated) {
next(null, translated);
});
},
function (_reason, next) {
websockets.in('uid_' + uid).emit('event:banned', {
until: until,
reason: _reason,
});
next();
},
], callback);
} }
}; };

@ -1,110 +1,82 @@
'use strict'; 'use strict';
var async = require('async'); const path = require('path');
var path = require('path'); const nconf = require('nconf');
var nconf = require('nconf');
var user = require('../../user'); const user = require('../../user');
var plugins = require('../../plugins'); const plugins = require('../../plugins');
var file = require('../../file'); const file = require('../../file');
module.exports = function (SocketUser) { module.exports = function (SocketUser) {
SocketUser.changePicture = function (socket, data, callback) { SocketUser.changePicture = async function (socket, data) {
if (!socket.uid) { if (!socket.uid) {
return callback(new Error('[[error:invalid-uid]]')); throw new Error('[[error:invalid-uid]]');
} }
if (!data) { if (!data) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
var type = data.type; const type = data.type;
let picture = '';
await user.isAdminOrGlobalModOrSelf(socket.uid, data.uid);
if (type === 'default') {
picture = '';
} else if (type === 'uploaded') {
picture = await user.getUserField(data.uid, 'uploadedpicture');
} else {
const returnData = await plugins.fireHook('filter:user.getPicture', {
uid: socket.uid,
type: type,
picture: undefined,
});
picture = returnData && returnData.picture;
}
async.waterfall([ await user.setUserField(data.uid, 'picture', picture);
function (next) {
user.isAdminOrGlobalModOrSelf(socket.uid, data.uid, next);
},
function (next) {
switch (type) {
case 'default':
next(null, '');
break;
case 'uploaded':
user.getUserField(data.uid, 'uploadedpicture', next);
break;
default:
plugins.fireHook('filter:user.getPicture', {
uid: socket.uid,
type: type,
picture: undefined,
}, function (err, returnData) {
next(err, returnData && returnData.picture);
});
break;
}
},
function (picture, next) {
user.setUserField(data.uid, 'picture', picture, next);
},
], callback);
}; };
SocketUser.removeUploadedPicture = function (socket, data, callback) { SocketUser.removeUploadedPicture = async function (socket, data) {
if (!socket.uid || !data || !data.uid) { if (!socket.uid || !data || !data.uid) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
await user.isAdminOrSelf(socket.uid, data.uid);
async.waterfall([ const userData = await user.getUserFields(data.uid, ['uploadedpicture', 'picture']);
function (next) { if (userData.uploadedpicture && !userData.uploadedpicture.startsWith('http')) {
user.isAdminOrSelf(socket.uid, data.uid, next); const pathToFile = path.join(nconf.get('base_dir'), 'public', userData.uploadedpicture);
}, if (pathToFile.startsWith(nconf.get('upload_path'))) {
function (next) { file.delete(pathToFile);
user.getUserFields(data.uid, ['uploadedpicture', 'picture'], next); }
}, }
function (userData, next) { await user.setUserFields(data.uid, {
if (userData.uploadedpicture && !userData.uploadedpicture.startsWith('http')) { uploadedpicture: '',
var pathToFile = path.join(nconf.get('base_dir'), 'public', userData.uploadedpicture); // if current picture is uploaded picture, reset to user icon
if (pathToFile.startsWith(nconf.get('upload_path'))) { picture: userData.uploadedpicture === userData.picture ? '' : userData.picture,
file.delete(pathToFile); });
} plugins.fireHook('action:user.removeUploadedPicture', { callerUid: socket.uid, uid: data.uid });
}
user.setUserFields(data.uid, {
uploadedpicture: '',
picture: userData.uploadedpicture === userData.picture ? '' : userData.picture, // if current picture is uploaded picture, reset to user icon
}, next);
},
function (next) {
plugins.fireHook('action:user.removeUploadedPicture', { callerUid: socket.uid, uid: data.uid }, next);
},
], callback);
}; };
SocketUser.getProfilePictures = function (socket, data, callback) { SocketUser.getProfilePictures = async function (socket, data) {
if (!data || !data.uid) { if (!data || !data.uid) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
}
const [list, uploaded] = await Promise.all([
plugins.fireHook('filter:user.listPictures', {
uid: data.uid,
pictures: [],
}),
user.getUserField(data.uid, 'uploadedpicture'),
]);
if (uploaded) {
list.pictures.push({
type: 'uploaded',
url: data.uploaded,
text: '[[user:uploaded_picture]]',
});
} }
async.waterfall([
function (next) {
async.parallel({
list: async.apply(plugins.fireHook, 'filter:user.listPictures', {
uid: data.uid,
pictures: [],
}),
uploaded: async.apply(user.getUserField, data.uid, 'uploadedpicture'),
}, next);
},
function (data, next) {
if (data.uploaded) {
data.list.pictures.push({
type: 'uploaded',
url: data.uploaded,
text: '[[user:uploaded_picture]]',
});
}
next(null, data.list.pictures); return list.pictures;
},
], callback);
}; };
}; };

@ -1,229 +1,143 @@
'use strict'; 'use strict';
var async = require('async'); const user = require('../../user');
const meta = require('../../meta');
var user = require('../../user'); const events = require('../../events');
var meta = require('../../meta'); const privileges = require('../../privileges');
var events = require('../../events');
var privileges = require('../../privileges');
module.exports = function (SocketUser) { module.exports = function (SocketUser) {
SocketUser.changeUsernameEmail = function (socket, data, callback) { SocketUser.changeUsernameEmail = async function (socket, data) {
if (!data || !data.uid || !socket.uid) { if (!data || !data.uid || !socket.uid) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
await isPrivilegedOrSelfAndPasswordMatch(socket, data);
async.waterfall([ return await SocketUser.updateProfile(socket, data);
function (next) {
isPrivilegedOrSelfAndPasswordMatch(socket, data, next);
},
function (next) {
SocketUser.updateProfile(socket, data, next);
},
], callback);
}; };
SocketUser.updateCover = function (socket, data, callback) { SocketUser.updateCover = async function (socket, data) {
if (!socket.uid) { if (!socket.uid) {
return callback(new Error('[[error:no-privileges]]')); throw new Error('[[error:no-privileges]]');
} }
async.waterfall([ await user.isAdminOrGlobalModOrSelf(socket.uid, data.uid);
function (next) { await user.checkMinReputation(socket.uid, data.uid, 'min:rep:cover-picture');
user.isAdminOrGlobalModOrSelf(socket.uid, data.uid, next); return await user.updateCoverPicture(data);
},
function (next) {
user.checkMinReputation(socket.uid, data.uid, 'min:rep:cover-picture', next);
},
function (next) {
user.updateCoverPicture(data, next);
},
], callback);
}; };
SocketUser.uploadCroppedPicture = function (socket, data, callback) { SocketUser.uploadCroppedPicture = async function (socket, data) {
if (!socket.uid) { if (!socket.uid) {
return callback(new Error('[[error:no-privileges]]')); throw new Error('[[error:no-privileges]]');
} }
async.waterfall([ await user.isAdminOrGlobalModOrSelf(socket.uid, data.uid);
function (next) { await user.checkMinReputation(socket.uid, data.uid, 'min:rep:profile-picture');
user.isAdminOrGlobalModOrSelf(socket.uid, data.uid, next); return await user.uploadCroppedPicture(data);
},
function (next) {
user.checkMinReputation(socket.uid, data.uid, 'min:rep:profile-picture', next);
},
function (next) {
user.uploadCroppedPicture(data, next);
},
], callback);
}; };
SocketUser.removeCover = function (socket, data, callback) { SocketUser.removeCover = async function (socket, data) {
if (!socket.uid) { if (!socket.uid) {
return callback(new Error('[[error:no-privileges]]')); throw new Error('[[error:no-privileges]]');
} }
await user.isAdminOrGlobalModOrSelf(socket.uid, data.uid);
async.waterfall([ await user.removeCoverPicture(data);
function (next) {
user.isAdminOrGlobalModOrSelf(socket.uid, data.uid, next);
},
function (next) {
user.removeCoverPicture(data, next);
},
], callback);
}; };
function isPrivilegedOrSelfAndPasswordMatch(socket, data, callback) { async function isPrivilegedOrSelfAndPasswordMatch(socket, data) {
const uid = socket.uid; const uid = socket.uid;
const isSelf = parseInt(uid, 10) === parseInt(data.uid, 10); const isSelf = parseInt(uid, 10) === parseInt(data.uid, 10);
async.waterfall([ const [isAdmin, isTargetAdmin, isGlobalMod] = await Promise.all([
function (next) { user.isAdministrator(uid),
async.parallel({ user.isAdministrator(data.uid),
isAdmin: async.apply(user.isAdministrator, uid), user.isGlobalModerator(uid),
isTargetAdmin: async.apply(user.isAdministrator, data.uid), ]);
isGlobalMod: async.apply(user.isGlobalModerator, uid),
}, next); if ((isTargetAdmin && !isAdmin) || (!isSelf && !(isAdmin || isGlobalMod))) {
}, throw new Error('[[error:no-privileges]]');
function (results, next) { }
if (results.isTargetAdmin && !results.isAdmin) { const [hasPassword, passwordMatch] = await Promise.all([
return next(new Error('[[error:no-privileges]]')); user.hasPassword(data.uid),
} data.password ? user.isPasswordCorrect(data.uid, data.password, socket.ip) : false,
]);
if (!isSelf && !(results.isAdmin || results.isGlobalMod)) {
return next(new Error('[[error:no-privileges]]')); if (isSelf && hasPassword && !passwordMatch) {
} throw new Error('[[error:invalid-password]]');
}
async.parallel({
hasPassword: async.apply(user.hasPassword, data.uid),
passwordMatch: function (next) {
if (data.password) {
user.isPasswordCorrect(data.uid, data.password, socket.ip, next);
} else {
next(null, false);
}
},
}, next);
}, function (results, next) {
if (isSelf && results.hasPassword && !results.passwordMatch) {
return next(new Error('[[error:invalid-password]]'));
}
next();
},
], callback);
} }
SocketUser.changePassword = function (socket, data, callback) { SocketUser.changePassword = async function (socket, data) {
if (!socket.uid) { if (!socket.uid) {
return callback(new Error('[[error:invalid-uid]]')); throw new Error('[[error:invalid-uid]]');
} }
if (!data || !data.uid) { if (!data || !data.uid) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
async.waterfall([ await user.changePassword(socket.uid, Object.assign(data, { ip: socket.ip }));
function (next) { await events.log({
user.changePassword(socket.uid, Object.assign(data, { ip: socket.ip }), next); type: 'password-change',
}, uid: socket.uid,
function (next) { targetUid: data.uid,
events.log({ ip: socket.ip,
type: 'password-change', });
uid: socket.uid,
targetUid: data.uid,
ip: socket.ip,
});
next();
},
], callback);
}; };
SocketUser.updateProfile = function (socket, data, callback) { SocketUser.updateProfile = async function (socket, data) {
if (!socket.uid) { if (!socket.uid) {
return callback(new Error('[[error:invalid-uid]]')); throw new Error('[[error:invalid-uid]]');
} }
if (!data || !data.uid) { if (!data || !data.uid) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
var oldUserData; const oldUserData = await user.getUserFields(data.uid, ['email', 'username']);
async.waterfall([ if (!oldUserData || !oldUserData.username) {
function (next) { throw new Error('[[error:invalid-data]]');
user.getUserFields(data.uid, ['email', 'username'], next); }
},
function (_oldUserData, next) { const [isAdminOrGlobalMod, canEdit] = await Promise.all([
oldUserData = _oldUserData; user.isAdminOrGlobalMod(socket.uid),
if (!oldUserData || !oldUserData.username) { privileges.users.canEdit(socket.uid, data.uid),
return next(new Error('[[error:invalid-data]]')); ]);
}
if (!canEdit) {
async.parallel({ throw new Error('[[error:no-privileges]]');
isAdminOrGlobalMod: function (next) { }
user.isAdminOrGlobalMod(socket.uid, next);
}, if (!isAdminOrGlobalMod && meta.config['username:disableEdit']) {
canEdit: function (next) { data.username = oldUserData.username;
privileges.users.canEdit(socket.uid, data.uid, next); }
},
}, next); if (!isAdminOrGlobalMod && meta.config['email:disableEdit']) {
}, data.email = oldUserData.email;
function (results, next) { }
if (!results.canEdit) {
return next(new Error('[[error:no-privileges]]')); const userData = await user.updateProfile(socket.uid, data);
}
async function log(type, eventData) {
if (!results.isAdminOrGlobalMod && meta.config['username:disableEdit']) { eventData.type = type;
data.username = oldUserData.username; eventData.uid = socket.uid;
} eventData.targetUid = data.uid;
eventData.ip = socket.ip;
if (!results.isAdminOrGlobalMod && meta.config['email:disableEdit']) { await events.log(eventData);
data.email = oldUserData.email; }
}
if (userData.email !== oldUserData.email) {
user.updateProfile(socket.uid, data, next); await log('email-change', { oldEmail: oldUserData.email, newEmail: userData.email });
}, }
function (userData, next) {
function log(type, eventData) { if (userData.username !== oldUserData.username) {
eventData.type = type; await log('username-change', { oldUsername: oldUserData.username, newUsername: userData.username });
eventData.uid = socket.uid; }
eventData.targetUid = data.uid; return userData;
eventData.ip = socket.ip;
events.log(eventData);
}
if (userData.email !== oldUserData.email) {
log('email-change', { oldEmail: oldUserData.email, newEmail: userData.email });
}
if (userData.username !== oldUserData.username) {
log('username-change', { oldUsername: oldUserData.username, newUsername: userData.username });
}
next(null, userData);
},
], callback);
}; };
SocketUser.toggleBlock = function (socket, data, callback) { SocketUser.toggleBlock = async function (socket, data) {
let isBlocked; const [is] = await Promise.all([
user.blocks.is(data.blockeeUid, data.blockerUid),
async.waterfall([ user.blocks.can(socket.uid, data.blockerUid, data.blockeeUid),
function (next) { ]);
async.parallel({ const isBlocked = is;
can: function (next) { await user.blocks[isBlocked ? 'remove' : 'add'](data.blockeeUid, data.blockerUid);
user.blocks.can(socket.uid, data.blockerUid, data.blockeeUid, next); return !isBlocked;
},
is: function (next) {
user.blocks.is(data.blockeeUid, data.blockerUid, next);
},
}, next);
},
function (results, next) {
isBlocked = results.is;
user.blocks[isBlocked ? 'remove' : 'add'](data.blockeeUid, data.blockerUid, next);
},
], function (err) {
callback(err, !isBlocked);
});
}; };
}; };

@ -1,70 +1,43 @@
'use strict'; 'use strict';
var async = require('async'); const user = require('../../user');
var user = require('../../user'); const events = require('../../events');
var events = require('../../events');
module.exports = function (SocketUser) { module.exports = function (SocketUser) {
SocketUser.acceptRegistration = function (socket, data, callback) { SocketUser.acceptRegistration = async function (socket, data) {
async.waterfall([ const isAdminOrGlobalMod = await user.isAdminOrGlobalMod(socket.uid);
function (next) { if (!isAdminOrGlobalMod) {
user.isAdminOrGlobalMod(socket.uid, next); throw new Error('[[error:no-privileges]]');
}, }
function (isAdminOrGlobalMod, next) { const uid = await user.acceptRegistration(data.username);
if (!isAdminOrGlobalMod) { await events.log({
return next(new Error('[[error:no-privileges]]')); type: 'registration-approved',
} uid: socket.uid,
ip: socket.ip,
user.acceptRegistration(data.username, next); targetUid: uid,
}, });
function (uid, next) { return uid;
events.log({
type: 'registration-approved',
uid: socket.uid,
ip: socket.ip,
targetUid: uid,
});
next(null, uid);
},
], callback);
}; };
SocketUser.rejectRegistration = function (socket, data, callback) { SocketUser.rejectRegistration = async function (socket, data) {
async.waterfall([ const isAdminOrGlobalMod = await user.isAdminOrGlobalMod(socket.uid);
function (next) { if (!isAdminOrGlobalMod) {
user.isAdminOrGlobalMod(socket.uid, next); throw new Error('[[error:no-privileges]]');
}, }
function (isAdminOrGlobalMod, next) { await user.rejectRegistration(data.username);
if (!isAdminOrGlobalMod) { await events.log({
return next(new Error('[[error:no-privileges]]')); type: 'registration-rejected',
} uid: socket.uid,
ip: socket.ip,
user.rejectRegistration(data.username, next); username: data.username,
}, });
function (next) {
events.log({
type: 'registration-rejected',
uid: socket.uid,
ip: socket.ip,
username: data.username,
});
next();
},
], callback);
}; };
SocketUser.deleteInvitation = function (socket, data, callback) { SocketUser.deleteInvitation = async function (socket, data) {
async.waterfall([ const isAdminOrGlobalMod = await user.isAdminOrGlobalMod(socket.uid);
function (next) { if (!isAdminOrGlobalMod) {
user.isAdminOrGlobalMod(socket.uid, next); throw new Error('[[error:no-privileges]]');
}, }
function (isAdminOrGlobalMod, next) { await user.deleteInvitation(data.invitedBy, data.email);
if (!isAdminOrGlobalMod) {
return next(new Error('[[error:no-privileges]]'));
}
user.deleteInvitation(data.invitedBy, data.email, next);
},
], callback);
}; };
}; };

@ -1,42 +1,31 @@
'use strict'; 'use strict';
var async = require('async'); const user = require('../../user');
const pagination = require('../../pagination');
var user = require('../../user'); const privileges = require('../../privileges');
var pagination = require('../../pagination');
var privileges = require('../../privileges');
module.exports = function (SocketUser) { module.exports = function (SocketUser) {
SocketUser.search = function (socket, data, callback) { SocketUser.search = async function (socket, data) {
if (!data) { if (!data) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
const allowed = await privileges.global.can('search:users', socket.uid);
async.waterfall([ if (!allowed) {
function (next) { throw new Error('[[error:no-privileges]]');
privileges.global.can('search:users', socket.uid, next); }
}, const result = await user.search({
function (allowed, next) { query: data.query,
if (!allowed) { page: data.page,
return next(new Error('[[error:no-privileges]]')); searchBy: data.searchBy,
} sortBy: data.sortBy,
user.search({ onlineOnly: data.onlineOnly,
query: data.query, bannedOnly: data.bannedOnly,
page: data.page, flaggedOnly: data.flaggedOnly,
searchBy: data.searchBy, paginate: data.paginate,
sortBy: data.sortBy, uid: socket.uid,
onlineOnly: data.onlineOnly, });
bannedOnly: data.bannedOnly, result.pagination = pagination.create(data.page, result.pageCount);
flaggedOnly: data.flaggedOnly, result['route_users:' + data.sortBy] = true;
paginate: data.paginate, return result;
uid: socket.uid,
}, next);
},
function (result, next) {
result.pagination = pagination.create(data.page, result.pageCount);
result['route_users:' + data.sortBy] = true;
next(null, result);
},
], callback);
}; };
}; };

@ -1,59 +1,40 @@
'use strict'; 'use strict';
var async = require('async'); const user = require('../../user');
const websockets = require('../index');
var user = require('../../user');
var websockets = require('../index');
module.exports = function (SocketUser) { module.exports = function (SocketUser) {
SocketUser.checkStatus = function (socket, uid, callback) { SocketUser.checkStatus = async function (socket, uid) {
if (!socket.uid) { if (!socket.uid) {
return callback(new Error('[[error:invalid-uid]]')); throw new Error('[[error:invalid-uid]]');
} }
async.waterfall([ const userData = await user.getUserFields(uid, ['lastonline', 'status']);
function (next) { return user.getStatus(userData);
user.getUserFields(uid, ['lastonline', 'status'], next);
},
function (userData, next) {
next(null, user.getStatus(userData));
},
], callback);
}; };
SocketUser.setStatus = function (socket, status, callback) { SocketUser.setStatus = async function (socket, status) {
if (socket.uid <= 0) { if (socket.uid <= 0) {
return callback(new Error('[[error:invalid-uid]]')); throw new Error('[[error:invalid-uid]]');
} }
var allowedStatus = ['online', 'offline', 'dnd', 'away']; const allowedStatus = ['online', 'offline', 'dnd', 'away'];
if (!allowedStatus.includes(status)) { if (!allowedStatus.includes(status)) {
return callback(new Error('[[error:invalid-user-status]]')); throw new Error('[[error:invalid-user-status]]');
} }
var data = { status: status }; const userData = { status: status };
if (status !== 'offline') { if (status !== 'offline') {
data.lastonline = Date.now(); userData.lastonline = Date.now();
} }
await user.setUserFields(socket.uid, userData);
async.waterfall([ if (status !== 'offline') {
function (next) { await user.updateOnlineUsers(socket.uid);
user.setUserFields(socket.uid, data, next); }
}, const eventData = {
function (next) { uid: socket.uid,
if (status !== 'offline') { status: status,
user.updateOnlineUsers(socket.uid, next); };
} else { websockets.server.emit('event:user_status_change', eventData);
next(); return eventData;
}
},
function (next) {
var data = {
uid: socket.uid,
status: status,
};
websockets.server.emit('event:user_status_change', data);
next(null, data);
},
], callback);
}; };
}; };

@ -39,7 +39,7 @@ module.exports = function (User) {
throw new Error('[[error:cannot-block-privileged]]'); throw new Error('[[error:cannot-block-privileged]]');
} }
if (parseInt(callerUid, 10) !== parseInt(blockerUid, 10) && !isCallerAdminOrMod) { if (parseInt(callerUid, 10) !== parseInt(blockerUid, 10) && !isCallerAdminOrMod) {
throw new Error(); throw new Error('[[error:no-privileges]]');
} }
}; };

@ -221,7 +221,7 @@ UserNotifications.sendNameChangeNotification = async function (uid, username) {
}; };
UserNotifications.pushCount = async function (uid) { UserNotifications.pushCount = async function (uid) {
var websockets = require('./../socket.io'); const websockets = require('./../socket.io');
const count = await UserNotifications.getUnreadCount(uid); const count = await UserNotifications.getUnreadCount(uid);
websockets.in('uid_' + uid).emit('event:notifications.updateCount', count); websockets.in('uid_' + uid).emit('event:notifications.updateCount', count);
}; };

@ -1,13 +1,13 @@
'use strict'; 'use strict';
var async = require('async'); const async = require('async');
var utils = require('../utils'); const utils = require('../utils');
var meta = require('../meta'); const meta = require('../meta');
var db = require('../database'); const db = require('../database');
var groups = require('../groups'); const groups = require('../groups');
var plugins = require('../plugins'); const plugins = require('../plugins');
module.exports = function (User) { module.exports = function (User) {
User.updateProfile = async function (uid, data) { User.updateProfile = async function (uid, data) {
@ -136,7 +136,7 @@ module.exports = function (User) {
} }
User.checkMinReputation = async function (callerUid, uid, setting) { User.checkMinReputation = async function (callerUid, uid, setting) {
var isSelf = parseInt(callerUid, 10) === parseInt(uid, 10); const isSelf = parseInt(callerUid, 10) === parseInt(uid, 10);
if (!isSelf || meta.config['reputation:disabled']) { if (!isSelf || meta.config['reputation:disabled']) {
return; return;
} }

@ -77,7 +77,7 @@ module.exports = function (User) {
} }
User.saveSettings = async function (uid, data) { User.saveSettings = async function (uid, data) {
var maxPostsPerPage = meta.config.maxPostsPerPage || 20; const maxPostsPerPage = meta.config.maxPostsPerPage || 20;
if (!data.postsPerPage || parseInt(data.postsPerPage, 10) <= 1 || parseInt(data.postsPerPage, 10) > maxPostsPerPage) { if (!data.postsPerPage || parseInt(data.postsPerPage, 10) <= 1 || parseInt(data.postsPerPage, 10) > maxPostsPerPage) {
throw new Error('[[error:invalid-pagination-value, 2, ' + maxPostsPerPage + ']]'); throw new Error('[[error:invalid-pagination-value, 2, ' + maxPostsPerPage + ']]');
} }

@ -1,12 +1,12 @@
'use strict'; 'use strict';
var path = require('path'); const path = require('path');
var nconf = require('nconf'); const nconf = require('nconf');
var winston = require('winston'); const winston = require('winston');
var db = require('../database'); const db = require('../database');
var file = require('../file'); const file = require('../file');
var batch = require('../batch'); const batch = require('../batch');
module.exports = function (User) { module.exports = function (User) {
User.deleteUpload = async function (callerUid, uid, uploadName) { User.deleteUpload = async function (callerUid, uid, uploadName) {

Loading…
Cancel
Save