Methods for adding and removing users RUBY-89

This commit is contained in:
Kyle Banker 2010-01-28 16:39:40 -05:00
parent 5b45c0fd83
commit f6e505e511
2 changed files with 47 additions and 14 deletions

View File

@ -89,6 +89,35 @@ module Mongo
ok?(command(auth))
end
# Adds a user to this database for use with authentication. If the user already
# exists in the system, the password will be updated.
#
# @param [String] username
# @param [String] password
#
# @return [Hash] an object representing the user.
def add_user(username, password)
users = self[SYSTEM_USER_COLLECTION]
user = users.find_one({:user => username}) || {:user => username}
user['pwd'] = hash_password(username, password)
users.save(user)
return user
end
# Remove the given user from this database. Returns false if the user
# doesn't exist in the system.
#
# @param [String] username
#
# @return [Boolean]
def remove_user(username)
if self[SYSTEM_USER_COLLECTION].find_one({:user => username})
self[SYSTEM_USER_COLLECTION].remove({:user => username}, :safe => true)
else
return false
end
end
# Deauthorizes use for this database for this connection.
#
# @raise [MongoDBError] if logging out fails.

View File

@ -21,18 +21,6 @@ class DBTest < Test::Unit::TestCase
@@db = @@conn.db('ruby-mongo-test')
@@users = @@db.collection('system.users')
def setup
@spongebob = 'spongebob'
@spongebob_password = 'squarepants'
@@users.remove
@@users.insert(:user => @spongebob, :pwd => @@db.send(:hash_password, @spongebob, @spongebob_password))
end
def teardown
@@users.remove if @@users
@@db.error
end
def test_close
@@conn.close
assert !@@conn.connected?
@ -139,9 +127,12 @@ class DBTest < Test::Unit::TestCase
end
def test_authenticate
@@db.add_user('spongebob', 'squarepants')
assert !@@db.authenticate('nobody', 'nopassword')
assert !@@db.authenticate(@spongebob, 'squareliederhosen')
assert @@db.authenticate(@spongebob, @spongebob_password)
assert !@@db.authenticate('spongebob' , 'squareliederhosen')
assert @@db.authenticate('spongebob', 'squarepants')
@@db.logout
@@db.remove_user('spongebob')
end
def test_logout
@ -202,6 +193,19 @@ class DBTest < Test::Unit::TestCase
assert db.collection('users').remove
end
def test_user_management
@@db.add_user("bob", "secret")
@@db.logout
p @@users.find.to_a
assert @@db.authenticate("bob", "secret")
assert @@db.remove_user("bob")
assert !@@db.authenticate("bob", "secret")
end
def test_remove_non_existant_user
assert !@@db.remove_user("joe")
end
context "database profiling" do
setup do
@db = @@conn['ruby-mongo-test-admin-functions']