31

For instance, if I have this user:

> db.system.users.find()
{ "user" : "testAdmin", "pwd" : "[some hash]", "roles" : [ "clusterAdmin" ], "otherDBRoles" : { "TestDB" : [ "readWrite" ]  } }

And I want to give that user the dbAdmin permissions on the TestDB database, I can remove the user record then add it back with the new permissions:

> db.system.users.remove({"user":"testAdmin"})
> db.addUser( { user: "testAdmin",
                  pwd: "[whatever]",
                  roles: [ "clusterAdmin" ],
                  otherDBRoles: { TestDB: [ "readWrite", "dbAdmin" ] } } )

But that seems hacky and error-prone.

And I can update the table record itself:

> db.system.users.update({"user":"testAdmin"}, {$set:{ otherDBRoles: { TestDB: [ "readWrite", "dbAdmin" ] }}})

But I'm not sure if that really creates the correct permissions - it looks fine but it may be subtly wrong.

Is there a better way to do this?

Ed Norris
  • 4,233
  • 5
  • 27
  • 29

2 Answers2

22

If you want to just update Role of User. You can do in the following way

db.updateUser( "userName",
               {

                 roles : [
                           { role : "dbAdmin", db : "dbName"  },
                           { role : "readWrite", db : "dbName"  }
                         ]
                }
             )

Note:- This will override only roles for that user.

Vaibhav
  • 2,073
  • 4
  • 23
  • 26
  • updateUser is not a function and only {"user" : "userName"} is accepted, string is not enough – benek Feb 06 '17 at 16:30
7

See array update operators.

> db.users.findOne()
{
    "_id" : ObjectId("51e3e2e16a847147f7ccdf7d"),
    "user" : "testAdmin",
    "pwd" : "[some hash]",
    "roles" : [
        "clusterAdmin"
    ],
    "otherDBRoles" : {
        "TestDB" : [
            "readWrite"
        ]
    }
}
> db.users.update({"user" : "testAdmin"}, {$addToSet: {'otherDBRoles.TestDB': 'dbAdmin'}}, false, false)
> db.users.findOne()
{
    "_id" : ObjectId("51e3e2e16a847147f7ccdf7d"),
    "user" : "testAdmin"
    "pwd" : "[some hash]",
    "roles" : [
        "clusterAdmin"
    ],
    "otherDBRoles" : {
        "TestDB" : [
            "readWrite",
            "dbAdmin"
        ]
    },
}

Update:

MongoDB checks permission on every access. If you see operator db.changeUserPassword:

> db.changeUserPassword
function (username, password) {
    var hashedPassword = _hashPassword(username, password);
    db.system.users.update({user : username, userSource : null}, {$set : {pwd : hashedPassword}});
    var err = db.getLastError();
    if (err) {
        throw "Changing password failed: " + err;
    }
}

You will see — operator changes user's document.

See also system.users Privilege Documents and Delegated Credentials for MongoDB Authentication

Vladimir Korshunov
  • 3,090
  • 3
  • 20
  • 25