refactor: async/await socket.io

This commit is contained in:
Barış Soner Uşaklı
2019-09-15 02:14:51 -04:00
parent 9d41955bca
commit a7d2b8a1fe
17 changed files with 916 additions and 1446 deletions

View File

@@ -1,20 +1,24 @@
'use strict';
var async = require('async');
const async = require('async');
var user = require('../user');
var topics = require('../topics');
var notifications = require('../notifications');
var messaging = require('../messaging');
var plugins = require('../plugins');
var meta = require('../meta');
var events = require('../events');
var emailer = require('../emailer');
var db = require('../database');
var userController = require('../controllers/user');
var privileges = require('../privileges');
const util = require('util');
const sleep = util.promisify(setTimeout);
var SocketUser = module.exports;
const user = require('../user');
const topics = require('../topics');
const notifications = require('../notifications');
const messaging = require('../messaging');
const plugins = require('../plugins');
const meta = require('../meta');
const events = require('../events');
const emailer = require('../emailer');
const db = require('../database');
const userController = require('../controllers/user');
const privileges = require('../privileges');
const utils = require('../utils');
const SocketUser = module.exports;
require('./user/profile')(SocketUser);
require('./user/search')(SocketUser);
@@ -23,375 +27,296 @@ require('./user/picture')(SocketUser);
require('./user/ban')(SocketUser);
require('./user/registration')(SocketUser);
SocketUser.exists = function (socket, data, callback) {
SocketUser.exists = async function (socket, data) {
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) {
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([
function (next) {
user.hasPassword(socket.uid, next);
},
function (hasPassword, next) {
if (!hasPassword) {
return next();
}
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);
await events.log({
type: 'user-delete',
uid: socket.uid,
targetUid: socket.uid,
ip: socket.ip,
username: userData.username,
email: userData.email,
});
};
SocketUser.emailExists = function (socket, data, callback) {
SocketUser.emailExists = async function (socket, data) {
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) {
return callback(new Error('[[error:no-privileges]]'));
throw new Error('[[error:no-privileges]]');
}
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
SocketUser.reset = {};
SocketUser.reset.send = function (socket, email, callback) {
SocketUser.reset.send = async function (socket, email) {
if (!email) {
return callback(new Error('[[error:invalid-data]]'));
throw new Error('[[error:invalid-data]]');
}
if (meta.config['password:disableEdit']) {
return callback(new Error('[[error:no-privileges]]'));
throw new Error('[[error:no-privileges]]');
}
user.reset.send(email, function (err) {
events.log({
async function logEvent(text) {
await events.log({
type: 'password-reset',
text: err ? err.message : '[[success:success]]',
text: text,
ip: socket.ip,
uid: socket.uid,
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]]'];
if (err && internalErrors.includes(err.message)) {
err = null;
if (!internalErrors.includes(err.message)) {
throw err;
}
}
};
setTimeout(callback.bind(err), 2500);
SocketUser.reset.commit = async function (socket, data) {
if (!data || !data.code || !data.password) {
throw new Error('[[error:invalid-data]]');
}
const [uid] = await Promise.all([
db.getObjectField('reset:uid', data.code),
user.reset.commit(data.code, data.password),
plugins.fireHook('action:password.reset', { uid: socket.uid }),
]);
await events.log({
type: 'password-reset',
uid: uid,
ip: socket.ip,
});
const username = await user.getUserField(uid, 'username');
const now = new Date();
const parsedDate = now.getFullYear() + '/' + (now.getMonth() + 1) + '/' + now.getDate();
emailer.send('reset_notify', uid, {
username: username,
date: parsedDate,
subject: '[[email:reset.notify.subject]]',
});
};
SocketUser.reset.commit = function (socket, data, callback) {
if (!data || !data.code || !data.password) {
return callback(new Error('[[error:invalid-data]]'));
}
var uid;
async.waterfall([
function (next) {
async.parallel({
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 }),
}, next);
},
function (results, next) {
uid = results.uid;
events.log({
type: 'password-reset',
uid: uid,
ip: socket.ip,
});
user.getUserField(uid, 'username', next);
},
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) {
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) {
return callback(new Error('[[error:invalid-data]]'));
throw new Error('[[error:invalid-data]]');
}
var userData;
async.waterfall([
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);
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;
}
notifObj.user = userData;
await notifications.push(notifObj, [data.uid]);
};
SocketUser.unfollow = function (socket, data, callback) {
SocketUser.unfollow = async function (socket, 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.waterfall([
function (next) {
user[method](uid, theiruid, next);
},
function (next) {
plugins.fireHook('action:user.' + method, {
fromUid: uid,
toUid: theiruid,
});
next();
},
], callback);
async function toggleFollow(method, uid, theiruid) {
await user[method](uid, theiruid);
plugins.fireHook('action:user.' + method, {
fromUid: uid,
toUid: theiruid,
});
}
SocketUser.saveSettings = function (socket, data, callback) {
SocketUser.saveSettings = async function (socket, data) {
if (!socket.uid || !data || !data.settings) {
return callback(new Error('[[error:invalid-data]]'));
throw new Error('[[error:invalid-data]]');
}
async.waterfall([
function (next) {
privileges.users.canEdit(socket.uid, data.uid, next);
},
function (allowed, next) {
if (!allowed) {
return next(new Error('[[error:no-privileges]]'));
}
user.saveSettings(data.uid, data.settings, next);
},
], callback);
const canEdit = await privileges.users.canEdit(socket.uid, data.uid);
if (!canEdit) {
throw new Error('[[error:no-privileges]]');
}
return await user.saveSettings(data.uid, data.settings);
};
SocketUser.setTopicSort = function (socket, sort, callback) {
user.setSetting(socket.uid, 'topicPostSort', sort, callback);
SocketUser.setTopicSort = async function (socket, sort) {
await user.setSetting(socket.uid, 'topicPostSort', sort);
};
SocketUser.setCategorySort = function (socket, sort, callback) {
user.setSetting(socket.uid, 'categoryTopicSort', sort, callback);
SocketUser.setCategorySort = async function (socket, sort) {
await user.setSetting(socket.uid, 'categoryTopicSort', sort);
};
SocketUser.getUnreadCount = function (socket, data, callback) {
SocketUser.getUnreadCount = async function (socket) {
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) {
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) {
return callback(null, {});
return {};
}
async.parallel({
unreadCounts: async.apply(topics.getUnreadTids, { uid: socket.uid, count: true }),
unreadChatCount: async.apply(messaging.getUnreadCount, socket.uid),
unreadNotificationCount: async.apply(user.notifications.getUnreadCount, socket.uid),
}, function (err, results) {
if (err) {
return callback(err);
const results = await utils.promiseParallel({
unreadCounts: topics.getUnreadTids({ uid: socket.uid, count: true }),
unreadChatCount: messaging.getUnreadCount(socket.uid),
unreadNotificationCount: user.notifications.getUnreadCount(socket.uid),
});
results.unreadTopicCount = results.unreadCounts[''];
results.unreadNewTopicCount = results.unreadCounts.new;
results.unreadWatchedTopicCount = results.unreadCounts.watched;
results.unreadUnrepliedTopicCount = results.unreadCounts.unreplied;
return results;
};
SocketUser.invite = async function (socket, email) {
if (!email || !socket.uid) {
throw new Error('[[error:invalid-data]]');
}
const registrationType = meta.config.registrationType;
if (registrationType !== 'invite-only' && registrationType !== 'admin-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]]');
}
const max = meta.config.maximumInvites;
email = email.split(',').map(email => email.trim()).filter(Boolean);
await async.eachSeries(email, async function (email) {
let invites = 0;
if (max) {
invites = await user.getInvitesNumber(socket.uid);
}
results.unreadTopicCount = results.unreadCounts[''];
results.unreadNewTopicCount = results.unreadCounts.new;
results.unreadWatchedTopicCount = results.unreadCounts.watched;
results.unreadUnrepliedTopicCount = results.unreadCounts.unreplied;
callback(null, results);
if (!isAdmin && max && invites >= max) {
throw new Error('[[error:invite-maximum-met, ' + invites + ', ' + max + ']]');
}
await user.sendInvitationEmail(socket.uid, email);
});
};
SocketUser.invite = function (socket, email, callback) {
if (!email || !socket.uid) {
return callback(new Error('[[error:invalid-data]]'));
}
var registrationType = meta.config.registrationType;
if (registrationType !== 'invite-only' && registrationType !== 'admin-invite-only') {
return callback(new Error('[[error:forum-not-invite-only]]'));
}
async.waterfall([
function (next) {
user.isAdministrator(socket.uid, next);
},
function (isAdmin, next) {
if (registrationType === 'admin-invite-only' && !isAdmin) {
return next(new Error('[[error:no-privileges]]'));
}
var max = meta.config.maximumInvites;
email = email.split(',').map(email => email.trim()).filter(Boolean);
async.eachSeries(email, function (email, next) {
async.waterfall([
function (next) {
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 = async function (socket, uid) {
return await userController.getUserDataByField(socket.uid, 'uid', uid);
};
SocketUser.getUserByUID = function (socket, uid, callback) {
userController.getUserDataByField(socket.uid, 'uid', uid, callback);
SocketUser.getUserByUsername = async function (socket, username) {
return await userController.getUserDataByField(socket.uid, 'username', username);
};
SocketUser.getUserByUsername = function (socket, username, callback) {
userController.getUserDataByField(socket.uid, 'username', username, callback);
SocketUser.getUserByEmail = async function (socket, email) {
return await userController.getUserDataByField(socket.uid, 'email', email);
};
SocketUser.getUserByEmail = function (socket, email, callback) {
userController.getUserDataByField(socket.uid, 'email', email, callback);
};
SocketUser.setModerationNote = function (socket, data, callback) {
SocketUser.setModerationNote = async function (socket, data) {
if (!socket.uid || !data || !data.uid || !data.note) {
return callback(new Error('[[error:invalid-data]]'));
throw new Error('[[error:invalid-data]]');
}
const noteData = {
uid: socket.uid,
note: data.note,
timestamp: Date.now(),
};
async.waterfall([
function (next) {
privileges.users.canEdit(socket.uid, data.uid, next);
},
function (allowed, next) {
if (allowed) {
return setImmediate(next, null, allowed);
}
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);
let canEdit = await privileges.users.canEdit(socket.uid, data.uid);
if (!canEdit) {
canEdit = await user.isModeratorOfAnyCategory(socket.uid);
}
if (!canEdit) {
throw new Error('[[error:no-privileges]]');
}
await db.sortedSetAdd('uid:' + data.uid + ':moderation:notes', noteData.timestamp, noteData.timestamp);
await db.setObject('uid:' + data.uid + ':moderation:note:' + noteData.timestamp, noteData);
};
SocketUser.deleteUpload = function (socket, data, callback) {
SocketUser.deleteUpload = async function (socket, data) {
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.consent = function (socket, data, callback) {
user.setUserField(socket.uid, 'gdpr_consent', 1, callback);
SocketUser.gdpr.consent = async function (socket) {
await user.setUserField(socket.uid, 'gdpr_consent', 1);
};
SocketUser.gdpr.check = function (socket, data, callback) {
async.waterfall([
async.apply(user.isAdministrator, socket.uid),
function (isAdmin, next) {
if (!isAdmin) {
data.uid = socket.uid;
}
db.getObjectField('user:' + data.uid, 'gdpr_consent', next);
},
], callback);
SocketUser.gdpr.check = async function (socket, data) {
const isAdmin = await user.isAdministrator(socket.uid);
if (!isAdmin) {
data.uid = socket.uid;
}
return await db.getObjectField('user:' + data.uid, 'gdpr_consent');
};
require('../promisify')(SocketUser);