Skip to content

Instantly share code, notes, and snippets.

@vickychijwani
Created August 3, 2015 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vickychijwani/e4e66b083e732bbecfa7 to your computer and use it in GitHub Desktop.
Save vickychijwani/e4e66b083e732bbecfa7 to your computer and use it in GitHub Desktop.
An untested example of how to refresh an access token in the Ghost API.
var accessToken;
var refreshToken;
var accessTokenCreatedAt;
var refreshTokenExpiresIn = 24 * 60 * 60; // taken from ghost core
function hasAccessTokenExpired() {
// consider the token as "expired" 5 minutes earlier, to be safe
return new Date().getTime() > accessTokenCreatedAt + authToken.expires_in - 300;
}
function hasRefreshTokenExpired() {
// consider the token as "expired" 5 minutes earlier, to be safe
return new Date().getTime() > accessTokenCreatedAt + refreshTokenExpiresIn - 300;
}
function validateAccessToken(callback) {
boolean valid = ! hasAccessTokenExpired();
if (! valid) {
refreshAccessToken(callback);
}
return valid;
}
function refreshAccessToken(callback) {
if (hasRefreshTokenExpired()) {
loginWithCredentials(callback);
}
// refresh the access token, and note that we call callback() once the token is refreshed
$.ajax({
type: 'POST',
url: API_BASE + '/authentication/token',
data: {
grant_type: 'refresh_token',
client_id: 'ghost-admin',
refresh_token: refreshToken
},
success: function (response) {
accessToken = response.access_token;
accessTokenCreatedAt = new Date().getTime();
callback(); // initiate the original API request that was deferred
},
error: function () {
// handle error
}
});
}
function loginWithCredentials(callback) {
// generate a new access / refresh token pair using username / password, similar to refreshAccessToken
// make sure to call callback() when login is successfully done, to ensure the deferred API request is made eventually
}
// Now here's the clever part...
function fetchAllPosts(callback) {
// passing the callback to validateAccessToken effectively "defers" the intended API request
if (! validateAccessToken(function () { fetchAllPosts(callback); })) {
return;
}
// your access token is valid, go ahead and make a request like GET /posts/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment