Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 85 86 87 88 89 90 | 2x 2x 2x 2x 2x 2x | import { useEffect, useState } from "react";
import { parse } from "cookie";
import Modal from "../Modal";
import { fetchTtl } from "../../session";
import refreshSession from "../../session/refresh";
import logoutSession from "../../session/logout";
// calculate TWO_MINUTES for interval
const SECOND = 1000;
const MINUTE = 60 * SECOND;
const TWO_MINUTES = 2 * MINUTE;
const DEFAULT_SESSION_CHECK_INTERVAL = TWO_MINUTES;
// 120 seconds is 2 minutes
const DEFAULT_WARNING_TIMEOUT_SECONDS = 120;
function shouldShowInactiveDialog(
timeRemainingSeconds,
warningTimeoutSeconds = DEFAULT_WARNING_TIMEOUT_SECONDS,
) {
return timeRemainingSeconds <= warningTimeoutSeconds;
}
const Session = () => {
const [isOpen, setIsOpen] = useState(false);
let ttlInterval;
useEffect(() => {
let didCancel = false;
const cookies = parse(document.cookie);
const hasAuthToken = !!cookies.qpp_auth_token;
async function isSessionValid() {
if (hasAuthToken) {
const timeRemaining = await fetchTtl(cookies.qpp_auth_token);
// safeguard against unmounted component
if (didCancel) return;
// token expired
if (timeRemaining === 0) {
logoutSession(window);
return;
}
// token is about to expire
if (shouldShowInactiveDialog(timeRemaining)) {
setIsOpen(true);
}
}
}
ttlInterval = setInterval(isSessionValid, DEFAULT_SESSION_CHECK_INTERVAL);
return () => {
clearInterval(ttlInterval);
didCancel = true;
};
}, []);
// This Dialog shows up 2 minutes before the user session ends
// giving the user an opportunity to refresh the token
// or to sign out
return (
<Modal
useDesignSystem
title="You will be signed out within two minutes"
isOpen={isOpen}
primary={{
title: "Keep me signed in",
onClick: () => {
refreshSession();
clearInterval(ttlInterval);
setIsOpen(false);
},
}}
secondary={{
title: "Sign me out now",
onClick: () => logoutSession(window),
}}
onRequestClose={() => setIsOpen(false)}
>
<p>
You have been inactive for thirty minutes. For your security, we will
sign you out automatically.
</p>
</Modal>
);
};
export default Session;
|