Files
lrc-frontend/src/api/Repository.js
2020-08-05 07:50:13 +02:00

74 lines
2.3 KiB
JavaScript

// Repository.js
import Vue from "vue";
import axios from "axios";
import store from "@/store";
const baseDomain = "http://localhost:5443";
const API_URL = `${baseDomain}/api/v1`;
const api = axios.create({
baseURL: API_URL,
});
api.interceptors.request.use(async function(config) {
if (store.getters.isAuthenticated) {
const token = store.state.access_token;
config.headers.Authorization = `Bearer ${token}`;
} else {
if(store.getters.isRefreshTokenValid){
await store.dispatch('refreshToken');
const token = store.state.access_token;
config.headers.Authorization = `Bearer ${token}`;
/*store.dispatch('refreshToken').then( () => {
const token = store.state.access_token;
config.headers.Authorization = `Bearer ${token}`;
}).catch( () => {
window.location = '/login';
});*/
} else {
Vue.swal({
title: "Session Expired",
text: "Your token/session has expired. Would you like to be redirected to the login page?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
}).then( (result) => {
if(result.value) {
window.location = '/login';
} else {
window.location = '/';
}
});
}
}
return config;
});
api.interceptors.response.use(function (response) {
return response;
}, function (error) {
if (401 === error.response.status || 422 === error.response.status) {
Vue.swal({
title: "Session Expired",
text: "Your token/session has expired. Would you like to be redirected to the login page?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
}).then( (result) => {
if(result.value) {
window.location = '/login';
} else {
window.location = '/';
}
});
} else {
console.error(error);
return Promise.reject(error);
}
});
export default api;