add_user.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. 'use strict';
  2. const Aspect = require('./operation').Aspect;
  3. const CommandOperation = require('./command');
  4. const defineAspects = require('./operation').defineAspects;
  5. const crypto = require('crypto');
  6. const handleCallback = require('../utils').handleCallback;
  7. const toError = require('../utils').toError;
  8. class AddUserOperation extends CommandOperation {
  9. constructor(db, username, password, options) {
  10. super(db, options);
  11. this.username = username;
  12. this.password = password;
  13. }
  14. _buildCommand() {
  15. const db = this.db;
  16. const username = this.username;
  17. const password = this.password;
  18. const options = this.options;
  19. // Get additional values
  20. let roles = Array.isArray(options.roles) ? options.roles : [];
  21. // If not roles defined print deprecated message
  22. // TODO: handle deprecation properly
  23. if (roles.length === 0) {
  24. console.log('Creating a user without roles is deprecated in MongoDB >= 2.6');
  25. }
  26. // Check the db name and add roles if needed
  27. if (
  28. (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') &&
  29. !Array.isArray(options.roles)
  30. ) {
  31. roles = ['root'];
  32. } else if (!Array.isArray(options.roles)) {
  33. roles = ['dbOwner'];
  34. }
  35. const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7;
  36. let userPassword = password;
  37. if (!digestPassword) {
  38. // Use node md5 generator
  39. const md5 = crypto.createHash('md5');
  40. // Generate keys used for authentication
  41. md5.update(username + ':mongo:' + password);
  42. userPassword = md5.digest('hex');
  43. }
  44. // Build the command to execute
  45. const command = {
  46. createUser: username,
  47. customData: options.customData || {},
  48. roles: roles,
  49. digestPassword
  50. };
  51. // No password
  52. if (typeof password === 'string') {
  53. command.pwd = userPassword;
  54. }
  55. return command;
  56. }
  57. execute(callback) {
  58. const options = this.options;
  59. // Error out if digestPassword set
  60. if (options.digestPassword != null) {
  61. return callback(
  62. toError(
  63. "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."
  64. )
  65. );
  66. }
  67. // Attempt to execute auth command
  68. super.execute((err, r) => {
  69. if (!err) {
  70. return handleCallback(callback, err, r);
  71. }
  72. return handleCallback(callback, err, null);
  73. });
  74. }
  75. }
  76. defineAspects(AddUserOperation, Aspect.WRITE_OPERATION);
  77. module.exports = AddUserOperation;