Proyectos de Subversion LeadersLinked - SPA

Rev

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

import { axios } from "../../utils";
import { addNotification } from "../notification/notification.actions";
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, fatal } = response.data;

        if (fatal) {
          dispatch(startLogout());
          return;
        }

        if (!success) {
          dispatch(addNotification({ style: "danger", msg: data }));
          return;
        }

        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,
});