简体   繁体   中英

React user session automatic logout after one hour

I want to logout the session of the current user after one hour of his login as well as on click of a button. I tried storing the current time stamp of the user as soon as he login using his auth-token. But got confused in achieving the proper result.

Here is the code :

Get from LocalStorage:

export default function setLocalData(key, value) 
{
    var responseStatus = false;

    switch (key) 
    {
        case 'currentUser':
            const currentDateTime = new Date();
            const updateDateTime = new Date();
            const expireDateTime = new Date(updateDateTime.setHours(updateDateTime.getHours() + 2));
            const currentTimestamp = Math.floor(currentDateTime.getTime() / 1000);
            const expireTimeStamp = Math.floor(expireDateTime.getTime() / 1000);

            const initialState = {
                isLogin: true,
                loginTime: currentTimestamp,
                expirationTime: expireTimeStamp,
                userInfo: value
            };
            localStorage.setItem(key, btoa(JSON.stringify(initialState)));

            responseStatus = true;

            break;

        default:
            responseStatus = false;

            break;
    }

    return responseStatus;
}

set to LocalStorage:

export default function getLocalData(key, type='all')
{
    var responseObject = null;

    try 
    {   
        if(localStorage.getItem(key))
        {   
            var response;

                response = JSON.parse(atob(localStorage.getItem(key)));

            switch (type) 
            {
                case 'all':
                    responseObject = (response) ? response : null;

                    break;

                default:
                    responseObject = null;

                    break;
            }
        }
    } 
    catch (e) 
    {
        responseObject = null;
    }

    return responseObject;
}

This is my component file where the automatic logout function needs to trigger:

class DefaultLayout extends Component {

  componentDidMount(){
    let token = LocalData.getLocalData('currentUser');
    console.log(token);

    setTimeout(()=> {
      this.signOut();
    }, token.expirationTime);
  }


  //this is triggered on clicking on logout() button
  signOut(e) {
    e.preventDefault();
    localStorage.clear();
    this.props.history.push('/login')
  }

  render() {
    //console.log(this.props)
    return ( ......
          ......
  }
}

On console.log(token), the result achieved is:

{
   expirationTime: 1575286437
   isLogin: true
   loginTime: 1575279237
   userInfo: "eyJhbGciOiJIUz11NiIsInR5cCI6IkpXVCJ9.....
}

I am not sure if am implementing this correctly. Kindly help to figure this out.

I think the problem is here

setTimeout(()=> {
      this.signOut();
    }, token.expirationTime);

You are setting the timeout value to the expiration time. It should be an interval in milliseconds. So if you want the function to be triggered after 1 hr then the value should be 60 * 60 * 1000 or some calculation based on the expiration time stamp.

Look at this

class DefaultLayout extends Component {

  componentDidMount(){
    let token = LocalData.getLocalData('currentUser');
    console.log(token);
    if(token.expirationTime>==token.loginTime){
       this.signOut();
    }    
  }


  //this is triggered on clicking on logout() button
  signOut() {    
    localStorage.clear();
    this.props.history.push('/login')
  }

  render() {
    //console.log(this.props)
    return ( ......
          ......
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM