If a token is in the localStorage of the browser we now assume that the user is already logged in. If that's no the case, he will be redirected to the login page.
52 lines
1.3 KiB
JavaScript
52 lines
1.3 KiB
JavaScript
import jwtDecode from 'jwt-decode'
|
|
|
|
const defaultState = {
|
|
userLoading: false,
|
|
username: "",
|
|
isAdmin: false,
|
|
isLogged: false,
|
|
polochonToken: "",
|
|
polochonUrl: "",
|
|
};
|
|
|
|
export default function userStore(state = defaultState, action) {
|
|
switch (action.type) {
|
|
case 'USER_LOGIN_PENDING':
|
|
return Object.assign({}, state, {
|
|
userLoading: true,
|
|
})
|
|
case 'USER_LOGIN_FULFILLED':
|
|
if (action.payload.status === "error") {
|
|
return logoutUser(state)
|
|
}
|
|
return updateFromToken(state, action.payload.data.token)
|
|
case 'USER_SET_TOKEN':
|
|
return updateFromToken(state, action.payload.token)
|
|
case 'USER_LOGOUT':
|
|
return logoutUser(state)
|
|
case 'GET_USER_FULFILLED':
|
|
return Object.assign({}, state, {
|
|
polochonToken: action.payload.data.token,
|
|
polochonUrl: action.payload.data.url,
|
|
})
|
|
default:
|
|
return state;
|
|
}
|
|
}
|
|
|
|
function logoutUser(state) {
|
|
localStorage.removeItem('token');
|
|
return Object.assign({}, state, defaultState)
|
|
}
|
|
|
|
function updateFromToken(state, token) {
|
|
const decodedToken = jwtDecode(token);
|
|
localStorage.setItem('token', token);
|
|
return Object.assign({}, state, {
|
|
userLoading: false,
|
|
isLogged: true,
|
|
isAdmin: decodedToken.isAdmin,
|
|
username: decodedToken.username,
|
|
})
|
|
}
|