PouchDB sync authorization?-open source projects pouchdb/pouchdb

twilson63

There is a PouchDB plugin built by Nolan Lawson that provides PouchDb with an authentication API:

var db = new PouchDB('http://mysite:5984/mydb');
db.login('batman', 'brucewayne').then(function (batman) {
  console.log("I'm Batman.");
  return db.logout();
});

Here are the methods it mixes in:

  • signup
  • login
  • logout
  • getSession
  • getUser

To prevent browser HTTP basic authentication modal dialogs of ye olde times, we have to be subtle in the way we use PouchDB. To prevent a rouge unauthenticated request to CouchDB (used to check whether the remote DB exists), pass skipSetup: true in Pouch’s constructor options. Secondly, to authenticate the request against _session, add the HTTP basic authorization header to db.login()’s AJAX options.

var user = {
  name: 'admin',
  password: 'admin'
};

var pouchOpts = {
  skipSetup: true
};

var ajaxOpts = {
  ajax: {
    headers: {
      Authorization: 'Basic ' + window.btoa(user.name + ':' + user.password)
    }
  }
};

var db = new PouchDB('http://localhost:5984/test', pouchOpts);

db.login(user.name, user.password, ajaxOpts).then(function() {
  return db.allDocs();
}).then(function(docs) {
  console.log(docs);
}).catch(function(error) {
  console.error(error);
});