add_user.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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.CommandCallbackOperation {
  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 ?? {};
  17. }
  18. executeCallback(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. // v5 removed the digestPassword option from AddUserOptions but we still want to throw
  25. // an error when digestPassword is provided.
  26. if ('digestPassword' in options && options.digestPassword != null) {
  27. return callback(new error_1.MongoInvalidArgumentError('Option "digestPassword" not supported via addUser, use db.command(...) instead'));
  28. }
  29. let roles;
  30. if (!options.roles || (Array.isArray(options.roles) && options.roles.length === 0)) {
  31. (0, utils_1.emitWarningOnce)('Creating a user without roles is deprecated. Defaults to "root" if db is "admin" or "dbOwner" otherwise');
  32. if (db.databaseName.toLowerCase() === 'admin') {
  33. roles = ['root'];
  34. }
  35. else {
  36. roles = ['dbOwner'];
  37. }
  38. }
  39. else {
  40. roles = Array.isArray(options.roles) ? options.roles : [options.roles];
  41. }
  42. let topology;
  43. try {
  44. topology = (0, utils_1.getTopology)(db);
  45. }
  46. catch (error) {
  47. return callback(error);
  48. }
  49. const digestPassword = topology.lastHello().maxWireVersion >= 7;
  50. let userPassword = password;
  51. if (!digestPassword) {
  52. // Use node md5 generator
  53. const md5 = crypto.createHash('md5');
  54. // Generate keys used for authentication
  55. md5.update(`${username}:mongo:${password}`);
  56. userPassword = md5.digest('hex');
  57. }
  58. // Build the command to execute
  59. const command = {
  60. createUser: username,
  61. customData: options.customData || {},
  62. roles: roles,
  63. digestPassword
  64. };
  65. // No password
  66. if (typeof password === 'string') {
  67. command.pwd = userPassword;
  68. }
  69. super.executeCommandCallback(server, session, command, callback);
  70. }
  71. }
  72. exports.AddUserOperation = AddUserOperation;
  73. (0, operation_1.defineAspects)(AddUserOperation, [operation_1.Aspect.WRITE_OPERATION]);
  74. //# sourceMappingURL=add_user.js.map