Skip to content

Instantly share code, notes, and snippets.

@mziwisky
Created January 22, 2015 23:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mziwisky/d23d9f145dffe9ba080a to your computer and use it in GitHub Desktop.
Save mziwisky/d23d9f145dffe9ba080a to your computer and use it in GitHub Desktop.
ajax interceptor management
var authExpirationHandler,
errorHandler;
function catchUnauthorizedResponses(data) {
if (data.status === 401 && !maybeLocalStorage.getItem("token")) {
// ensure the in-memory session really is expired before destroying it
return axios.get("/api/auth/session").then(
(response) => {
// we ARE still auth'd, so just throw the error down the chain
throw data;
}, (err) => {
// local session is invalid, so invoke handler and throw the original error
authExpirationHandler ? authExpirationHandler.call(null) : null;
// TODO: remove self from interceptors chain
throw data;
});
} else {
throw data;
}
}
function authHeader(email, token) {
return "Bearer email=\"" + email + "\", token=\"" + token + "\"";
}
function authorizeAxiosRequests(config) {
if (session) {
config.headers.Authorization = authHeader(email, token);
}
return config;
}
function catchAllErrorResponses(data) {
// maybe don't call errorHandler if (!!authExpirationHandler && data.status === 401) ?? i dunno.
errorHandler.call(null, data.status);
}
module.exports = {
addErrorInterceptors (handler) {
errorHandler = handler;
// TODO: add catchAllErrorResponses to the interceptors chain
},
addAuthInterceptors (email, token, handler) {
authExpirationHandler = handler;
// TODO: add catchUnauthorizedResponses to the interceptors chain
// TODO: add authorizeAxiosRequests to the interceptors chain
}
}
// ...
function handleError(status) {
switch(status) {
case 401:
// display "Unauthorized" error
default:
// display more generic error
}
}
function initialize() {
AjaxInterceptorManager.addErrorInterceptors();
}
// ...
// ...
function handleSessionExpiration() {
SessionStore.actionHandlers.SESSION_DESTROYED.call(SessionStore);
}
function loadSession(sessionData) {
session = sessionData;
maybeLocalStorage.setItem("email", session.user.email);
maybeLocalStorage.setItem("token", session.token);
AjaxInterceptorManager.addAuthInterceptors(session.user.email, session.token, handleSessionExpiration);
}
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment