Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 65 | Rev 71 | 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";

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

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

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

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

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

    const token = window.localStorage.getItem("jwt");

    if (token) {
      dispatch(login());
      dispatch(stopLoading());
    } else {
      dispatch(getPermissions());
    }
  };
};

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

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