Adding inactivity handler
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
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");
|
||||
@@ -11,42 +12,33 @@ const ProtectedRoute = ({ children }) => {
|
||||
navigate("/login");
|
||||
};
|
||||
|
||||
if (!token) {
|
||||
return <Navigate to="/login" />;
|
||||
}
|
||||
useIdleTimer(() => {
|
||||
if (token) {
|
||||
handleLogout();
|
||||
}
|
||||
}, 60000); // 1 minute
|
||||
|
||||
if (!token) return <Navigate to="/login" />;
|
||||
|
||||
return (
|
||||
<PageWrapper>
|
||||
<div
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
style={{
|
||||
height: "100vh",
|
||||
margin: 0,
|
||||
padding: 0,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
backgroundColor: "#242424",
|
||||
position: "relative",
|
||||
position: "absolute",
|
||||
top: "1rem",
|
||||
right: "1rem",
|
||||
backgroundColor: "#1a1a1a",
|
||||
color: "#fff",
|
||||
padding: "0.5rem 1rem",
|
||||
border: "none",
|
||||
borderRadius: "4px",
|
||||
cursor: "pointer",
|
||||
}}
|
||||
>
|
||||
<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}
|
||||
</div>
|
||||
Logout
|
||||
</button>
|
||||
{children}
|
||||
</PageWrapper>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
const useIdleTimer = (onIdle, timeout = 60000) => {
|
||||
const timerRef = useRef(null);
|
||||
|
||||
const resetTimer = () => {
|
||||
clearTimeout(timerRef.current);
|
||||
timerRef.current = setTimeout(onIdle, timeout);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const events = ["mousemove", "keydown", "mousedown", "touchstart"];
|
||||
events.forEach(e => window.addEventListener(e, resetTimer));
|
||||
|
||||
resetTimer(); // initialize timer
|
||||
|
||||
return () => {
|
||||
clearTimeout(timerRef.current);
|
||||
events.forEach(e => window.removeEventListener(e, resetTimer));
|
||||
};
|
||||
}, []);
|
||||
};
|
||||
|
||||
export default useIdleTimer;
|
||||
Reference in New Issue
Block a user