From 5036cfbab35ac84a69eb55b86a329accfcc840c2 Mon Sep 17 00:00:00 2001 From: jb-alvarado Date: Sun, 24 May 2020 17:52:05 +0200 Subject: [PATCH] use interceptors to renew token --- ffplayout/frontend/plugins/axios.js | 32 ++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/ffplayout/frontend/plugins/axios.js b/ffplayout/frontend/plugins/axios.js index 586e8b53..707e0c72 100644 --- a/ffplayout/frontend/plugins/axios.js +++ b/ffplayout/frontend/plugins/axios.js @@ -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)