node.jscouchdbcouchdb-nano

How can I automatically assign a role to a CouchDB user?


I have the following method for registering users:

// Registration method
exports.register = function(req, res) {
    var username = req.body.username,
        password = req.body.password,
        first = req.body.first;
        last = req.body.last;
        role = req.body.institution;

    nano = require('nano')('http://127.0.0.1:5984');
    var users = nano.use('_users');

    var user = {
                    "_id": "org.couchdb.user:" + username,
                    "name": username,
                    "type": "user",
                    "roles": [],
                    "password": password,
                    "realname": first + " " + last
                };

    users.insert(user, function(err, body) {
        if(err) {
            res.send(err.reason, err.status_code);
        } else {
            res.send(body, 200);
        }
    });
};

As you can see, I have a variable called role which I would like to set in the "roles" array. Unfortunately, as you probably know, CouchDB only allows the admin to set roles. I'm okay with this, but I'm using the roles as institutions, so I'd like a registering user to be able to pick what institution they're registering under and therefore it should automatically be assigning them this role. Without hard-coding my admin credentials into this method, i.e. nano.config.url = "http://admin:password@127.0.0.1:5984/" How can I automatically assign a new user to their specified role as I've mentioned?


Solution

  • The roles array is used by CouchDB to decide database authorization. This allows you to configure access to a given database by a user's role. If the user can set their own role then somebody can give themselves access to any institution. They can even make themselves an admin, which defeats the purpose of protecting your admin password.

    I'm not sure what your use-case is, but I don't think you are trying to prevent access to other institutions. Rather, I suspect you are trying to use the roles to perform some other application function (e.g. filtering out information for them to simplify what they see). Since you are wanting to perform a non-security function, I strongly suggest that you just add your own field to the users documents. You could add an institutions property to each user.


    If you really want to do this, there is a way. The error you are receiving is coming from an update validation function in _design/_auth in the _users database. As an admin you can change this function.

    Download the document. Open the file and search for Only _admin may edit roles to see where the test is being performed. Remove that conditional and save the document back to CouchDB.