Ran into a headache. I'm trying to set an ajaxPreFilter to constantly refresh an API Token prior to each request.
I've got the whole structure built and everything working (including refreshing the token) apart from the actual setting of the Request header with the API token.
var currentRequests = {};
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
//don't do the prefilter code for the refresh_token function and login function
if(options.url == 'API_URL/api/auth/refresh_token' || options.url == 'API_URL/api/auth/login') {
return;
}
successCallback = function(token)
{
jqXHR.setRequestHeader("X-Api-Token", token);
};
errorCallback = function() {
console.error("Could not refresh token, aborting Ajax call to " + options.url);
currentRequests[options.url].abort();
};
check_token_expiry(successCallback, errorCallback);
});
function check_token_expiry(successCallback, errorCallback)
{
current_api_token = localStorage.getItem("api_token");
current_refresh_token = localStorage.getItem("refresh_token");
current_api_token_expiry = localStorage.getItem("api_token_expiry");
current_refresh_token_expiry = localStorage.getItem("refresh_token_expiry");
time_now = Math.floor(Date.now() / 1000);
if(current_refresh_token_expiry > time_now)
{
$.ajax({
type: 'POST',
url: "API_URL/api/auth/refresh_token",
data: "refresh_token=" + current_refresh_token
}).done(function(data) {
if(data.status == 'success') {
localStorage.setItem("api_token", data.token);
localStorage.setItem("refresh_token", data.refresh_token);
localStorage.setItem("api_token_expiry", data.token_expiry);
localStorage.setItem("refresh_token_expiry", data.refresh_token_expiry);
successCallback(data.token);
}
}).fail(function(data) {
errorCallback(data);
});
}
else
{
window.location.href = "login.html";
}
}
I think my problem lies within the successCallback function but not sure how to apply the RequestHeader to each of the ajax calls. I've tried just using localStorage.getItem("api_token") within the call directly but it's still grabbing the previous value which was the reason I started down this route in the first place rather than just using beforeSend();
Any help would be much appreciated.