Authentication with node.js, nano and CouchDB -
is there way change config parameters in nano after initialization? i'd init nano with:
nano = require('nano')('http://127.0.0.1:5984')
and later change user , password, after user submits login form. error:
nano.cfg.user = params.user.name typeerror: cannot set property 'user' of undefined
or should fork nano , write auth function adjust values?
i can't test right now, but, looking @ sources, can note 2 things:
- that configuration is exposed
config
, notcfg
; - that config option connection
url
.
then think need set url configuration option new value authentication parameters:
nano.config.url = 'http://' + params.user.name + ':' + params.user.password + '@localhost:5984';
or can keep configuration object in couch.example.js , like:
cfg.user = params.user.name; cfg.pass = params.user.password; nano.config.url = cfg.url;
update: here's complete example:
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 authentication..."); setuserpass('usename', 'password'); db.get(docid, function (e, r, h) { if (e) { console.log("sorry, did not work:"); return console.error(e); } console.log("it worked:"); console.log(r); console.log(h); }); return; } console.log("hmmm, went wrong:"); return console.error(e); } console.log("no auth required:"); console.log(r); console.log(h); });
Comments
Post a Comment