2022-02-01 13:24:01 +09:00
|
|
|
import { createContext, useState } from "react";
|
2022-02-03 02:33:22 +09:00
|
|
|
import { useLocation, useNavigate } from "react-router-dom";
|
2022-02-01 13:24:01 +09:00
|
|
|
|
|
|
|
export const HeaderContext = createContext({});
|
|
|
|
|
|
|
|
export const HeaderContextProvider = ({ children }) => {
|
|
|
|
|
2022-02-03 02:33:22 +09:00
|
|
|
const {pathname} = useLocation();
|
|
|
|
const navigator = useNavigate();
|
|
|
|
const acc_type = pathname.split('/')[1];
|
|
|
|
|
2022-02-01 13:24:01 +09:00
|
|
|
const [selected_item_sidebar, SetSelectedItemOfSidebar] = useState('');
|
|
|
|
|
2022-02-03 02:33:22 +09:00
|
|
|
const handleLogout = () => {
|
|
|
|
axios.get(`/${acc_type}/logout`)
|
|
|
|
.then(() => {
|
|
|
|
localStorage.removeItem(`${acc_type}_token`);
|
|
|
|
navigator(`/${acc_type}/login`);
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
const isAuthenticate = () => {
|
|
|
|
let token = localStorage.getItem(`${acc_type}_token`);
|
2022-02-03 20:59:24 +09:00
|
|
|
if (!token){
|
|
|
|
navigator(`/${acc_type}/login`);
|
|
|
|
return false;
|
2022-02-03 02:33:22 +09:00
|
|
|
}
|
2022-02-03 20:59:24 +09:00
|
|
|
else {
|
2022-02-03 04:39:18 +09:00
|
|
|
token = JSON.parse(token);
|
|
|
|
let expires = token.expires;
|
2022-02-03 06:27:47 +09:00
|
|
|
let now = new Date().getTime(); //current timestamp
|
2022-02-03 20:59:24 +09:00
|
|
|
if (now >= expires){
|
2022-02-03 06:27:47 +09:00
|
|
|
handleLogout();
|
|
|
|
return false;
|
|
|
|
}
|
2022-02-03 02:33:22 +09:00
|
|
|
}
|
2022-02-03 04:39:18 +09:00
|
|
|
return true;
|
2022-02-03 02:33:22 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2022-02-01 13:24:01 +09:00
|
|
|
return (
|
|
|
|
<HeaderContext.Provider
|
|
|
|
value={{
|
2022-02-03 02:33:22 +09:00
|
|
|
selected_item_sidebar, SetSelectedItemOfSidebar,
|
|
|
|
handleLogout,
|
|
|
|
isAuthenticate
|
2022-02-01 13:24:01 +09:00
|
|
|
}}
|
|
|
|
>
|
|
|
|
{children}
|
|
|
|
</HeaderContext.Provider>
|
|
|
|
);
|
|
|
|
};
|