47 lines
1023 B
React
47 lines
1023 B
React
import React from "react";
|
|
import { Navigate, useNavigate } from "react-router-dom";
|
|
import PageWrapper from "./PageWrapper";
|
|
import useIdleTimer from "../hooks/useIdleTimer";
|
|
|
|
const ProtectedRoute = ({ children }) => {
|
|
const token = localStorage.getItem("token");
|
|
const navigate = useNavigate();
|
|
|
|
const handleLogout = () => {
|
|
localStorage.removeItem("token");
|
|
navigate("/login");
|
|
};
|
|
|
|
useIdleTimer(() => {
|
|
if (token) {
|
|
handleLogout();
|
|
}
|
|
}, 60000); // 1 minute
|
|
|
|
if (!token) return <Navigate to="/login" />;
|
|
|
|
return (
|
|
<PageWrapper>
|
|
<button
|
|
onClick={handleLogout}
|
|
style={{
|
|
position: "absolute",
|
|
top: "1rem",
|
|
right: "1rem",
|
|
backgroundColor: "#1a1a1a",
|
|
color: "#fff",
|
|
padding: "0.5rem 1rem",
|
|
border: "none",
|
|
borderRadius: "4px",
|
|
cursor: "pointer",
|
|
}}
|
|
>
|
|
Logout
|
|
</button>
|
|
{children}
|
|
</PageWrapper>
|
|
);
|
|
};
|
|
|
|
export default ProtectedRoute;
|