<commit_before>"use strict";

var f = require('util').format
  , crypto = require('crypto')
  , MongoError = require('../error');

var AuthSession = function(db, username, password) {
  this.db = db;
  this.username = username;
  this.password = password;
}

AuthSession.prototype.equal = function(session) {
  return session.db == this.db 
    && session.username == this.username
    && session.password == this.password;  
}

/**
 * Creates a new MongoCR authentication mechanism
 * @class
 * @return {MongoCR} A cursor instance
 */
var MongoCR = function() {
  this.authStore = [];
}

// Add to store only if it does not exist
var addAuthSession = function(authStore, session) {
  var found = false;

  for(var i = 0; i < authStore.length; i++) {
    if(authStore[i].equal(session)) {
      found = true;
      break;
    }
  }

  if(!found) authStore.push(session);
}

/**
 * Authenticate
 * @method
 * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on
 * @param {Pool} pool Connection pool for this topology
 * @param {string} db Name of the database
 * @param {string} username Username
 * @param {string} password Password
 * @param {authResultCallback} callback The callback to return the result from the authentication
 * @return {object}
 */
MongoCR.prototype.auth = function(server, pool, db, username, password, callback) {
  var self = this;
  // Get all the connections
  var connections = pool.getAll();
  // Total connections
  var count = connections.length;
  if(count == 0) return callback(null, null);

  // Valid connections
  var numberOfValidConnections = 0;
  var credentialsValid = false;
  var errorObject = null;

  // For each connection we need to authenticate
  while(connections.length > 0) {    
    // Execute MongoCR
    var executeMongoCR = function(connection) {
      // Let's start the process
      server.command(f("%s.$cmd", db)
        , { getnonce: 1 }
        , { connection: connection }, function(err, r) {
          // Adjust the number of connections left
          // Get nonce
          var nonce = r.result.nonce;
          // Use node md5 generator
          var md5 = crypto.createHash('md5');
          // Generate keys used for authentication
          md5.update(username + ":mongo:" + password);
          var hash_password = md5.digest('hex');
          // Final key
          md5 = crypto.createHash('md5');
          md5.update(nonce + username + hash_password);
          var key = md5.digest('hex');

          // Execute command
          server.command(f("%s.$cmd", db)
            , { authenticate: 1, user: username, nonce: nonce, key:key}
            , { connection: connection }, function(err, r) {
              count = count - 1;

              // If we have an error
              if(err) {
                errorObject = err;
              } else if(r.result['$err']) {
                errorObject = r.result;
              } else if(r.result['errmsg']) {
                errorObject = r.result;
              } else {
                credentialsValid = true;
                numberOfValidConnections = numberOfValidConnections + 1;
              }

              // We have authenticated all connections
              if(count == 0 && numberOfValidConnections > 0) {
                // Store the auth details
                addAuthSession(self.authStore, new AuthSession(db, username, password));
                // Return correct authentication
                callback(null, true);
              } else if(count == 0) {
                if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr"));
                callback(errorObject, false);
              }
          });
      });
    }

    // Get the connection
    executeMongoCR(connections.shift());
  }
}

/**
 * Re authenticate pool
 * @method
 * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on
 * @param {Pool} pool Connection pool for this topology
 * @param {authResultCallback} callback The callback to return the result from the authentication
 * @return {object}
 */
MongoCR.prototype.reauthenticate = function(server, pool, callback) {
  var count = this.authStore.length;
  if(count == 0) return callback(null, null);
  // Iterate over all the auth details stored
  for(var i = 0; i < this.authStore.length; i++) {
    this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) {
      count = count - 1;
      // Done re-authenticating
      if(count == 0) {
        callback(null, null);
      }
    });
  }
}

/**
 * This is a result from a authentication strategy
 *
 * @callback authResultCallback
 * @param {error} error An error object. Set to null if no error present
 * @param {boolean} result The result of the authentication process
 */

module.exports = MongoCR;<commit_msg>Fixed error issue happening in nonce of mongocr<commit_after>"use strict";

var f = require('util').format
  , crypto = require('crypto')
  , MongoError = require('../error');

