laas-admin-api
Version:
LaaS admin api server.
66 lines (60 loc) • 1.89 kB
JavaScript
(function () {
var config = require('../config');
var basic = require('basic-auth');
var LDAP = require('ldapauth-fork');
var AsyncCache = require('async-cache');
var cache = new AsyncCache({
max: 1000,
maxAge: 1000 * 60 * 60 * 24,
load: function (key, cb) {
var creds = key.split(':');
ldapAuth(creds[0], creds[1], cb);
}
});
var ldapConfig = {
url: config.ldap.protocol + '://' + config.ldap.host + ':' + config.ldap.port,
searchBase: config.ldap.base,
searchFilter: '(uid={{username}})'
};
if (config.ldap.binddn) {
ldapConfig.adminDn = config.ldap.binddn;
ldapConfig.adminPassword = config.ldap.bindpass;
}
var ldap = new LDAP(ldapConfig);
module.exports = function () {
return function (req, res, next) {
basicAuth(req, function (err, user) {
if (! err && ! user) err = error('Unauthorized', 401);
if (err) return res.status(err.code || 500).send(err.message);
next ();
});
};
};
function basicAuth (req, cb) {
var creds = basic(req);
if (! creds) return cb(error('Unauthorized', 401));
try {
cache.get(creds.name + ':' + creds.pass, cb);
} catch (err) {
cb(err);
}
}
function error (message, code) {
var err = new Error(message);
err.code = code;
return err;
}
function ldapAuth (username, password, cb) {
var start = Date.now();
ldap.authenticate(username, password, function (err, user) {
console.log({ duration: Date.now()-start }, 'LDAP request');
if (err && err.name === 'InvalidCredentialsError') {
console.log('Authentication was unsuccessful using ldap for user "%s"', username);
err = null;
} else if (! err && user) {
console.log('Authentication was successful using ldap for user "%s"', username);
}
cb(err, user);
});
}
})();