-
Notifications
You must be signed in to change notification settings - Fork 4
/
react-idle-timer.tsx
84 lines (71 loc) · 2.41 KB
/
react-idle-timer.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import React, { FC, useState, useEffect } from "react";
import { useIdleTimer } from "react-idle-timer";
import { message } from "antd";
import { useMsal } from "../components/msal-react-lite";
import moment from "moment";
//const HelloWorld: FC<any> = () => {
const ReactIdleTimer: FC<any> = (props: any) => {
const [expirationTime, setExpirationTime] = useState<string>("");
const [enableCounter, setEnableCounter] = useState<boolean>(false);
const [currentTime, setCurrentTime] = useState<string>("");
const expirationTimer = process.env.REACT_APP_LOGOUT_TIMER;
const { isLoggedIn } = useMsal();
useEffect(() => {
var timeFunction;
if (enableCounter) {
if (expirationTime === "") {
var date = moment()
.add(parseInt(expirationTimer ?? "120000") / 1000, "seconds")
.format("LTS");
setExpirationTime(date);
message.warning(`session expires at ${date}`, 0);
}
timeFunction = setTimeout(function () {
setCurrentTime(moment().format("LTS"));
}, 1000);
if (
currentTime >= expirationTime &&
currentTime !== "" &&
expirationTime !== ""
) {
sessionStorage.clear();
clearTimeout(timeFunction);
setExpirationTime("");
setEnableCounter(false);
document.location.href="/";
}
} else {
clearTimeout(timeFunction);
setExpirationTime("");
}
}, [enableCounter, currentTime]);
const handleOnIdle = (event: any) => {
if (isLoggedIn) {
console.log(`user is idle`, event);
console.log("last active", getLastActiveTime());
//message.warning(`Your session will expire at ${expirationTime}`, 0);
setEnableCounter(true);
setCurrentTime(moment().format("LTS"));
}
};
const handleOnActive = (event: any) => {
console.log("user is active", event);
console.log("time remaining", getRemainingTime());
};
const handleOnAction = (e: any) => {
console.log("user did something", e);
message.destroy();
setExpirationTime("");
setEnableCounter(false);
setCurrentTime(moment().format("LTS"));
};
const { getRemainingTime, getLastActiveTime } = useIdleTimer({
timeout: parseInt(process.env.REACT_APP_IDLE_TIMER ?? "15000"),
onIdle: handleOnIdle,
onActive: handleOnActive,
onAction: handleOnAction,
debounce: 500,
});
return <div>{props.children}</div>;
};
export default ReactIdleTimer;