【问题标题】:Authentication with node.js, nano and CouchDB使用 node.js、nano 和 CouchDB 进行身份验证
【发布时间】:2019-05-23 14:21:47
【问题描述】:

有没有办法在初始化后更改 nano 中的配置参数?我想用以下方法初始化 nano:

nano = require('nano')('http://127.0.0.1:5984')

然后在用户提交登录表单后更改用户和密码。我总是得到一个错误:

nano.cfg.user = params.user.name
TypeError: Cannot set property 'user' of undefined

或者我应该 fork nano 并编写一个 auth 函数来调整值?

【问题讨论】:

    标签: node.js authentication couchdb couchdb-nano


    【解决方案1】:

    我现在无法测试它,但是,查看源代码,您可以注意到两点:

    那我认为你需要将url配置选项设置为一个带有认证参数的新值:

    nano.config.url = 'http://' + params.user.name + ':' + params.user.password + '@localhost:5984';
    

    或者您可以像couch.example.js 一样保留一个配置对象,然后执行以下操作:

    cfg.user = params.user.name;
    cfg.pass = params.user.password;
    nano.config.url = cfg.url;
    

    更新:这是一个完整的例子:

    var cfg = {
      host: "localhost",
      port: "5984",
      ssl: false
    };
    
    cfg.credentials = function credentials() {
      if (cfg.user && cfg.pass) {
        return cfg.user + ":" + cfg.pass + "@";
      }
      else { return ""; }
    };
    
    cfg.url = function () {
      return "http" + (cfg.ssl ? "s" : "") + "://" + cfg.credentials() + cfg.host +
        ":" + cfg.port;
    };
    
    var nano = require('nano')(cfg.url()),
      db = nano.use('DB_WITH_AUTH'),
      docId = 'DOCUMENT_ID';
    
    function setUserPass(user, pass) {
      cfg.user = user;
      cfg.pass = pass;
      nano.config.url = cfg.url();
    }
    
    db.get(docId, function (e, r, h) {
      if (e) {
        if (e['status-code'] === 401) {
          console.log("Trying again with authentication...");
          setUserPass('USENAME', 'PASSWORD');
          db.get(docId, function (e, r, h) {
            if (e) {
              console.log("Sorry, it did not work:");
              return console.error(e);
            }
            console.log("It worked:");
            console.log(r);
            console.log(h);
          });
          return;
        }
        console.log("Hmmm, something went wrong:");
        return console.error(e);
      }
      console.log("No auth required:");
      console.log(r);
      console.log(h);
    });
    

    【讨论】:

    • 不幸的是,还有从 url 生成的路径。我尝试了几种可能性,最终将身份验证放在了标题中。
    • @Patrick 我不确定你的意思是什么,所以我添加了一个工作示例来解释我的意思。我希望它有助于澄清。
    • 非常感谢,我一开始就试过了。但是,我找到了一些 http-authentication 的来源,这比重写整个 cfg 代码更容易。我请求拉入节点存储库,所以我希望更新很快就会出现。
    【解决方案2】:

    身份验证可以作为 http 标头的一部分发送:

    if(cfg.user && cfg.pass) {
      req.headers['Authorization'] = "Basic " + new Buffer(cfg.user+":"+cfg.pass).toString('base64');
    }
    

    用户名和密码可以用'auth'函数设置:

    function auth_db(user, password, callback) {
      cfg.user = user;
      cfg.pass = password;
      return relax({db: "_session", method: "GET"}, callback);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-14
      • 1970-01-01
      • 1970-01-01
      • 2017-11-19
      • 2016-10-21
      • 2023-04-05
      • 1970-01-01
      • 2010-12-27
      相关资源
      最近更新 更多