Created
May 30, 2019 14:56
-
-
Save htom78/23d84085877420e84c0faba1fb4c8afb to your computer and use it in GitHub Desktop.
vuejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getAuthToken () { | |
// if the current store token expires soon | |
if (jwt(store.getters['auth/token']).exp - 240 <= (Date.now() / 1000).toFixed(0)) { | |
// if not already requesting a token | |
if (authTokenRequest === null) { | |
authTokenRequest = axios.post('/auth/refresh', {}, { withCredentials: true }) | |
.then(response => { | |
// request complete and store | |
resetAuthTokenRequest() | |
store.commit('auth/refresh', response.data.access_token) | |
return response.data.access_token | |
}) | |
} | |
return authTokenRequest | |
} | |
return store.getters['auth/token'] | |
} | |
// tokenRequest dirty bit reseter | |
function resetAuthTokenRequest () { | |
authTokenRequest = null | |
} | |
// Axios Intercept Requests | |
axios.interceptors.request.use(async function (config) { | |
// If not one of these specific pages that doesn't need a token, use method to get the current token or request a new one. Otherwise, use current token (possibly none) | |
if (!config.url.includes('login') && !config.url.includes('refresh') && !config.url.includes('forgot_password') && !config.url.includes('reset_password') && !config.url.includes('activate')) { | |
config.headers['Authorization'] = 'Bearer ' + await getAuthToken() | |
} else { | |
config.headers['Authorization'] = 'Bearer ' + store.getters['auth/token'] | |
} | |
return config | |
}, function (error) { | |
return Promise.reject(error) | |
}) | |
axios.interceptors.response.use(function (config) { | |
return config | |
}, function (error) { | |
// Prevent endless redirects (login is where you should end up) | |
if (error.request !== undefined) { | |
if (error.request.responseURL.includes('login')) { | |
return Promise.reject(error) | |
} | |
} | |
// If you can't refresh your token or you are sent Unauthorized on any request, logout and go to login | |
if (error.request !== undefined && (error.request.responseURL.includes('refresh') || error.request.status === 401 && error.config.__isRetryRequest)) { | |
store.dispatch('auth/logout') | |
router.push({name: 'Login'}) | |
} else if (error.request !== undefined && error.request.status === 401) { | |
error.config.__isRetryRequest = true | |
return axios.request(error.config) | |
} | |
return Promise.reject(error) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment