@@ -5,8 +5,14 @@ const Connection = require('./connection');
55const Query = require ( './commands' ) . Query ;
66const createClientInfo = require ( '../topologies/shared' ) . createClientInfo ;
77const MongoError = require ( '../error' ) . MongoError ;
8+ const defaultAuthProviders = require ( '../auth/defaultAuthProviders' ) . defaultAuthProviders ;
9+ let AUTH_PROVIDERS ;
810
911function connect ( options , callback ) {
12+ if ( AUTH_PROVIDERS == null ) {
13+ AUTH_PROVIDERS = defaultAuthProviders ( options . bson ) ;
14+ }
15+
1016 if ( options . family !== void 0 ) {
1117 makeConnection ( options . family , options , ( err , socket ) => {
1218 if ( err ) {
@@ -132,6 +138,14 @@ function performInitialHandshake(conn, options, callback) {
132138 // relocated, or at very least restructured.
133139 conn . ismaster = ismaster ;
134140 conn . lastIsMasterMS = new Date ( ) . getTime ( ) - start ;
141+
142+ const credentials = options . credentials ;
143+ if ( credentials ) {
144+ credentials . resolveAuthMechanism ( ismaster ) ;
145+ authenticate ( conn , credentials , callback ) ;
146+ return ;
147+ }
148+
135149 callback ( null , conn ) ;
136150 } ) ;
137151}
@@ -260,6 +274,7 @@ function makeConnection(family, options, callback) {
260274
261275const CONNECTION_ERROR_EVENTS = [ 'error' , 'close' , 'timeout' , 'parseError' ] ;
262276function runCommand ( conn , ns , command , options , callback ) {
277+ if ( typeof options === 'function' ) ( callback = options ) , ( options = { } ) ;
263278 const socketTimeout = typeof options . socketTimeout === 'number' ? options . socketTimeout : 360000 ;
264279 const bson = conn . options . bson ;
265280 const query = new Query ( bson , ns , command , {
@@ -293,4 +308,18 @@ function runCommand(conn, ns, command, options, callback) {
293308 conn . write ( query . toBin ( ) ) ;
294309}
295310
311+ function authenticate ( conn , credentials , callback ) {
312+ const mechanism = credentials . mechanism ;
313+ if ( ! AUTH_PROVIDERS [ mechanism ] ) {
314+ callback ( new MongoError ( `authMechanism '${ mechanism } ' not supported` ) ) ;
315+ return ;
316+ }
317+
318+ const provider = AUTH_PROVIDERS [ mechanism ] ;
319+ provider . auth ( runCommand , [ conn ] , credentials , ( ) => {
320+ console . log ( 'authed through provider!' ) ;
321+ callback ( null , conn ) ;
322+ } ) ;
323+ }
324+
296325module . exports = connect ;
0 commit comments