Skip to content

Commit 06733b7

Browse files
author
Eric Koleda
committed
Add the ability to detect expired refresh tokens.
1 parent ba66e7c commit 06733b7

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

src/Service.js

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -380,7 +380,7 @@ Service_.prototype.hasAccess = function() {
380380
return this.lockable_(function() {
381381
var token = this.getToken();
382382
if (!token || this.isExpired_(token)) {
383-
if (token && token.refresh_token) {
383+
if (token && this.canRefresh_(token)) {
384384
try {
385385
this.refresh();
386386
} catch (e) {
@@ -595,6 +595,24 @@ Service_.prototype.isExpired_ = function(token) {
595595
}
596596
};
597597

598+
/**
599+
* Determines if a retrieved token can be refreshed.
600+
* @param {Object} token The token to inspect.
601+
* @return {boolean} True if it can be refreshed, false otherwise.
602+
* @private
603+
*/
604+
Service_.prototype.canRefresh_ = function(token) {
605+
if (!token.refresh_token) return false;
606+
var expiresIn = token.refresh_token_expires_in;
607+
if (!expiresIn) {
608+
return true;
609+
} else {
610+
var expiresTime = token.granted_time + Number(expiresIn);
611+
var now = getTimeInSeconds_(new Date());
612+
return expiresTime - now > Service_.EXPIRATION_BUFFER_SECONDS_;
613+
}
614+
};
615+
598616
/**
599617
* Uses the service account flow to exchange a signed JSON Web Token (JWT) for
600618
* an access token.

0 commit comments

Comments
 (0)