reactjs 使用react的会话超时警告模式

tkqqtvp1  于 2023-03-22  发布在  React
关注(0)|答案(3)|浏览(160)

我需要在13分钟不活动后显示超时警告模式,如果用户没有采取任何行动,则在15分钟后结束会话。我需要使用reactjs实现这一点。我在https://www.npmjs.com/package/react-timeout#react-classic-verbose检查了react-timeout,但没有帮助。如果有人知道这样做的方法,请与我分享。

ctehm74n

ctehm74n1#

您可以像这样创建一个高阶组件,并通过高阶组件传递子组件
HOC:
`// code

export default function(ComposedClass) {
  class AutoLogout extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        warningTime: 1000 * 60 * 10,
        signoutTime: 1000 * 60 * 15,
      };
    }

    componentDidMount() {
      this.events = [
        'load',
        'mousemove',
        'mousedown',
        'click',
        'scroll',
        'keypress'
      ];

      for (var i in this.events) {
        window.addEventListener(this.events[i], this.resetTimeout);
      }

      this.setTimeout();
    }

    clearTimeoutFunc = () => {
      if (this.warnTimeout) clearTimeout(this.warnTimeout);

      if (this.logoutTimeout) clearTimeout(this.logoutTimeout);
    };

    setTimeout = () => {
      this.warnTimeout = setTimeout(this.warn, this.state.warningTime);
      this.logoutTimeout = setTimeout(this.logout, this.state.signoutTime);
    };

    resetTimeout = () => {
      this.clearTimeoutFunc();
      this.setTimeout();
    };

    warn = () => {
      window.alert("You will be logged out automatically in 1 minute")
      console.log('You will be logged out automatically in 1 minute.');
    };

    logout = () => {
      // Send a logout request to the API
      console.log('Sending a logout request to the API...');
      this.destroy();
    };

    destroy = () => {
     //clear the session
      browserHistory.push('/');
      window.location.assign('/');
    };

    render() {

      return (
        <div>
          <ComposedClass {...this.props} />
        </div>
      );
    }
  }
}

'
您可以将此HOC Package 到路由文件中的所有那些您希望因不活动而向用户给予警告的组件中
<Route path="/test" component={HOC(comonent)} />
在上面的代码组件将是你要添加此功能的页面。

pod7payv

pod7payv2#

如果你想用Package实现同样的功能,那么你可以使用React Idle Timer Package编写下面的代码
npm i react-idle-timer

import React from 'react'
import { useIdleTimer } from 'react-idle-timer'
import { useHistory } from 'react-router'

const SESSION_IDEL_MINUTES = 4;

const AutoLagoutTimer = (props: any) => {
    const { ComposedClass } = props
    const history = useHistory()

    const handleOnIdle = (event: any) => {
        // SHOW YOUR MODAL HERE AND LAGOUT
        console.log('user is idle', event)
        console.log('last active', getLastActiveTime())
        history.push("/lagout")
    }

    const {getLastActiveTime } = useIdleTimer({
        timeout: 1000 * 60 * SESSION_IDEL_MINUTES,
        onIdle: handleOnIdle,
        debounce: 500,
    })

    return <ComposedClass />
}

export default AutoLagoutTimer;

对于所有受保护的路由,您可以像下面这样使用此组件进行 Package

<Route path={"/dashboard"}>
        <AutoLagoutTimer ComposedClass={Dashboard} />
    </Route>
ufj5ltwl

ufj5ltwl3#

下面是模态怠速警告的完整示例。
假设你正在使用reactstrap进行样式化,这里是一个例子。

import React, {useState, useEffect} from 'react';
import {Modal, ModalHeader, ModalBody, ModalFooter} from 'reactstrap';

function IdleMonitor()
{
  //Modal
  const [idleModal, setIdleModal] = useState(false);

  let idleTimeout = 1000 * 60 * 1;  //1 minute
  let idleLogout = 1000 * 60 * 2; //2 Minutes
  let idleEvent; 
  let idleLogoutEvent;

  /**
   * Add any other events listeners here
   */
  const events = [
    'mousemove',
    'click',
    'keypress'
  ];

  /**
   * @method sessionTimeout
   * This function is called with each event listener to set a timeout or clear a timeout.
   */
  const sessionTimeout = () => 
  {  
    if(!!idleEvent) clearTimeout(idleEvent);
    if(!!idleLogoutEvent) clearTimeout(idleLogoutEvent);

    idleEvent = setTimeout(() => setIdleModal(true), idleTimeout); //show session warning modal.
    idleLogoutEvent = setTimeout(() => logOut, idleLogout); //Call logged out on session expire.
  };

  /**
   * @method extendSession
   * This function will extend current user session.
   */
  const extendSession = () => 
  {
    console.log('user wants to stay logged in');
  }

  /**
   * @method logOut
   * This function will destroy current user session.
   */
  const logOut = () => 
  {
    console.log('logging out');
  }

  useEffect(() => 
  {
    for (let e in events) 
    {
      window.addEventListener(events[e], sessionTimeout);
    }

    return () => 
    {
      for(let e in events)
      {
        window.removeEventListener(events[e], sessionTimeout);
      }
    }
  },[]);

    return (

      <Modal isOpen={idleModal} toggle={() => setIdleModal(false)}>
        <ModalHeader toggle={() => setIdleModal(false)}>
            Session expire warning
        </ModalHeader>
        <ModalBody>
            your session will expire in {idleLogout / 60 / 1000} minutes. Do you want to extend the session?
        </ModalBody>
        <ModalFooter>
          <button className="btn btn-info"  onClick={()=> logOut()}>Logout</button>
          <button className="btn btn-success" onClick={()=> extendSession()}>Extend session</button>
        
        </ModalFooter>
      </Modal>
    )

  }

export default IdleMonitor;

在创建了这个类之后,你可以简单地从任何地方调用它,就像这样

<IdleMonitor/>

别忘了进口。

相关问题