refactor: async/await controllers/authentication

v1.18.x
Barış Soner Uşaklı 5 years ago
parent b99279a83c
commit b9105ef9c6

@ -21,59 +21,42 @@ const sockets = require('../socket.io');
const authenticationController = module.exports; const authenticationController = module.exports;
function registerAndLoginUser(req, res, userData, callback) { async function registerAndLoginUser(req, res, userData) {
var uid; const data = await plugins.fireHook('filter:register.interstitial', {
async.waterfall([ userData: userData,
function (next) { interstitials: [],
plugins.fireHook('filter:register.interstitial', { });
userData: userData,
interstitials: [],
}, next);
},
function (data, next) {
// If interstitials are found, save registration attempt into session and abort
var deferRegistration = data.interstitials.length;
if (!deferRegistration) {
return next();
}
userData.register = true;
req.session.registration = userData;
if (req.body.noscript === 'true') { // If interstitials are found, save registration attempt into session and abort
return res.redirect(nconf.get('relative_path') + '/register/complete'); const deferRegistration = data.interstitials.length;
}
return res.json({ referrer: nconf.get('relative_path') + '/register/complete' }); if (deferRegistration) {
}, userData.register = true;
function (next) { req.session.registration = userData;
user.shouldQueueUser(req.ip, next);
}, if (req.body.noscript === 'true') {
function (queue, next) { res.redirect(nconf.get('relative_path') + '/register/complete');
plugins.fireHook('filter:register.shouldQueue', { req: req, res: res, userData: userData, queue: queue }, next); return;
}, }
function (data, next) { res.json({ referrer: nconf.get('relative_path') + '/register/complete' });
if (data.queue) { return;
addToApprovalQueue(req, userData, callback); }
} else { const queue = await user.shouldQueueUser(req.ip);
user.create(userData, next); const result = await plugins.fireHook('filter:register.shouldQueue', { req: req, res: res, userData: userData, queue: queue });
} if (result.queue) {
}, return await addToApprovalQueue(req, userData);
function (_uid, next) { }
uid = _uid;
if (res.locals.processLogin) { const uid = await user.create(userData);
authenticationController.doLogin(req, uid, next); if (res.locals.processLogin) {
} else { await authenticationController.doLogin(req, uid);
next(); }
}
}, user.deleteInvitationKey(userData.email);
function (next) { return await plugins.fireHook('filter:register.complete', { uid: uid, referrer: req.body.referrer || nconf.get('relative_path') + '/' });
user.deleteInvitationKey(userData.email);
plugins.fireHook('filter:register.complete', { uid: uid, referrer: req.body.referrer || nconf.get('relative_path') + '/' }, next);
},
], callback);
} }
const registerAndLoginUserAsync = util.promisify(registerAndLoginUser); const registerAndLoginUserCallback = util.callbackify(registerAndLoginUser);
authenticationController.register = async function (req, res) { authenticationController.register = async function (req, res) {
@ -83,7 +66,7 @@ authenticationController.register = async function (req, res) {
return res.sendStatus(403); return res.sendStatus(403);
} }
var userData = req.body; const userData = req.body;
try { try {
if (registrationType === 'invite-only' || registrationType === 'admin-invite-only') { if (registrationType === 'invite-only' || registrationType === 'admin-invite-only') {
await user.verifyInvitation(userData); await user.verifyInvitation(userData);
@ -110,28 +93,22 @@ authenticationController.register = async function (req, res) {
res.locals.processLogin = true; // set it to false in plugin if you wish to just register only res.locals.processLogin = true; // set it to false in plugin if you wish to just register only
await plugins.fireHook('filter:register.check', { req: req, res: res, userData: userData }); await plugins.fireHook('filter:register.check', { req: req, res: res, userData: userData });
const data = await registerAndLoginUserAsync(req, res, userData); const data = await registerAndLoginUser(req, res, userData);
if (data) {
if (data.uid && req.body.userLang) { if (data.uid && req.body.userLang) {
user.setSetting(data.uid, 'userLang', req.body.userLang); await user.setSetting(data.uid, 'userLang', req.body.userLang);
}
res.json(data);
} }
res.json(data);
} catch (err) { } catch (err) {
helpers.noScriptErrors(req, res, err.message, 400); helpers.noScriptErrors(req, res, err.message, 400);
} }
}; };
function addToApprovalQueue(req, userData, callback) { async function addToApprovalQueue(req, userData) {
async.waterfall([ userData.ip = req.ip;
function (next) { await user.addToApprovalQueue(userData);
userData.ip = req.ip; return { message: '[[register:registration-added-to-queue]]' };
user.addToApprovalQueue(userData, next);
},
function (next) {
next(null, { message: '[[register:registration-added-to-queue]]' });
},
], callback);
} }
authenticationController.registerComplete = function (req, res, next) { authenticationController.registerComplete = function (req, res, next) {
@ -188,7 +165,7 @@ authenticationController.registerComplete = function (req, res, next) {
if (req.session.registration.register === true) { if (req.session.registration.register === true) {
res.locals.processLogin = true; res.locals.processLogin = true;
registerAndLoginUser(req, res, req.session.registration, done); registerAndLoginUserCallback(req, res, req.session.registration, done);
} else { } else {
// Update user hash, clear registration data in session // Update user hash, clear registration data in session
const payload = req.session.registration; const payload = req.session.registration;
@ -202,7 +179,7 @@ authenticationController.registerComplete = function (req, res, next) {
} }
}); });
await user.async.setUserFields(uid, payload); await user.setUserFields(uid, payload);
done(); done();
} }
}); });
@ -320,108 +297,65 @@ function continueLogin(req, res, next) {
})(req, res, next); })(req, res, next);
} }
authenticationController.doLogin = function (req, uid, callback) { authenticationController.doLogin = async function (req, uid) {
if (!uid) { if (!uid) {
return callback(); return;
} }
async.waterfall([ const loginAsync = util.promisify(req.login).bind(req);
function (next) { await loginAsync({ uid: uid });
req.login({ uid: uid }, next); await authenticationController.onSuccessfulLogin(req, uid);
},
function (next) {
authenticationController.onSuccessfulLogin(req, uid, next);
},
], callback);
}; };
authenticationController.onSuccessfulLogin = function (req, uid, callback) { authenticationController.onSuccessfulLogin = async function (req, uid) {
// If already called once, return prematurely // If already called once, return prematurely
if (req.res.locals.user) { if (req.res.locals.user) {
if (typeof callback === 'function') {
return setImmediate(callback);
}
return true; return true;
} }
var uuid = utils.generateUUID(); try {
const uuid = utils.generateUUID();
req.uid = uid;
req.loggedIn = true; req.uid = uid;
req.loggedIn = true;
async.waterfall([ await meta.blacklist.test(req.ip);
function (next) { await user.logIP(uid, req.ip);
meta.blacklist.test(req.ip, next);
}, req.session.meta = {};
function (next) {
user.logIP(uid, req.ip, next); delete req.session.forceLogin;
}, // Associate IP used during login with user account
function (next) { req.session.meta.ip = req.ip;
req.session.meta = {};
// Associate metadata retrieved via user-agent
delete req.session.forceLogin; req.session.meta = _.extend(req.session.meta, {
// Associate IP used during login with user account uuid: uuid,
req.session.meta.ip = req.ip; datetime: Date.now(),
platform: req.useragent.platform,
// Associate metadata retrieved via user-agent browser: req.useragent.browser,
req.session.meta = _.extend(req.session.meta, { version: req.useragent.version,
uuid: uuid, });
datetime: Date.now(), await Promise.all([
platform: req.useragent.platform, user.auth.addSession(uid, req.sessionID),
browser: req.useragent.browser, (uid > 0) ? db.setObjectField('uid:' + uid + ':sessionUUID:sessionId', uuid, req.sessionID) : null,
version: req.useragent.version, user.updateLastOnlineTime(uid),
}); user.updateOnlineUsers(uid),
]);
async.parallel([ // Force session check for all connected socket.io clients with the same session id
function (next) { sockets.in('sess_' + req.sessionID).emit('checkSession', uid);
user.auth.addSession(uid, req.sessionID, next);
},
function (next) {
if (uid > 0) {
db.setObjectField('uid:' + uid + ':sessionUUID:sessionId', uuid, req.sessionID, next);
} else {
next();
}
},
function (next) {
user.updateLastOnlineTime(uid, next);
},
function (next) {
user.updateOnlineUsers(uid, next);
},
], function (err) {
next(err);
});
},
function (next) {
// Force session check for all connected socket.io clients with the same session id
sockets.in('sess_' + req.sessionID).emit('checkSession', uid);
plugins.fireHook('action:user.loggedIn', { uid: uid, req: req });
next();
},
], function (err) {
if (err) {
req.session.destroy();
}
if (typeof callback === 'function') { plugins.fireHook('action:user.loggedIn', { uid: uid, req: req });
callback(err); } catch (err) {
} else { req.session.destroy();
return !!err; throw err;
} }
});
}; };
authenticationController.localLogin = function (req, username, password, next) { authenticationController.localLogin = async function (req, username, password, next) {
if (!username) { if (!username) {
return next(new Error('[[error:invalid-username]]')); return next(new Error('[[error:invalid-username]]'));
} }
var userslug = utils.slugify(username);
var uid;
var userData = {};
if (!password || !utils.isPasswordValid(password)) { if (!password || !utils.isPasswordValid(password)) {
return next(new Error('[[error:invalid-password]]')); return next(new Error('[[error:invalid-password]]'));
} }
@ -430,132 +364,99 @@ authenticationController.localLogin = function (req, username, password, next) {
return next(new Error('[[error:password-too-long]]')); return next(new Error('[[error:password-too-long]]'));
} }
async.waterfall([ const userslug = utils.slugify(username);
function (next) { const uid = await user.getUidByUserslug(userslug);
user.getUidByUserslug(userslug, next); try {
}, const [userData, isAdminOrGlobalMod, banned, hasLoginPrivilege] = await Promise.all([
function (_uid, next) { db.getObjectFields('user:' + uid, ['uid', 'passwordExpiry']),
uid = _uid; user.isAdminOrGlobalMod(uid),
user.bans.isBanned(uid),
async.parallel({ privileges.global.can('local:login', uid),
userData: async.apply(db.getObjectFields, 'user:' + uid, ['passwordExpiry']), ]);
isAdminOrGlobalMod: function (next) {
user.isAdminOrGlobalMod(uid, next);
},
banned: function (next) {
user.bans.isBanned(uid, next);
},
hasLoginPrivilege: function (next) {
privileges.global.can('local:login', uid, next);
},
}, next);
},
function (result, next) {
userData = Object.assign(result.userData, {
uid: uid,
isAdminOrGlobalMod: result.isAdminOrGlobalMod,
});
if (parseInt(uid, 10) && !result.hasLoginPrivilege) { userData.isAdminOrGlobalMod = isAdminOrGlobalMod;
return next(new Error('[[error:local-login-disabled]]'));
}
if (result.banned) { if (parseInt(uid, 10) && !hasLoginPrivilege) {
return getBanInfo(uid, next); return next(new Error('[[error:local-login-disabled]]'));
} }
user.isPasswordCorrect(uid, password, req.ip, next); if (banned) {
}, const banMesage = await getBanInfo(uid);
function (passwordMatch, next) { return next(new Error(banMesage));
if (!passwordMatch) { }
return next(new Error('[[error:invalid-login-credentials]]'));
}
next(null, userData, '[[success:authentication-successful]]'); const passwordMatch = await user.isPasswordCorrect(uid, password, req.ip);
}, if (!passwordMatch) {
], next); return next(new Error('[[error:invalid-login-credentials]]'));
}
next(null, userData, '[[success:authentication-successful]]');
} catch (err) {
next(err);
}
}; };
authenticationController.logout = function (req, res, next) { const regenerateAsync = util.promisify((req, callback) => req.session.regenerate(callback));
authenticationController.logout = async function (req, res, next) {
if (!req.loggedIn || !req.sessionID) { if (!req.loggedIn || !req.sessionID) {
return res.status(200).send('not-logged-in'); return res.status(200).send('not-logged-in');
} }
const uid = req.uid; const uid = req.uid;
const sessionID = req.sessionID; const sessionID = req.sessionID;
async.waterfall([
function (next) {
user.auth.revokeSession(sessionID, uid, next);
},
function (next) {
req.logout();
req.session.regenerate(function (err) {
req.uid = 0;
req.headers['x-csrf-token'] = req.csrfToken();
next(err);
});
},
function (next) {
user.setUserField(uid, 'lastonline', Date.now() - (meta.config.onlineCutoff * 60000), next);
},
function (next) {
db.sortedSetAdd('users:online', Date.now() - (meta.config.onlineCutoff * 60000), uid, next);
},
function (next) {
plugins.fireHook('static:user.loggedOut', { req: req, res: res, uid: uid, sessionID: sessionID }, next);
},
async.apply(middleware.autoLocale, req, res),
function () {
// Force session check for all connected socket.io clients with the same session id
sockets.in('sess_' + sessionID).emit('checkSession', 0);
if (req.body.noscript === 'true') {
res.redirect(nconf.get('relative_path') + '/');
} else {
async.series({
buildHeader: async.apply(middleware.buildHeader, req, res),
header: async.apply(middleware.generateHeader, req, res, {}),
}, function (err, payload) {
if (err) {
return res.status(500);
}
payload = { try {
header: payload.header, await user.auth.revokeSession(sessionID, uid);
config: res.locals.config, req.logout();
};
plugins.fireHook('filter:user.logout', payload); await regenerateAsync(req);
res.status(200).send(payload); req.uid = 0;
}); req.headers['x-csrf-token'] = req.csrfToken();
}
}, await user.setUserField(uid, 'lastonline', Date.now() - (meta.config.onlineCutoff * 60000));
], next); await db.sortedSetAdd('users:online', Date.now() - (meta.config.onlineCutoff * 60000), uid);
await plugins.fireHook('static:user.loggedOut', { req: req, res: res, uid: uid, sessionID: sessionID });
const autoLocaleAsync = util.promisify(middleware.autoLocale);
await autoLocaleAsync(req, res);
// Force session check for all connected socket.io clients with the same session id
sockets.in('sess_' + sessionID).emit('checkSession', 0);
if (req.body.noscript === 'true') {
return res.redirect(nconf.get('relative_path') + '/');
}
const buildHeaderAsync = util.promisify(middleware.buildHeader);
const generateHeaderAsync = util.promisify(middleware.generateHeader);
await buildHeaderAsync(req, res);
const header = await generateHeaderAsync(req, res, {});
const payload = {
header: header,
config: res.locals.config,
};
plugins.fireHook('filter:user.logout', payload);
res.status(200).send(payload);
} catch (err) {
next(err);
}
}; };
function getBanInfo(uid, callback) { async function getBanInfo(uid) {
var banInfo; try {
async.waterfall([ const banInfo = await user.getLatestBanInfo(uid);
function (next) {
user.getLatestBanInfo(uid, next);
},
function (_banInfo, next) {
banInfo = _banInfo;
if (banInfo.reason) {
return next();
}
translator.translate('[[user:info.banned-no-reason]]', function (translated) { if (!banInfo.reason) {
banInfo.reason = translated; banInfo.reason = await translator.translate('[[user:info.banned-no-reason]]');
next();
});
},
function (next) {
next(new Error(banInfo.banned_until ? '[[error:user-banned-reason-until, ' + banInfo.banned_until_readable + ', ' + banInfo.reason + ']]' : '[[error:user-banned-reason, ' + banInfo.reason + ']]'));
},
], function (err) {
if (err) {
if (err.message === 'no-ban-info') {
err.message = '[[error:user-banned]]';
}
} }
callback(err); return banInfo.banned_until ?
}); '[[error:user-banned-reason-until, ' + banInfo.banned_until_readable + ', ' + banInfo.reason + ']]' :
'[[error:user-banned-reason, ' + banInfo.reason + ']]';
} catch (err) {
if (err.message === 'no-ban-info') {
return '[[error:user-banned]]';
}
throw err;
}
} }
require('../promisify')(authenticationController, ['register', 'registerComplete', 'registerAbort', 'login', 'localLogin', 'logout']);

@ -1,22 +1,22 @@
'use strict'; 'use strict';
var async = require('async'); const async = require('async');
var validator = require('validator'); const validator = require('validator');
var db = require('../database'); const db = require('../database');
var meta = require('../meta'); const meta = require('../meta');
var emailer = require('../emailer'); const emailer = require('../emailer');
var notifications = require('../notifications'); const notifications = require('../notifications');
var groups = require('../groups'); const groups = require('../groups');
var utils = require('../utils'); const utils = require('../utils');
var plugins = require('../plugins'); const plugins = require('../plugins');
module.exports = function (User) { module.exports = function (User) {
User.addToApprovalQueue = async function (userData) { User.addToApprovalQueue = async function (userData) {
userData.userslug = utils.slugify(userData.username); userData.userslug = utils.slugify(userData.username);
await canQueue(userData); await canQueue(userData);
const hashedPassword = await User.hashPassword(userData.password); const hashedPassword = await User.hashPassword(userData.password);
var data = { const data = {
username: userData.username, username: userData.username,
email: userData.email, email: userData.email,
ip: userData.ip, ip: userData.ip,

Loading…
Cancel
Save