MongoDB: lock/unlock users

While there are no built in commands for lock/unLock, it is possible to add them. Here are a couple of simple implementations that remove the user you want to lock from the db.system.users collection and save it in a lockedUsers collection so we can unlock them later by doing the reverse.
I've also shown examples where the user can't login when they're "locked".
 
function lockUser(db, user) {
 var toLock = db.system.users.find({ "user" : user });
 if (toLock.size() != 1) {
 print("Error! found " + toLock.size() + " matching users");
 return;
 }
 db.lockedUsers.insert(toLock[0]);
 db.system.users.remove({"user":user});
}
 
function unlockUser(db, user) {
 var toUnlock = db.lockedUsers.find( {"user":user} );
 if (toUnlock.size() != 1) {
 print("Error! found " + toUnlock.size() + " matching users");
 return;
 }
 db.system.users.insert(toUnlock[0]); 
 db.lockedUsers.remove({"user":user});
}
The user is there on the server in the system.users collection
 
> use test
switched to db test
> db.system.users.find()
{ "_id" : ObjectId("53071b36fdc712345718c9b2"), "user" : "admin", "pwd" : "7c67ef13bbd4cae106d959320af3f704", "roles" : [ "dbAdminAnyDatabase" ] }
{ "_id" : ObjectId("53071a8afdc712345718c9b1"), "user" : "author", "pwd" : "9e67390049a2cb02f8f80ba8525233df", "roles" : [ "read" ] }
The user can login
 
$ mongo test -u author -p pass
MongoDB shell version: 2.4.8
connecting to: test
> 
Now lock the user on the server
 
> lockUser(db, "author")
> db.system.users.find()
{ "_id" : ObjectId("53071b36fdc712345718c9b2"), "user" : "admin", "pwd" : "7c67ef13bbd4cae106d959320af3f704", "roles" : [ "dbAdminAnyDatabase" ] }
The user can't login
 
$ mongo test -u author -p pass
MongoDB shell version: 2.4.8
connecting to: test
Fri Feb 21 10:17:40.514 Error: 18 { code: 18, ok: 0.0, errmsg: "auth fails" } at src/mongo/shell/db.js:228
exception: login failed
Unlock the user
 
> unlockUser(db, "author")
> db.system.users.find()
{ "_id" : ObjectId("53071b36fdc712345718c9b2"), "user" : "admin", "pwd" : "7c67ef13bbd4cae106d959320af3f704", "roles" : [ "dbAdminAnyDatabase" ] }
{ "_id" : ObjectId("53071a8afdc712345718c9b1"), "user" : "author", "pwd" : "9e67390049a2cb02f8f80ba8525233df", "roles" : [ "read" ] }
And now author can login again
 
$ mongo test -u author -p pass
MongoDB shell version: 2.4.8
connecting to: test
>

  • Ask Question