You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

134 line
4.6 KiB

  1. import React, { createContext, useState, useEffect, useRef } from 'react';
  2. import {useNavigate} from "react-router-dom";
  3. import {useIdleTimer} from "react-idle-timer";
  4. import { handleLogoutFunction } from 'auth/index';
  5. import { useDispatch } from "react-redux";
  6. import { useIntl } from "react-intl";
  7. import {
  8. isUserLoggedIn,
  9. isGLDLoggedIn,
  10. isPasswordExpiry
  11. } from "utils/Utils";
  12. const TimerContext = createContext();
  13. const AutoLogoutProvider = ({ children }) => {
  14. const intl = useIntl();
  15. const [lastRequestTime, setLastRequestTime] = useState(Date.now());
  16. const navigate = useNavigate();
  17. const [logoutInterval, setLogoutInterval] = useState(1);
  18. const idleLogoutTriggeredRef = useRef(false);
  19. // const [remainingInterval] = useState(5);
  20. const [state, setState] = useState('Active');
  21. const dispatch = useDispatch()
  22. const onIdle = () => {
  23. setLastRequestTime(Date.now());
  24. setState('Idle')
  25. }
  26. const onActive = () => {
  27. setLastRequestTime(Date.now());
  28. setState('Active')
  29. }
  30. const {
  31. // getRemainingTime,
  32. //getTabId,
  33. isLastActiveTab,
  34. } = useIdleTimer({
  35. onIdle,
  36. onActive,
  37. timeout: 1_000,
  38. throttle: 500,
  39. crossTab: true,
  40. syncTimers: 200,
  41. })
  42. const lastActiveTab = isLastActiveTab() === null ? 'loading' : isLastActiveTab()
  43. //const tabId = getTabId() === null ? 'loading' : getTabId().toString()
  44. const getLogoutInterval = () =>{
  45. if(isUserLoggedIn()&&logoutInterval===1){
  46. //TODO: get auto logout time here
  47. if(isGLDLoggedIn()){
  48. setLogoutInterval(240);
  49. // console.log("Set Logout Interval: 240")
  50. }else{
  51. setLogoutInterval(60);
  52. // console.log("Set Logout Interval: 60")
  53. }
  54. // axios.get(`${apiPath}${GET_IDLE_LOGOUT_TIME}`,
  55. // )
  56. // .then((response) => {
  57. // if (response.status === 200) {
  58. // setLastRequestTime(Date.now());
  59. // setLogoutInterval(parseInt(response.data.data));
  60. // }
  61. // })
  62. // .catch(error => {
  63. // console.log(error);
  64. // return false;
  65. // });
  66. }
  67. else{
  68. if(!isUserLoggedIn()&&logoutInterval>1){
  69. setLogoutInterval(1);
  70. }
  71. //navigate('/login');
  72. }
  73. }
  74. useEffect(() => {
  75. getLogoutInterval()
  76. // console.log("AutoLogoutProvider Start")
  77. // console.log(logoutInterval)
  78. const interval = setInterval(async () => {
  79. const currentTime = Date.now();
  80. if (isPasswordExpiry()){
  81. navigate('/user/changePassword');
  82. }
  83. // getRemainingTime();
  84. if(state !== "Active" && lastActiveTab){
  85. const timeElapsed = currentTime - lastRequestTime;
  86. // console.log(parseInt(timeElapsed/1000));
  87. // console.log(logoutInterval* 60);
  88. // console.log(remainingInterval * 60);
  89. // console.log(logoutInterval * 60 * 1000 - timeElapsed)
  90. if (timeElapsed >= logoutInterval * 60 * 1000) {
  91. if (isUserLoggedIn() && !idleLogoutTriggeredRef.current) {
  92. idleLogoutTriggeredRef.current = true;
  93. // Skip alert if token-expiry (axios 401) already showed one, to avoid duplicate alerts
  94. if (localStorage.getItem("expiredAlertShown") === null) {
  95. localStorage.setItem("expiredAlertShown", "true");
  96. alert(intl.formatMessage({ id: "autoLogout" }));
  97. }
  98. dispatch(handleLogoutFunction());
  99. navigate('/login');
  100. window.location.reload();
  101. }
  102. }
  103. }
  104. // else if(state === "Active"){
  105. // const timeElapsed = currentTime - lastRequestTime;
  106. // if ( (logoutInterval * 60 * 1000 - timeElapsed) <= remainingInterval * 60 * 1000){
  107. // }
  108. // //TODO: if is active and remaining time < 5 min then refresh token
  109. // }
  110. }, 1000); // Check every second
  111. return () => {
  112. clearInterval(interval);
  113. };
  114. }, [lastRequestTime,logoutInterval]);
  115. return (
  116. <TimerContext.Provider value={{lastRequestTime,setLastRequestTime}}>
  117. {children}
  118. </TimerContext.Provider>
  119. );
  120. };
  121. export { TimerContext, AutoLogoutProvider };