Skip to content

Commit

Permalink
Merge pull request #86 from zooniverse/oauth-refresh-token
Browse files Browse the repository at this point in the history
Replace _checkPanoptesSession with _getNewToken
  • Loading branch information
eatyourgreens authored Mar 6, 2018
2 parents 595e694 + 8bc2017 commit d9a4eb6
Showing 1 changed file with 18 additions and 11 deletions.
29 changes: 18 additions & 11 deletions lib/oauth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'));
Expand Down Expand Up @@ -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;
Expand All @@ -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'));
Expand Down Expand Up @@ -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));
Expand All @@ -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) {
Expand Down

0 comments on commit d9a4eb6

Please sign in to comment.