Pat*_*ick 5 authentication couchdb node.js couchdb-nano
有没有办法在初始化后更改nano中的配置参数?我想初始纳米:
nano = require('nano')('http://127.0.0.1:5984')
Run Code Online (Sandbox Code Playgroud)
用户提交登录表单后,更改用户和密码.我总是收到一个错误:
nano.cfg.user = params.user.name
TypeError: Cannot set property 'user' of undefined
Run Code Online (Sandbox Code Playgroud)
或者我应该fork nano并编写auth函数来调整值?
我现在无法测试它,但是,查看来源,您可以注意到两件事:
然后我认为您需要使用身份验证参数将 url 配置选项设置为新值:
nano.config.url = 'http://' + params.user.name + ':' + params.user.password + '@localhost:5984';
Run Code Online (Sandbox Code Playgroud)
或者你可以像在couch.example.js一样保留一个配置对象并执行以下操作:
cfg.user = params.user.name;
cfg.pass = params.user.password;
nano.config.url = cfg.url;
Run Code Online (Sandbox Code Playgroud)
更新:这是一个完整的例子:
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);
});
Run Code Online (Sandbox Code Playgroud)
身份验证可以作为 http 标头的一部分发送:
if(cfg.user && cfg.pass) {
req.headers['Authorization'] = "Basic " + new Buffer(cfg.user+":"+cfg.pass).toString('base64');
}
Run Code Online (Sandbox Code Playgroud)
可以使用“auth”功能设置用户名和密码:
function auth_db(user, password, callback) {
cfg.user = user;
cfg.pass = password;
return relax({db: "_session", method: "GET"}, callback);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4805 次 |
| 最近记录: |