wildduck/lib/handlers/on-auth.js

102 lines
3.8 KiB
JavaScript
Raw Normal View History

'use strict';
const config = require('wild-config');
2017-12-08 20:29:00 +08:00
module.exports = (server, userHandler, userCache) => (login, session, callback) => {
let username = (login.username || '').toString().trim();
userHandler.authenticate(
username,
login.password,
2017-07-24 21:44:08 +08:00
'imap',
{
protocol: 'IMAP',
2017-10-30 19:41:53 +08:00
sess: session.id,
ip: session.remoteAddress
},
(err, result) => {
if (err) {
return callback(err);
}
2019-07-12 15:21:48 +08:00
if (!result) {
return callback();
}
2017-07-24 21:44:08 +08:00
if (result.scope === 'master' && result.require2fa) {
// master password not allowed if 2fa is enabled!
return callback();
}
let checkConnectionLimits = next => {
if (typeof server.notifier.allocateConnection === 'function') {
2017-12-08 20:29:00 +08:00
return userCache.get(result.user, 'imapMaxConnections', config.imap.maxConnections || 15, (err, limit) => {
if (err) {
return callback(err);
}
2018-10-31 16:04:32 +08:00
let connection = login.connection || {};
server.notifier.allocateConnection(
{
service: 'imap',
session,
user: result.user,
limit
},
2018-10-31 16:04:32 +08:00
(err, success) => {
2018-10-31 16:06:24 +08:00
if (!err) {
if (success) {
server.loggelf({
short_message: '[CONNSTART] Connection established for ' + result.user,
_connection: 'establish',
_service: 'imap',
2020-03-24 21:39:04 +08:00
_sess: session && session.id,
2018-10-31 16:06:24 +08:00
_user: result.user,
_cid: connection.id,
_ip: connection.remoteAddress,
_limit: limit
});
} else {
server.loggelf({
short_message: '[CONNFAILED] Connection failed for ' + result.user,
_connection: 'limited',
_service: 'imap',
2020-03-24 21:39:04 +08:00
_sess: session && session.id,
2018-10-31 16:06:24 +08:00
_user: result.user,
_cid: connection.id,
_ip: connection.remoteAddress,
_limit: limit
});
}
2018-10-31 16:04:32 +08:00
}
next(err, success);
}
);
});
}
return next(null, true);
};
checkConnectionLimits((err, success) => {
if (err) {
return callback(err);
}
if (!success) {
err = new Error('[ALERT] Too many simultaneous connections.');
err.response = 'NO';
return callback(err);
}
callback(null, {
user: {
id: result.user,
username: result.username
}
});
});
}
);
};