使用node.js,nano和CouchDB进行身份验证

时间:2011-10-05 12:27:58

标签: node.js authentication couchdb couchdb-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函数来调整值吗?

2 个答案:

答案 0 :(得分:3)

我现在无法测试它,但是,查看来源,你可以注意到两件事:

然后我认为您需要将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);
});

答案 1 :(得分:1)

身份验证可以作为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);
}