rap-react
Version:
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
82 lines (79 loc) • 2.62 kB
JavaScript
import React from "react";
import { useLocation } from "react-router-dom/dist";
import { UserContext } from "../../../context/user/userContext";
import { useContext, useEffect, useState } from "react";
import { Navigate } from "react-router-dom/dist";
import loaderContext from "../../../context/loader/LoaderContext";
import { refreshToken } from "../../../services/authService";
export const RequireAuth = ({ children }) => {
//const search = window.location.search;
const location = useLocation();
const [waiting, setWaiting] = useState(true);
const [processing, setProcessing] = useState(-1);
const {
state,
logout,
getTokenDetails,
getBrandSpecificOptions,
getProfileAndPrivileges,
} = useContext(UserContext);
const [renderChildren, shouldRenderChildren] = useState(false);
const { updateLoaderStatus } = useContext(loaderContext);
const [isGettingNewToken, setIsGettingNewToken] = useState(false);
const { hasMultipleBrands, isPrimaryBrand, isSelf, corpBrandCode } = getBrandSpecificOptions();
useEffect(() => {
const isAuthenticated = () => {
const { token, isInValid, isExpired, isExpiring } = getTokenDetails();
if (isExpired || isInValid) {
logout();
} else if (isExpiring) {
if (isGettingNewToken === false) {
setIsGettingNewToken(true);
refreshToken(token).then((res) => {
setIsGettingNewToken(false);
});
}
} else {
shouldRenderChildren(true);
updateLoaderStatus(false);
const isAuthenticated = state?.user?.isAuthenticated ?? false;
if (isAuthenticated === false) {
if (processing === -1) {
setProcessing(0);
getProfileAndPrivileges(
token,
hasMultipleBrands,
isPrimaryBrand,
isSelf,
corpBrandCode,
() => {
setWaiting(false);
setProcessing(1);
}
);
}
} else {
updateLoaderStatus(false);
setWaiting(false);
}
}
};
isAuthenticated();
}, [
state,
getTokenDetails,
getProfileAndPrivileges,
updateLoaderStatus,
renderChildren,
processing,
logout,
isGettingNewToken,
hasMultipleBrands,
isPrimaryBrand,
]);
if (waiting) return <React.Fragment></React.Fragment>;
if (renderChildren) {
return children;
}
return <Navigate to="/login" state={{ from: location }} />;
};