1

我正在尝试实现可以​​使用 openldap 登录的功能。为此,我正在使用 ldapjs 客户端 API - http://ldapjs.org/

以下是我的登录步骤

  1. 从 Web 表单 (ejs) 获取用户名和密码
  2. 使用 ldapjs 的搜索 API 查找用户:http: //ldapjs.org/client.html#search
  3. 如果找到用户,则使用绑定 API 进行身份验证: http: //ldapjs.org/client.html#bind

这工作正常,但如果在第 2 步搜索失败,即如果找不到用户,我还需要添加异常

如何在我知道搜索是否失败并且在 ldap 中不存在的地方添加异常?

下面是我的登录控制器功能

    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);

            });
        
    });
}
4

0 回答 0