enigma-bbs/core/user_login.js

108 lines
3.8 KiB
JavaScript
Raw Normal View History

/* jslint node: true */
'use strict';
// ENiGMA½
const setClientTheme = require('./theme.js').setClientTheme;
const clientConnections = require('./client_connections.js').clientConnections;
const StatLog = require('./stat_log.js');
const logger = require('./logger.js');
const Events = require('./events.js');
const Config = require('./config.js').get;
const {
Errors,
ErrorReasons
} = require('./enig_error.js');
// deps
const async = require('async');
exports.userLogin = userLogin;
function userLogin(client, username, password, cb) {
client.user.authenticate(username, password, function authenticated(err) {
if(err) {
client.log.info( { username : username, error : err.message }, 'Failed login attempt');
// :TODO: if username exists, record failed login attempt to properties
// :TODO: check Config max failed logon attempts/etc. - set err.maxAttempts = true
return cb(err);
}
const user = client.user;
//
// Ensure this user is not already logged in.
//
2018-11-22 02:50:03 +00:00
const existingClientConnection = clientConnections.find(cc => {
return user !== cc.user && // not current connection
user.userId === cc.user.userId; // ...but same user
});
if(existingClientConnection) {
client.log.info(
{
existingClientId : existingClientConnection.session.id,
username : user.username,
userId : user.userId
},
'Already logged in'
);
return cb(Errors.BadLogin(
`User ${user.username} already logged in.`,
ErrorReasons.AlreadyLoggedIn
));
}
// update client logger with addition of username
client.log = logger.log.child(
{
clientId : client.log.fields.clientId,
sessionId : client.log.fields.sessionId,
username : user.username,
}
);
client.log.info('Successful login');
// User's unique session identifier is the same as the connection itself
user.sessionId = client.session.uniqueId; // convienence
Events.emit(Events.getSystemEvents().UserLogin, { user } );
2018-06-03 23:59:16 +00:00
async.parallel(
[
function setTheme(callback) {
setClientTheme(client, user.properties.theme_id);
return callback(null);
},
function updateSystemLoginCount(callback) {
return StatLog.incrementSystemStat('login_count', 1, callback);
},
function recordLastLogin(callback) {
return StatLog.setUserStat(user, 'last_login_timestamp', StatLog.now, callback);
},
function updateUserLoginCount(callback) {
return StatLog.incrementUserStat(user, 'login_count', 1, callback);
},
function recordLoginHistory(callback) {
const loginHistoryMax = Config().statLog.systemEvents.loginHistoryMax;
const historyItem = JSON.stringify({
userId : user.userId,
sessionId : user.sessionId,
});
2018-11-11 08:58:49 +00:00
return StatLog.appendSystemLogEntry(
'user_login_history',
historyItem,
loginHistoryMax,
StatLog.KeepType.Max,
callback
);
}
],
err => {
return cb(err);
}
);
});
}