@@ -3,12 +3,27 @@ import { useLocalState } from "../util/useLocalStorage";
33import { useEffect , useState } from "react" ;
44import { HOST } from "../../host" ;
55
6+
7+ /**
8+
9+ A higher-order component that renders its children only if the user is authorized as a manager.
10+
11+ @param {Object } props - The component props.
12+
13+ @param {React.ReactNode } props.children - The children to be rendered if the user is authorized.
14+
15+ @return {React.ReactNode } The rendered component or an empty string.
16+ */
617const PrivateRouteManager = React . memo ( ( { children } ) => {
718 const [ user , setUser ] = useLocalState ( "" , "user" ) ;
819 const [ isAuthorized , setIsAuthorized ] = useState ( false ) ;
920 const [ privilege , setPrivilege ] = useState ( null ) ;
1021 const [ shouldRender , setShouldRender ] = useState ( false ) ;
1122
23+ /**
24+ Makes a request to the server to check if the user is authorized.
25+ @return {Promise<Object> } A promise that resolves to an object containing authorization data.
26+ */
1227 const make_request = React . useCallback ( async ( ) => {
1328 return await fetch ( `${ HOST } /check-authorization` , {
1429 method : "POST" ,
@@ -21,6 +36,13 @@ const PrivateRouteManager = React.memo(({ children }) => {
2136 . then ( ( data ) => data ) ;
2237 } , [ user ] ) ;
2338
39+ /**
40+ Checks if the user is authorized as a manager.
41+
42+ If authorized, sets the shouldRender state to true and renders the children.
43+
44+ If not authorized, sets the shouldRender state to false and redirects the user to the homepage.
45+ */
2446 const checkPriv = React . useCallback ( async ( ) => {
2547 if ( user . hasOwnProperty ( "email" ) ) {
2648 const data = await make_request ( ) ;
@@ -41,12 +63,10 @@ const PrivateRouteManager = React.memo(({ children }) => {
4163 if ( data . isAuthorized && data . privilege === "manager" ) {
4264 console . log ( "user found" ) ;
4365 // do something here if success
44- // setShouldRender(true); // not needed
4566 setShouldRender ( true ) ;
4667 } else {
4768 console . log ( "priv failed" ) ;
4869 // do something here if it failed
49- // setShouldRender(false); // not needed
5070 setShouldRender ( false ) ;
5171 // since you want to navigate to "/" if the check is false, you can simply do it here
5272 document . location . assign ( "/" ) ;
0 commit comments