Use ldapjs with bluebird promise

1.8k views Asked by At

I posted something similar here: Use ldapjs with promise. Unfortunately, it is still unsolved.

This time I tried bluebird and hopefully I can get some luck.

// https://www.npmjs.com/package/ldapjs
var Promise = require('bluebird');
var ldap = Promise.promisifyAll( require('ldapjs') );
var config  = require('./config');
var print_r = require('print_r').print_r;


var my_filter = "(&(objectCategory=person)(objectClass=user)" + "(cn=" + 'someone' + "))";
var ldap_username = config.ad.username;
var ldap_password = config.ad.password;
var ldap_url = config.ad.url;
var ldap_dn_search = config.ad.dn_search;

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
ldap.Attribute.settings.guid_format = ldap.GUID_FORMAT_B;


var opts = {
  filter: my_filter,
  scope: 'sub',
};


//test
console.log(my_filter);
console.log(ldap_username);
console.log(ldap_password);
console.log(ldap_url);
console.log(ldap_dn_search);


/* NOTE: This code is working!!!
client.bind(ldap_username, ldap_password, function (err) {
  client.search(ldap_dn_search, opts, function (err, search) {
    search.on('searchEntry', function (entry) {
      var user = entry.object;
      console.log(user);
    });
  });  
});
*/

// I tried to rewrite the code above with promise
ldap.createClientAsync({
  url: ldap_url
})
.then(function(client){
  console.log('bind'); // No print
  return client.bindAsync(ldap_username, ldap_password);
})
.then(function() {
  console.log('search'); // No print
  return client.searchAsync(ldap_dn_search, opts);
})
.then(function(search) {
    // No flow here
  search.on('searchEntry', function (entry) {
    var user = entry.object;
    console.log(user);
  });
})

The script doesn't output anything. It is waiting for something in terminal.

1

There are 1 answers

0
Michael Oryl On

Using Bluebird Promises, the easy way to do this is to create your client normally, and then run the promisifyAll() on the client.

var ldap = require('ldapjs');
var Promise = require('bluebird');

var client = ldap.createClient({
  url: 'ldap://my-server:1234',
});

Promise.promisifyAll(client);

Now you can call client.addAsync() and client.searchAsync() and such.

client.bindAsync(secUserDn, secUserPassword)
  .then(doSearch) // if it works, call doSearch
  .catch(function (err) { // if bind fails, handle it
    console.error('Error on bind', err)
  });

function doSearch(data) {
  client.searchAsync('CN=A Test,OU=Users,DC=website,DC=com', options)
    .then(function (data) { // Handle the search result processing
      console.log('I got a result');
    })  
    .catch(function (err) { // Catch potential errors and handle them
      console.error('Error on search', err);
    });
}