Skip to content

Instantly share code, notes, and snippets.

@hpstuff
Created March 26, 2018 07:42
Show Gist options
  • Save hpstuff/5f3b8e41e07a1f6ca2f03f15a8ab53fc to your computer and use it in GitHub Desktop.
Save hpstuff/5f3b8e41e07a1f6ca2f03f15a8ab53fc to your computer and use it in GitHub Desktop.
Redux
import jwt_decode from 'jwt-decode';
import { setTokens } from '../actions';
import { SET_TOKEN, CLEAR_TOKEN } from '../actions/types';
import * as api from '../api';
const prefix = /^@REQUEST\//;
const refreshToken = (refresh_token, dispatch) =>
api.refresh_token(refresh_token) //call refresh token api
.then(({ authToken, refreshToken }) => {
dispatch(setTokens(authToken, refreshToken)); //dispatch the new token and refresh token so they can be saved in the store
});
export const jwt_refresh = ({ dispatch, getState }) => {
let refreshingToken;
return (next) => (action) => { //handle every action
if (action.type === SET_TOKEN || !prefix.test(action.type)) {
return next(action); //skip actions if match regex or is 'SET_TOKEN'
}
const { token, refresh_token } = getState().user.tokens; //get the current token and refresh token
if (!token) {
return next(action); //skip this check if there is no tokens yet
}
const token_data = jwt_decode(token);
if (token_data.exp && (token_data.exp * 1000) - Date.now() < 5000) { //check if token is expire
if (!refreshingToken) { //check if we already refreshing the tokens
refreshingToken = refreshToken(refresh_token, dispatch) //refresh the tokens
.then(() => refreshingToken = null)
.then(() => next(action)) //then pass the action
.catch((e) => {
console.log('Refresh token catch', e);
refreshingToken = null;
dispatch({type: CLEAR_TOKEN}); //if there is an error clear the token
});
return;
}
return refreshingToken.then(() => next(action)); //if there is already refreshing going on wait till is done, then pass the actions
}
return next(action);
};
}
@hpstuff
Copy link
Author

hpstuff commented Mar 26, 2018

let store = createStore(
    /*...*/
    composeEnhancers(applyMiddleware(/*...*/, jwt_refresh)),
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment