1

I am trying to implement functionality where I can login with openldap. for that I am using ldapjs client API - http://ldapjs.org/

Below are my steps for login

  1. Get username and password from web form (ejs)
  2. find user using search API of ldapjs: http://ldapjs.org/client.html#search
  3. if user found then use bind API to authenticate: http://ldapjs.org/client.html#bind

This is working fine, but I also need to add exception if search fails at step 2, i.e. if user is not found

How can I add exception where I will know if search fails and user it not there in ldap?

Below is my controller function for login

    exports.postLogin = (req, postResponse, next) => {

    const username = 'cn=' + req.body.username + ',' + process.env.DN;
    const password = req.body.password;

    const opts = {
        filter: '(cn=' + req.body.username + ')',
        scope: 'sub'
    };

    ldapClient.search(process.env.DN, opts, (err, res) => {
       assert.ifError(err);

      

            res.on('searchEntry', (entry) => {
                //once user is found, then authenticate
                ldapClient.bind(
                    username,
                    password,
                    (err, response) => {
                        if (err) {

                            req.flash('error', 'Cannot authenticate: ', err.lde_message);
                            return postResponse.redirect('/user/login');
                        }
                        else {

                            req.session.user = req.body.username;
                           
                            postResponse.redirect('/dashboard');

                        }
                    });
            });
         
            res.on('error', (err) => {
                console.error('error: ' + err.message);
            });

        
            res.on('end', (result) => {
                console.log('status: ' + result.status);

            });
        
    });
}
Prasad Gavande
  • 213
  • 1
  • 4
  • 19

0 Answers0