Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to implement Auto Logout client side in react

This tutorial explains how to implement auto logout system in client system in react application. The Auto Logout system is implemented by most of the web application nowadays, that helps users to protect their secure data from unauthorized access in case they forgot to logout their web application sessions.

So In this tutorial, we are going to share React source code to implement auto logout system. In this example we are maintaining two timestamp for user session.
  • First timestamp helps to notify alert message when user is inactive for 16 seconds.
  • Second timestamp helps to initiate logout module when user is inactive for 30 seconds.

Auto Logout System When User Is Inactive In React :

Lets see the below example, that helps to build more understanding on this.

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
constructor
(props) {
super(props);

this.state = { logginStatus: true };
this.events = [
"load",
"mousemove",
"mousedown",
"click",
"scroll",
"keypress"
];

this.warn = this.warn.bind(this);
this.logout = this.logout.bind(this);
this.resetTimeout = this.resetTimeout.bind(this);

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

this.setTimeout();
}

clearTimeout
() {
if (this.warnTimeout) clearTimeout(this.warnTimeout);

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

setTimeout
() {
this.warnTimeout = setTimeout(this.warn, 16 * 1000);

this.logoutTimeout = setTimeout(this.logout, 30 * 1000);
}

resetTimeout
() {
this.clearTimeout();
this.setTimeout();
}

warn
() {
alert
("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.setState({ logginStatus: false });
// this.destroy(); // Cleanup
}

destroy
() {
this.clearTimeout();

for (var i in this.events) {
window
.removeEventListener(this.events[i], this.resetTimeout);
}
}
render
() {
return (
div className="App">

Session auto logout after inactivityh1>

Status :{this.state.logginStatus ? "Loggin" : "Logout"}h2>
div>
);
}
}

const rootElement = document.getElementById("root");
ReactDOM.render(App />, rootElement);

Output :
-------------------------
Check out this link : https://codesandbox.io/s/ox8o8o53oq


This is all about auto logout system in react application. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.



This post first appeared on Learn Programming, please read the originial post: here

Share the post

How to implement Auto Logout client side in react

×

Subscribe to Learn Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×