add_user.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.AddUserOperation = void 0;
  4. const crypto = require("crypto");
  5. const error_1 = require("../error");
  6. const utils_1 = require("../utils");
  7. const command_1 = require("./command");
  8. const operation_1 = require("./operation");
  9. /** @internal */
  10. class AddUserOperation extends command_1.CommandOperation {
  11. constructor(db, username, password, options) {
  12. super(db, options);
  13. this.db = db;
  14. this.username = username;
  15. this.password = password;
  16. this.options = options !== null && options !== void 0 ? options : {};
  17. }
  18. execute(server, session, callback) {
  19. const db = this.db;
  20. const username = this.username;
  21. const password = this.password;
  22. const options = this.options;
  23. // Error out if digestPassword set
  24. if (options.digestPassword != null) {
  25. return callback(new error_1.MongoInvalidArgumentError('Option "digestPassword" not supported via addUser, use db.command(...) instead'));
  26. }
  27. let roles;
  28. if (!options.roles || (Array.isArray(options.roles) && options.roles.length === 0)) {
  29. (0, utils_1.emitWarningOnce)('Creating a user without roles is deprecated. Defaults to "root" if db is "admin" or "dbOwner" otherwise');
  30. if (db.databaseName.toLowerCase() === 'admin') {
  31. roles = ['root'];
  32. }
  33. else {
  34. roles = ['dbOwner'];
  35. }
  36. }
  37. else {
  38. roles = Array.isArray(options.roles) ? options.roles : [options.roles];
  39. }
  40. let topology;
  41. try {
  42. topology = (0, utils_1.getTopology)(db);
  43. }
  44. catch (error) {
  45. return callback(error);
  46. }
  47. const digestPassword = topology.lastHello().maxWireVersion >= 7;
  48. let userPassword = password;
  49. if (!digestPassword) {
  50. // Use node md5 generator
  51. const md5 = crypto.createHash('md5');
  52. // Generate keys used for authentication
  53. md5.update(`${username}:mongo:${password}`);
  54. userPassword = md5.digest('hex');
  55. }
  56. // Build the command to execute
  57. const command = {
  58. createUser: username,
  59. customData: options.customData || {},
  60. roles: roles,
  61. digestPassword
  62. };
  63. // No password
  64. if (typeof password === 'string') {
  65. command.pwd = userPassword;
  66. }
  67. super.executeCommand(server, session, command, callback);
  68. }
  69. }
  70. exports.AddUserOperation = AddUserOperation;
  71. (0, operation_1.defineAspects)(AddUserOperation, [operation_1.Aspect.WRITE_OPERATION]);
  72. //# sourceMappingURL=add_user.js.map