Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 71 | Rev 93 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import { axios } from "../../utils";
import { actionsTypes } from "./auth.types";

export const validateAuth = () => {
  return (dispatch) => {
    dispatch(startLoading());

    axios
      .get("/signin", { headers: { "Content-Type": "application/json" } })
      .then((response) => {
        const { success, data } = response.data;

        if (!success) {
          throw new Error(data);
        }

        if (data.is_logged_in) {
          dispatch(login());
        } else {
          dispatch(startLogout());
        }

        if (data.jwt) {
          window.localStorage.setItem("jwt", data.jwt);
        }

        dispatch(setPermissions(data));
      })
      .catch((err) => {
        console.log(err);
        throw new Error(err);
      })
      .finally(() => dispatch(stopLoading()));
  };
};

const setPermissions = (permissions) => ({
  type: actionsTypes.SET_PERMISSIONS,
  payload: permissions,
});

export const startLoading = () => ({
  type: actionsTypes.START_LOADING,
});

export const stopLoading = () => ({
  type: actionsTypes.STOP_LOADING,
});

export const login = () => ({
  type: actionsTypes.LOGIN,
});

const startLogout = () => {
  return (dispatch) => {
    window.localStorage.removeItem("jwt");
    dispatch(logout());
  };
};

export const logout = () => ({
  type: actionsTypes.LOGOUT,
});