JWT refresh

This commit is contained in:
2020-11-29 20:23:20 +01:00
parent e48d300ca9
commit 6d02533d69
18 changed files with 69 additions and 22 deletions

View File

@@ -2,6 +2,29 @@ import axios from "axios";
import * as toggles from "./toggles";
import { push } from "connected-react-router";
import { backend } from "../config.js";
import store from "../index.js";
axios.defaults.withCredentials = true;
axios.interceptors.response.use(
(response) => {
return response;
},
(error) => {
return new Promise((resolve) => {
if (error.response && error.response.status === 401 && error.config && !error.config.__isRetryRequest) {
const response = axios.post(backend + "user/refreshtoken", {withCredentials: true}).then((res) => {
const jwt = res.headers['x-auth-token'];
store.dispatch(setNewToken(jwt))
error.config.__isRetryRequest = true
error.config.headers['x-auth-token'] = jwt
return axios(error.config);
})
resolve(response)
}
throw error
})
});
const autocomplete = (input) => {
return {
@@ -16,6 +39,13 @@ export const clearAutocomplete = () => {
};
};
export const setNewToken = (token) => {
return {
type: "SET_NEW_TOKEN",
payload: token
}
}
export const fetchAutocomplete = (input) => {
return function (dispatch) {
axios
@@ -124,13 +154,14 @@ export const fetchDish = (id) => {
};
};
export const refreshUserData = (token) => {
export const refreshUserData = () => {
return function (dispatch) {
const state = store.getState()
axios({
url: backend + "user/refresh",
method: "POST",
headers: {
"x-auth-token": token,
"x-auth-token": state.data.userData.jwt,
},
})
.then((response) => {
@@ -138,7 +169,7 @@ export const refreshUserData = (token) => {
toggles.setLoggedIn(
response.data.firstname,
response.data.lastname,
token,
state.data.userData.jwt,
response.data.id,
response.data.email,
response.data.NIP,
@@ -149,7 +180,7 @@ export const refreshUserData = (token) => {
);
})
.catch((err) => {
if (err.status === 401) {
if (err.status === 401 || err.status === 500) {
dispatch(logout());
}
console.log(err);