add_user.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. const digestPassword = (0, utils_1.getTopology)(db).lastHello().maxWireVersion >= 7;
  41. let userPassword = password;
  42. if (!digestPassword) {
  43. // Use node md5 generator
  44. const md5 = crypto.createHash('md5');
  45. // Generate keys used for authentication
  46. md5.update(`${username}:mongo:${password}`);
  47. userPassword = md5.digest('hex');
  48. }
  49. // Build the command to execute
  50. const command = {
  51. createUser: username,
  52. customData: options.customData || {},
  53. roles: roles,
  54. digestPassword
  55. };
  56. // No password
  57. if (typeof password === 'string') {
  58. command.pwd = userPassword;
  59. }
  60. super.executeCommand(server, session, command, callback);
  61. }
  62. }
  63. exports.AddUserOperation = AddUserOperation;
  64. (0, operation_1.defineAspects)(AddUserOperation, [operation_1.Aspect.WRITE_OPERATION]);
  65. //# sourceMappingURL=add_user.js.map