diff --git a/lib/uri_parser.js b/lib/uri_parser.js index 8ff66b142..957d71ef2 100644 --- a/lib/uri_parser.js +++ b/lib/uri_parser.js @@ -451,6 +451,13 @@ function parseConnectionString(uri, options, callback) { parsedOptions = Object.assign({}, parsedOptions, options); const auth = { username: null, password: null, db: db && db !== '' ? qs.unescape(db) : null }; + if (parsedOptions.auth) { + // maintain support for legacy options passed into `MongoClient` + if (parsedOptions.auth.username) auth.username = parsedOptions.auth.username; + if (parsedOptions.auth.user) auth.username = parsedOptions.auth.user; + if (parsedOptions.auth.password) auth.password = parsedOptions.auth.password; + } + if (cap[4].split('?')[0].indexOf('@') !== -1) { return callback(new MongoParseError('Unescaped slash in userinfo section')); } diff --git a/test/tests/unit/connection_string_tests.js b/test/tests/unit/connection_string_tests.js index 30cfb75be..6234340bd 100644 --- a/test/tests/unit/connection_string_tests.js +++ b/test/tests/unit/connection_string_tests.js @@ -29,6 +29,38 @@ const skipTests = [ ]; describe('Connection String', function() { + it('should support auth passed in through options', function(done) { + const optionsWithUser = { + authMechanism: 'SCRAM-SHA-1', + auth: { user: 'testing', password: 'llamas' } + }; + + const optionsWithUsername = { + authMechanism: 'SCRAM-SHA-1', + auth: { username: 'testing', password: 'llamas' } + }; + + parseConnectionString('mongodb://localhost', optionsWithUser, (err, result) => { + expect(err).to.not.exist; + expect(result.auth).to.containSubset({ + db: 'admin', + username: 'testing', + password: 'llamas' + }); + + parseConnectionString('mongodb://localhost', optionsWithUsername, (err, result) => { + expect(err).to.not.exist; + expect(result.auth).to.containSubset({ + db: 'admin', + username: 'testing', + password: 'llamas' + }); + + done(); + }); + }); + }); + it('should provide a default port if one is not provided', function(done) { parseConnectionString('mongodb://hostname', function(err, result) { expect(err).to.not.exist;