diff --git a/lib/oauth.js b/lib/oauth.js index 8b1a0c0..8b2e586 100644 --- a/lib/oauth.js +++ b/lib/oauth.js @@ -31,7 +31,7 @@ module.exports = new Model({ checkBearerToken: function() { var awaitBearerToken; - if (this._bearerTokenIsExpired()) { + if (this._bearerTokenWillExpire()) { awaitBearerToken = this._refreshBearerToken(); } else { var tokenDetails = JSON.parse(SESSION_STORAGE.getItem(LOCAL_STORAGE_PREFIX + 'tokenDetails')); @@ -165,7 +165,7 @@ module.exports = new Model({ ].join(''); }, - _bearerTokenIsExpired: function() { + _bearerTokenWillExpire: function() { var tokenDetails = JSON.parse(SESSION_STORAGE.getItem(LOCAL_STORAGE_PREFIX + 'tokenDetails')); if (tokenDetails) { return Date.now() >= tokenDetails.expires_at - TOKEN_EXPIRATION_ALLOWANCE; @@ -174,14 +174,10 @@ module.exports = new Model({ } }, - _checkForPanoptesSession: function() { - var sessionTokenDetails = JSON.parse(SESSION_STORAGE.getItem(LOCAL_STORAGE_PREFIX + 'tokenDetails')); + _getNewToken: function() { var redirectUri = ls.get(LOCAL_STORAGE_PREFIX + 'redirectUri'); this.update({ _currentSessionCheckPromise: new Promise(function(resolve, reject) { - if (sessionTokenDetails) { - resolve(sessionTokenDetails); - } if (!redirectUri) { reject(Error('No redirect URI found')); @@ -256,6 +252,18 @@ module.exports = new Model({ }); }, + _handleExpiredToken: function() { + var tokenDetails = JSON.parse(SESSION_STORAGE.getItem(LOCAL_STORAGE_PREFIX + 'tokenDetails')); + var tokenHasExpired = false; + if (tokenDetails && tokenDetails.expires_at) { + tokenHasExpired = Date.now() > tokenDetails.expires_at; + } + if (tokenHasExpired) { + console.info('Panoptes session has expired'); + this._deleteBearerToken(); + } + }, + _handleNewBearerToken: function(tokenDetails) { if (tokenDetails && tokenDetails.access_token) { console.log('Got new bearer token', tokenDetails.access_token.slice(-6)); @@ -272,16 +280,15 @@ module.exports = new Model({ }, _refreshBearerToken: function() { - return this._checkForPanoptesSession() + return this._getNewToken() .then(function(tokenDetails) { return this._handleNewBearerToken(tokenDetails); }.bind(this)) .catch(function (error) { - console.info('Panoptes session has expired'); console.log(error); - this._deleteBearerToken(); + this._handleExpiredToken(); return null; - }); + }.bind(this)); }, _saveRedirectUri: function(redirectUri) {