api.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import Vue from 'vue'
  2. import axios from 'axios'
  3. import VueAxios from 'vue-axios'
  4. import router from './routes.js'
  5. Vue.use(VueAxios, axios)
  6. Vue.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
  7. Vue.axios.defaults.headers.common['Content-Type'] = 'application/json'
  8. if (window.appConfig.subdirectory) {
  9. Vue.axios.defaults.baseURL = window.appConfig.subdirectory;
  10. }
  11. Vue.axios.interceptors.response.use(response => response, error => {
  12. // Whether or not the promise must be returned, if unauthenticated is received
  13. // we update the auth state of the front-end
  14. if ( error.response.status === 401 ) {
  15. Vue.$storage.remove('authenticated')
  16. }
  17. // Return the error when we need to handle it at component level
  18. if( error.config.hasOwnProperty('returnError') && error.config.returnError === true ) {
  19. return Promise.reject(error);
  20. }
  21. // Return the error for form validation at component level
  22. if( error.response.status === 422 ) {
  23. return Promise.reject(error);
  24. }
  25. // Push to the login view and force the page to refresh to get a fresh CSRF token
  26. if ( error.response.status === 401 ) {
  27. router.push({ name: 'login', params: { forceRefresh: true } })
  28. return new Promise(() => {})
  29. }
  30. if ( error.response.status === 407 ) {
  31. router.push({ name: 'genericError', params: { err: error.response, closable: false } })
  32. return new Promise(() => {})
  33. }
  34. // we push to a specific or generic error view
  35. let routeName = 'genericError'
  36. // api calls are stateless so when user inactivity is detected
  37. // by the backend middleware it cannot logout the user directly
  38. // so it returns a 418 response.
  39. // We catch the 418 response and push the user to the autolock view
  40. if ( error.response.status === 418 ) routeName = 'autolock'
  41. if ( error.response.status === 404 ) routeName = '404'
  42. router.push({ name: routeName, params: { err: error.response } })
  43. return new Promise(() => {})
  44. })