/// <summary> /// Authenticates the on first request. /// </summary> /// <param name="databaseName">Name of the database.</param> private void AuthenticateIfRequired(string databaseName) { return; if (databaseName == null) { throw new ArgumentNullException("databaseName"); } EnsureOpenConnection(); if (_connection.IsAuthenticated(databaseName)) { return; } var builder = new MongoConnectionStringBuilder(ConnectionString); if (string.IsNullOrEmpty(builder.Username)) { return; } var serializationFactory = MongoConfiguration.Default.SerializationFactory; var document = new Document().Add("getnonce", 1.0); var nonceResult = SendCommandCore <Document>(serializationFactory, databaseName, typeof(Document), document); var nonce = (string)nonceResult["nonce"]; if (nonce == null) { throw new MongoException("Error retrieving nonce", null); } var pwd = MongoHash.Generate(builder.Username + ":mongo:" + builder.Password); var auth = new Document { { "authenticate", 1.0 }, { "user", builder.Username }, { "nonce", nonce }, { "key", MongoHash.Generate(nonce + builder.Username + pwd) } }; try { var result = SendCommandCore <Document>(serializationFactory, databaseName, typeof(Document), auth); if (!Convert.ToBoolean(result["ok"])) { throw new MongoException("Authentication faild for " + builder.Username); } } catch (MongoCommandException exception) { //Todo: use custom exception? throw new MongoException("Authentication faild for " + builder.Username, exception); } _connection.MarkAuthenticated(databaseName); }
/// <summary> /// Adds the user. /// </summary> /// <param name = "username">The username.</param> /// <param name = "password">The password.</param> public void AddUser(string username, string password) { var users = _database["system.users"]; var pwd = MongoHash.Generate(username + ":mongo:" + password); var user = new Document().Add("user", username).Add("pwd", pwd); if (FindUser(username) != null) { throw new MongoException("A user with the name " + username + " already exists in this database.", null); } users.Insert(user); }