From c19f5b62a0e113ba1927763893deae8bd995bf36 Mon Sep 17 00:00:00 2001 From: Jannis Mattheis Date: Thu, 15 Mar 2018 20:25:36 +0100 Subject: [PATCH] Add axios default config --- ui/src/actions/defaultAxios.js | 47 ++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 ui/src/actions/defaultAxios.js diff --git a/ui/src/actions/defaultAxios.js b/ui/src/actions/defaultAxios.js new file mode 100644 index 0000000..198b0e8 --- /dev/null +++ b/ui/src/actions/defaultAxios.js @@ -0,0 +1,47 @@ +import axios from 'axios'; +import dispatcher from '../stores/dispatcher'; +import * as GlobalAction from './GlobalAction'; + +let currentToken = null; +const tokenKey = 'gotify-login-key'; + +/** + * Set the authorization token for the next requests. + * @param {string} token the gotify application token + */ +export function setAuthorizationToken(token) { + currentToken = token; + if (token) { + localStorage.setItem(tokenKey, token); + axios.defaults.headers.common['X-Gotify-Key'] = token; + } else { + localStorage.removeItem(tokenKey); + delete axios.defaults.headers.common['X-Gotify-Key']; + } +} + +axios.interceptors.response.use(null, (error) => { + if (error.response.status === 401) { + setAuthorizationToken(null); + dispatcher.dispatch({type: 'REMOVE_CURRENT_USER'}); + } + + console.warn('Error status', error.response.status); + return Promise.reject(error); +}); + +/** + * @return {string} the application token + */ +export function getToken() { + return currentToken; +} + +/** Checks if the current user is logged, if so update the state. */ +export function checkIfAlreadyLoggedIn() { + const key = localStorage.getItem(tokenKey); + if (key) { + setAuthorizationToken(key); + GlobalAction.initialLoad(); + } +}