use interceptors to renew token
This commit is contained in:
parent
8b0bb17a96
commit
5036cfbab3
@ -1,6 +1,4 @@
|
||||
export default async function ({ $axios, store, redirect }) {
|
||||
await store.dispatch('auth/inspectToken')
|
||||
|
||||
export default function ({ $axios, store, redirect }) {
|
||||
$axios.onRequest((config) => {
|
||||
const token = store.state.auth.jwtToken
|
||||
if (token) {
|
||||
@ -13,6 +11,34 @@ export default async function ({ $axios, store, redirect }) {
|
||||
}
|
||||
})
|
||||
|
||||
$axios.interceptors.response.use((response) => {
|
||||
return response
|
||||
}, (error) => {
|
||||
const originalRequest = error.config
|
||||
|
||||
// prevent infinite loop
|
||||
if (error.response.status === 401 && originalRequest.url.includes('auth/refresh/refresh')) {
|
||||
store.commit('auth/REMOVE_TOKEN')
|
||||
redirect('/')
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
if (error.response.status === 401 && !originalRequest._retry) {
|
||||
originalRequest._retry = true
|
||||
return $axios.post('auth/token/refresh/', {
|
||||
refresh: store.state.auth.jwtRefresh
|
||||
})
|
||||
.then((res) => {
|
||||
if (res.status === 201 || res.status === 200) {
|
||||
store.commit('auth/UPADTE_TOKEN', { token: res.data.access })
|
||||
originalRequest.headers.Authorization = `Bearer ${res.data.access}`
|
||||
return $axios(originalRequest)
|
||||
}
|
||||
})
|
||||
}
|
||||
return Promise.reject(error)
|
||||
})
|
||||
|
||||
$axios.onError((error) => {
|
||||
const code = parseInt(error.response && error.response.status)
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user