PouchDB sync authorization?
Asked Answered
S

2

9

How do I ensure that the current user has authorization to access a CouchDB database via PouchDB? From my experimentation, calling the new PouchDB() method with the CouchDB database name grants you access to that data.

Setting require_valid_user to true in Futon seems to work, but the Futon modal window still pops up after authenticating the user via POST /_session. I want to have a standard login screen (username and password) that logs the user into my application and grants access to the correct CouchDB database (via PouchDB). I can I do this? Any help will be greatly appreciated.

Srini answered 27/10, 2014 at 22:39 Comment(1)
You may want to check out this plugin github.com/nolanlawson/pouchdb-authenticationSpiderwort
S
9

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 = {
  skip_setup: 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);
});
Spiderwort answered 13/1, 2015 at 3:27 Comment(1)
the skipSetup property has been changed to skip_setupRubyeruch
F
0

i use pouchdb-authentication for sync

 npm i pouchdb-authentication

plugin import

var PouchDB = require("pouchdb");
PouchDB.plugin(require('pouchdb-authentication'));

code:

var localDb = new PouchDB('mydatabase');
var remoteDb = new PouchDB('http://localhost:5984/mydatabase', {skip_setup: true});

remoteDb.login(username, password).then(function () {
  localDb.sync(remoteDb, {live: true, retry: true, /* other sync options */});
});
Fauve answered 30/7, 2020 at 9:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.