diff --git a/lib/mongo/db.rb b/lib/mongo/db.rb index f5613f5..72f0e8d 100644 --- a/lib/mongo/db.rb +++ b/lib/mongo/db.rb @@ -173,12 +173,15 @@ module Mongo # # @param [String] username # @param [String] password + # @param [Boolean] read_only + # Create a read-only user. # # @return [Hash] an object representing the user. - def add_user(username, password) + def add_user(username, password, read_only = false) users = self[SYSTEM_USER_COLLECTION] user = users.find_one({:user => username}) || {:user => username} user['pwd'] = Mongo::Support.hash_password(username, password) + user['readOnly'] = true if read_only; users.save(user) return user end diff --git a/test/auxillary/authentication_test.rb b/test/auxillary/authentication_test.rb index 83d33b4..a744d1e 100644 --- a/test/auxillary/authentication_test.rb +++ b/test/auxillary/authentication_test.rb @@ -26,6 +26,7 @@ class AuthenticationTest < Test::Unit::TestCase @admin.authenticate('bob', 'secret') @db1.add_user('user1', 'secret') @db2.add_user('user2', 'secret') + @db2.add_user('userRO', 'secret', true) # read-only @admin.logout assert_raise Mongo::OperationFailure do @@ -53,6 +54,7 @@ class AuthenticationTest < Test::Unit::TestCase assert @db1['stuff'].insert({:a => 2}, :safe => true) assert @db2['stuff'].insert({:a => 2}, :safe => true) + assert @db2['stuff'].find(:safe => true) @db1.logout assert_raise Mongo::OperationFailure do @@ -63,6 +65,12 @@ class AuthenticationTest < Test::Unit::TestCase assert_raise Mongo::OperationFailure do assert @db2['stuff'].insert({:a => 2}, :safe => true) end + + @db2.authenticate('userRO', 'secret') + assert @db2['stuff'].find(:safe => true) + assert_raise Mongo::OperationFailure do + assert @db2['stuff'].insert({:a => 2}, :safe => true) + end end end diff --git a/test/db_test.rb b/test/db_test.rb index 910d2c8..c14dd39 100644 --- a/test/db_test.rb +++ b/test/db_test.rb @@ -151,6 +151,13 @@ class DBTest < Test::Unit::TestCase @@db.remove_user('foo:bar') end + def test_authenticate_read_only + @@db.add_user('joebob', 'user', true) # read-only user + assert @@db.authenticate('joebob', 'user') + @@db.logout + @@db.remove_user('joebob') + end + def test_authenticate_with_connection_uri @@db.add_user('spongebob', 'squarepants') assert Mongo::Connection.from_uri("mongodb://spongebob:squarepants@#{host_port}/#{@@db.name}")