public void Auth(bool doAuth, string dbname, string username, string pwhash)
{
if (Authorized || !doAuth) return;
var cmd = dbname + ".$cmd";
Writer.WriteQuery(new Doc { { "getnonce", 1 } }, cmd, 1);
dynamic reply = Receive().First();
if (reply.ok != 1d)
{
throw new MongoSecurityException("Failed getting nonce", username, dbname);
}
var nonce = reply.nonce;
var key = nonce + username + pwhash;
Writer.WriteQuery(new Doc
{
{"authenticate", 1},
{"user", username},
{"nonce", nonce},
{"key", BsonWriter.MD5HashString(key)}
}, cmd, 1);
dynamic auth = Receive().First();
Authorized = (auth.ok == 1d);
if (!Authorized)
{
throw new MongoSecurityException("Authentication failed or user not authorized", username, dbname);
}
}