0

我想编写一个函数,在检查与服务器的绑定是否正确之后添加 ldap 服务器的参数,否则数据将不会添加到 db 中;我必须使用羽毛 js。在将参数添加到数据库之前,我尝试写几行来验证参数: const ldap=require("ldapjs"); 但问题是,当我在 ldap.bind 函数内部和外部执行 console.log(errors) 时:我注意到结果仅在函数内部可见,而对其余代码不可见!我需要它对其他部分也可见,以便我可以使用它,我想知道如何解决这个问题。

这是代码以及 console.log 的结果。

module.exports = (ldapConnexion, mode = "create") => {

  const errors = {
    url_path: [],
    browsingAccount: [],
    password: [],
    userSearchBase:[],


  };

  const client=ldap.createClient({url:ldapConnexion.url_path})
 client.bind(ldapConnexion.browsingAccount,ldapConnexion.password,function(err){
    if (err){errors.browsingAccount.push("unvalid credentials:"+err);console.log(err)}})

console.log(errors)

const hasErrors = Object.keys(errors).reduce(
  (res, errorType) =>
    res || (errors[errorType] && errors[errorType].length > 0),
  false
);
return { errors, hasErrors };


    }
4

1 回答 1

0

为此,我们可以通过这种方式实现代码:如果这可以使其他文件中的某人感兴趣,请执行以下操作:

  const ldap = require('ldapjs');

module.exports = (ldapConnexion, mode = "create",cb) => {


  const errors = {
    url_path: [],
    browsingAccount: [],
    password: [],
    userSearchBase: [],


  };
  var opts ={
         
    rejectUnauthorized: false, // To force the client not to check self-signed certificates
}

//create the ldap client with the list of informations mentionned in the form   
var client = ldap.createClient({
    url:ldapConnexion.url_path, tlsOptions:opts
});
  client.bind(ldapConnexion.browsingAccount, ldapConnexion.password, function (err) {
    if (err) {
      errors.browsingAccount.push("unvalid credentials:" + err.message);
      //console.log(errors);
      cb(errors,true);
      client.unbind(function(err){if(err){console.log(err)}});

    } client.unbind(function(err){if(err){console.log(err)}});
  })

 // console.log(errors)


  if (!ldapConnexion.url_path) {
    errors.url_path.push("Url obligatoire");

  }
  if (!ldapConnexion.browsingAccount) {
    errors.browsingAccount.push("le compte lecteur est obligatoire");

  }
  if (!ldapConnexion.password) {
    errors.password.push("le mot de passe est obligatoire");

  }



  const hasErrors = Object.keys(errors).reduce(
    (res, errorType) =>
      res || (errors[errorType] && errors[errorType].length > 0),
    false
  );
  cb(errors, hasErrors)
}

在钩子里:

  const validateConnexionHook = function (mode = "create") {
  return context => {
    return new Promise((resolve, reject) => {
      const ldapConnexion = context.data || {};

      validateConnexion(ldapConnexion, mode, (errors, hasErrors) => {
        console.log('**************')
        // console.log(errors);
        console.log(hasErrors);
        if (hasErrors) {
          context.error = errors;
          reject(errors)
        }
        else setTimeout(function () { resolve(); }, 3000);
      })

    })
  }
}
于 2020-06-29T11:55:23.507 回答