1
votes

I have a couchDB database called "guestbook". I first used the code below to add the a user to the "_users" database:

$scope.submit = function(){

var url = "https://sub.iriscouch.com/_users/org.couchdb.user:" + $scope.name;
console.log(url);

$http({

    url: url,
    method: "PUT",
    data: {name : $scope.name, 
           password: $scope.pass,
           roles: [],
           type: "user"
          },
    withCredentials: true,
    headers: {"Authorization": auth_hash(adminUsername, adminPass)}
})

.success(function(data, status, headers, config){

    console.log(headers);
    console.log(config);
 });
 }

Once the user was added to _users I used Futon to add that user as member to my "guestbook" _security document.

After that I tried to used that username and password (that was added as a member to "guestbook" _security) to get all the documents in the "guestbook" database. See code below:

   $scope.login = function(){
   var url = "https://sub.iriscouch.com/guestbook/_all_docs";

   $http({
    url: url,
    method: 'GET',
    params: {
        include_docs: true,

    },
    withCredentials: true,
    headers: {"Authorization": auth_hash($scope.uname, $scope.upass)}
})

.success(function(data, status, headers, config){

    $scope.book = data.rows;
    console.log($scope.book);

});
}

function auth_hash(username, password)
{
     return "Basic" +btoa(username + ":" + password);
}

But everytime I tired access the "_all_docs" I get a 401 unauthorised error. The username I am using to access has been added as a member into the _security documents of the guestbook database.

Can anyone help. What am I doing wrong.

2

2 Answers

0
votes

Do you have added the user name w/o the org.couchdb.user prefix to the _security object?

I can easily understand your code but didn't see a obviously mistake. I would recommend you test your API calls with Postman (Chrome App) or similar to know whether the problem is client- or server-side caused.

0
votes

401 indicates Couch is unable to log in your user rather than it's not allowing them access to the database.

Might be a copy/paste error in writing the code example, but it looks like your line:

return "Basic" +btoa(username + ":" + password);

Is missing a space between Basic and your hash in the returned string:

return "Basic " +btoa(username + ":" + password);

This will mean that your Authorization header isn't correct.

However, your first code block appears to use the same function successfully, so I'm clutching at straws.