diff --git a/README.md b/README.md index b306b9a..6aaf088 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,26 @@ var credentials = { }; ``` +### MFA code +```js + +var Robinhood = robinhood({ + username : '', + password : '' + }, (data) => { + if (data && data.mfa_required) { + var mfa_code = '123456'; // set mfa_code here + + Robinhood.set_mfa_code(mfa_code, () => { + console.log(Robinhood.auth_token()); + }); + } + else { + console.log(Robinhood.auth_token()); + } + }) +``` + ### Robinhood API Auth Token ```js //A previously authenticated Robinhood API auth token diff --git a/src/robinhood.js b/src/robinhood.js index 3314abe..1717ac1 100644 --- a/src/robinhood.js +++ b/src/robinhood.js @@ -68,7 +68,8 @@ function RobinhoodWebApi(opts, callback) { username : null, password : null, headers : null, - auth_token : null + auth_token : null, + mfa_code : null }, api = {}; @@ -87,11 +88,16 @@ function RobinhoodWebApi(opts, callback) { }; _setHeaders(); if (!_private.auth_token) { - _login(function(){ + _login(function(data){ _isInit = true; if (callback) { - callback.call(); + if (data) { + callback(data); + } + else { + callback.call() + } } }); } else { @@ -114,28 +120,44 @@ function RobinhoodWebApi(opts, callback) { } function _login(callback){ + var form = { + password: _private.password, + username: _private.username + }; + + if (_private.mfa_code) { + form.mfa_code = _private.mfa_code + } + _request.post({ uri: _apiUrl + _endpoints.login, - form: { - password: _private.password, - username: _private.username - } + form: form }, function(err, httpResponse, body) { if(err) { throw (err); } - _private.auth_token = body.token; - _build_auth_header(_private.auth_token); - - _setHeaders(); - - // Set account - _set_account().then(function() { - callback.call(); - }).catch(function(err) { - throw (err); - }) + if (body.mfa_required && body.mfa_required === true) { + callback(body); + } + else { + if (!body.token) { + throw new Error( + "token not found " + JSON.stringify(httpResponse) + ) + } + _private.auth_token = body.token; + _build_auth_header(_private.auth_token); + + _setHeaders(); + + // Set account + _set_account().then(function() { + callback.call(); + }).catch(function(err) { + throw (err); + }) + } }); } @@ -161,6 +183,14 @@ function RobinhoodWebApi(opts, callback) { /* +--------------------------------+ * * | Define API methods | * * +--------------------------------+ */ + + // Sets the mfa_code variable and initiates the login process again + api.set_mfa_code = function(mfa_code, callback) { + _private.mfa_code = mfa_code; + + _login(callback); + }; + api.auth_token = function() { return _private.auth_token; };