mongocr.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. const crypto = require('crypto');
  3. const AuthProvider = require('./auth_provider').AuthProvider;
  4. /**
  5. * Creates a new MongoCR authentication mechanism
  6. *
  7. * @extends AuthProvider
  8. */
  9. class MongoCR extends AuthProvider {
  10. /**
  11. * Implementation of authentication for a single connection
  12. * @override
  13. */
  14. _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) {
  15. const username = credentials.username;
  16. const password = credentials.password;
  17. const source = credentials.source;
  18. sendAuthCommand(connection, `${source}.$cmd`, { getnonce: 1 }, (err, r) => {
  19. let nonce = null;
  20. let key = null;
  21. // Get nonce
  22. if (err == null) {
  23. nonce = r.nonce;
  24. // Use node md5 generator
  25. let md5 = crypto.createHash('md5');
  26. // Generate keys used for authentication
  27. md5.update(username + ':mongo:' + password, 'utf8');
  28. const hash_password = md5.digest('hex');
  29. // Final key
  30. md5 = crypto.createHash('md5');
  31. md5.update(nonce + username + hash_password, 'utf8');
  32. key = md5.digest('hex');
  33. }
  34. const authenticateCommand = {
  35. authenticate: 1,
  36. user: username,
  37. nonce,
  38. key
  39. };
  40. sendAuthCommand(connection, `${source}.$cmd`, authenticateCommand, callback);
  41. });
  42. }
  43. }
  44. module.exports = MongoCR;