Skip to content

Instantly share code, notes, and snippets.

@htom78
Created May 30, 2019 14:56
Show Gist options
  • Save htom78/23d84085877420e84c0faba1fb4c8afb to your computer and use it in GitHub Desktop.
Save htom78/23d84085877420e84c0faba1fb4c8afb to your computer and use it in GitHub Desktop.
vuejs
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