Grégoire Delattre c5cafacbf1 Update everything to work with the new router
By the way, remove the router state from redux.
2019-05-19 02:31:25 +02:00

86 lines
2.5 KiB
JavaScript

import { Map, List, fromJS } from "immutable"
import jwtDecode from "jwt-decode"
import Cookies from "universal-cookie"
const defaultState = Map({
error: "",
loading: false,
username: "",
isAdmin: false,
isActivated: false,
isTokenSet: false,
isLogged: false,
polochonToken: "",
polochonUrl: "",
tokens: List(),
modules: Map(),
modulesLoading: false,
});
const handlers = {
"USER_LOGIN_PENDING": state => state.set("loading", true),
"USER_LOGIN_ERROR": (state, action) => {
state.set("loading", false);
return logoutUser(action.payload.response.message);
},
"USER_LOGIN_FULFILLED": (state, action) => {
return updateFromToken(state, action.payload.response.data.token)
},
"USER_SIGNUP_PENDING": state => state.set("loading", true),
"USER_SIGNUP_ERROR": (state, action) => state.merge(Map({
error: action.payload.response.message,
loading: false,
})),
"USER_SIGNUP_FULFILLED": state => state.merge(Map({error: "", loading: false})),
"USER_SET_TOKEN": (state, action) => updateFromToken(state, action.payload.token),
"USER_LOGOUT": () => logoutUser(),
"GET_USER_PENDING": state => state.set("loading", true),
"GET_USER_FULFILLED": (state, action) => state.merge(Map({
polochonToken: action.payload.response.data.token,
polochonUrl: action.payload.response.data.url,
loading: false,
})),
"GET_USER_TOKENS_PENDING": state => state.set("loading", true),
"GET_USER_TOKENS_FULFILLED": (state, action) => state.merge(Map({
"tokens": fromJS(action.payload.response.data),
"loading": false,
})),
"GET_USER_MODULES_PENDING": state => state.set("modulesLoading", true),
"GET_USER_MODULES_FULFILLED": (state, action) => state.merge(Map({
"modules": fromJS(action.payload.response.data),
"modulesLoading": false,
})),
}
function logoutUser(error) {
localStorage.removeItem("token");
const cookies = new Cookies();
cookies.remove("token");
if (error !== "") {
return defaultState.set("error", error);
} else {
return defaultState
}
}
function updateFromToken(state, token) {
const decodedToken = jwtDecode(token);
localStorage.setItem("token", token);
const cookies = new Cookies();
cookies.set("token", token);
return state.merge(Map({
error: "",
isLogged: true,
isTokenSet: true,
isAdmin: decodedToken.isAdmin,
isActivated: decodedToken.isActivated,
username: decodedToken.username,
}))
}
export default (state = defaultState, action) =>
handlers[action.type] ? handlers[action.type](state, action) : state;