diff --git a/lib/api.js b/lib/api.js index eb66fba..bb1e859 100644 --- a/lib/api.js +++ b/lib/api.js @@ -111,7 +111,7 @@ Api.prototype = { /** * If there's no OAuthKey, request one */ - if (!this.requestOptions.headers.Authorization) { + if (!this.requestOptions.headers.Authorization || this.isExpired()) { return new Promise(function(resolve, reject){ self.authorize(function(){ self.method.call(self, method, function(data, response){ @@ -255,10 +255,18 @@ Api.prototype = { _.extend(self.requestOptions.headers, { Authorization: data.token_type + ' ' + data.access_token }); + // Multiplying expires_in (seconds) by 1000 since JS getTime() is expressed in ms + self.authorizationExpireTime = new Date().getTime() + ( data.expires_in * 1000 ); callback(data); }); }, + isExpired: function() { + // Expressed in ms ( 10 seconds ) + var THRESHOLD = 10000; + return (new Date().getTime() - THRESHOLD) > this.authorizationExpireTime; + }, + /** * Populates the SDK object with the services */