var AuthSession = function(db, username, password) {
  this.db = db;
  this.username = username;
  this.password = password;
}

AuthSession.prototype.equal = function(session) {
  return session.db == this.db 
    && session.username == this.username
    && session.password == this.password;  
}

/**
 * Creates a new MongoCR authentication mechanism
 * @class
 * @return {MongoCR} A cursor instance
 */
var MongoCR = function() {
  this.authStore = [];
}

// Add to store only if it does not exist
var addAuthSession = function(authStore, session) {
  var found = false;

  for(var i = 0; i < authStore.length; i++) {
    if(authStore[i].equal(session)) {
      found = true;
      break;
    }
  }

  if(!found) authStore.push(session);
}

/**
 * Authenticate
 * @method
 * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on
 * @param {Pool} pool Connection pool for this topology
 * @param {string} db Name of the database
 * @param {string} username Username
 * @param {string} password Password
 * @param {authResultCallback} callback The callback to return the result from the authentication
 * @return {object}
 */
MongoCR.prototype.auth = function(server, pool, db, username, password, callback) {
  var self = this;
  // Get all the connections
  var connections = pool.getAll();
  // Total connections
  var count = connections.length;
  if(count == 0) return callback(null, null);

  // Valid connections
  var numberOfValidConnections = 0;
  var credentialsValid = false;
  var errorObject = null;

  // For each connection we need to authenticate
  while(connections.length > 0) {    
    // Execute MongoCR
    var executeMongoCR = function(connection) {
      // Let's start the process
      server.command(f("%s.$cmd", db)
        , { getnonce: 1 }
        , { connection: connection }, function(err, r) {
          var nonce = null;
          var key = null;
          
          // Adjust the number of connections left
          // Get nonce
          if(err == null) {
            nonce = r.result.nonce;
            // Use node md5 generator
            var md5 = crypto.createHash('md5');
            // Generate keys used for authentication
            md5.update(username + ":mongo:" + password);
            var hash_password = md5.digest('hex');
            // Final key
            md5 = crypto.createHash('md5');
            md5.update(nonce + username + hash_password);
            key = md5.digest('hex');
          }

          // Execute command
          server.command(f("%s.$cmd", db)
            , { authenticate: 1, user: username, nonce: nonce, key:key}
            , { connection: connection }, function(err, r) {
              count = count - 1;

              // If we have an error
              if(err) {
                errorObject = err;
              } else if(r.result['$err']) {
                errorObject = r.result;
              } else if(r.result['errmsg']) {
                errorObject = r.result;
              } else {
                credentialsValid = true;
                numberOfValidConnections = numberOfValidConnections + 1;
              }

              // We have authenticated all connections
              if(count == 0 && numberOfValidConnections > 0) {
                // Store the auth details
                addAuthSession(self.authStore, new AuthSession(db, username, password));
                // Return correct authentication
                callback(null, true);
              } else if(count == 0) {
                if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr"));
                callback(errorObject, false);
              }
          });
      });
    }

    // Get the connection
    executeMongoCR(connections.shift());
  }
}

/**
 * Re authenticate pool
 * @method
 * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on
 * @param {Pool} pool Connection pool for this topology
 * @param {authResultCallback} callback The callback to return the result from the authentication
 * @return {object}
 */
MongoCR.prototype.reauthenticate = function(server, pool, callback) {
  var count = this.authStore.length;
  if(count == 0) return callback(null, null);
  // Iterate over all the auth details stored
  for(var i = 0; i < this.authStore.length; i++) {
    this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) {
      count = count - 1;
      // Done re-authenticating
      if(count == 0) {
        callback(null, null);
      }
    });
  }
}

/**
 * This is a result from a authentication strategy
 *
 * @callback authResultCallback
 * @param {error} error An error object. Set to null if no error present
 * @param {boolean} result The result of the authentication process
 */

module.exports = MongoCR;
{'fraction_non_alphanumeric': 0.11763529058717616, 'fraction_numerical': 0.004801440432129639, 'mean_word_length': 2.3891525423728814, 'pattern_counts': {'":': 2, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2919320', 'n_tokens_mistral': 2845, 'n_tokens_neox': 2729, 'n_words': 850}