I am trying to use the ldap js library in my node project "ldapjs": "^1.0.2". I have succesfully made the connection with the ldap server and getting the results back. But due to some reason, I am getting timeout error when I am trying to call my service from UI for the ldap. It works fine if I try to use my back end service directly in chrome (as it is a get service) but when I try from my ui code, the ldap service goes down. I get time out error in the console.
My back end is in Node and fron end code is in Vue. I am using axios to call my backend service.
ldap Code :
function getUserLdapDetails(id) {
return new Promise(async function (resolve, reject) {
var client;
try {
var response = {};
setTimeout(function () {
resolve('Not able to get Ldap details');
}, 5000);
var tlsOption = {
'rejectUnauthorized': true
}
client = ldap.createClient({
url: server,
tlsOptions: tlsOption
});
client.bind(userPrincipalName, password, (err, res) => {
console.log("In Ldap Bind and connection is establised :" + client.connected);
if (err) {
console.log(err);
return reject(err);
}
});
var opts = {
filter: "id=" + id,
scope: "sub",
attributes: [
"mail",
"sn",
"telephoneNumber",
"givenName"
]
};
client.search(searchOption, opts, function (err, res) {
if (err) {
console.log(err);
resolve(response);
}
res.on("searchEntry", function (entry, end) {
response.mail = entry.object.mail;
response.lastName = entry.object.sn;
response.firstNme = entry.object.givenName;
response.phone = entry.object.telephoneNumber;
resolve(response);
});
});
} catch (err) {
console.log(err);
return reject(err);
} finally {
client.unbind(function (err) {
if (err) {
console.log(err);
return reject(err);
}
});
}
}).catch((err) => {
console.log(err);
return err;
});
}
Finally, I have figured out the solution. Sometimes the client is idling out and also in some cases we are getting exceptions from the LDAP server for the search due to different reasons.
I found out a lot of event listeners we can add to listen for these events. Below are a few, unfortunately, they are not documented.
Below are the changes I did to handle
client = ldap.createClient({
url: server,
tlsOptions: tlsOption,
timeLimit: 7000,
reconnect: true
});
await client.on('connect', function () {
client.bind(userPrincipalName, password, (err, res) => {
console.log("In Ldap Bind and connection is establised :" + client.connected);
if (err) {
console.log(err);
return reject(err);
}
});
client.on('timeout', function (err) {
console.log('Timeout .....' + err);
});
client.on('error', function (err) {
console.warn('LDAP connection failed, it will reconnect', err);
});