github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/webapp/javascript/components/Protected.tsx (about) 1 import React, { useEffect } from 'react'; 2 import { useAppSelector, useAppDispatch } from '@webapp/redux/hooks'; 3 import { 4 loadCurrentUser, 5 selectCurrentUser, 6 } from '@webapp/redux/reducers/user'; 7 import { isAuthRequired } from '@webapp/util/features'; 8 import { useHistory, useLocation } from 'react-router-dom'; 9 10 export default function Protected({ 11 children, 12 }: { 13 children: React.ReactElement | React.ReactElement[]; 14 }): JSX.Element { 15 const dispatch = useAppDispatch(); 16 const currentUser = useAppSelector(selectCurrentUser); 17 const history = useHistory(); 18 const location = useLocation(); 19 20 useEffect(() => { 21 if (isAuthRequired) { 22 dispatch(loadCurrentUser()).then((e: ShamefulAny): void => { 23 if (!e.isOk && e?.error?.code === 401) { 24 history.push('/login', { redir: location }); 25 } 26 }); 27 } 28 }, [dispatch]); 29 30 if (!isAuthRequired || currentUser) { 31 return <>{children}</>; 32 } 33 34 return <></>; 35 }