Reputation: 305
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.
Upvotes: 2
Views: 13816
Reputation: 410
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 ( ......
......
}
}
Upvotes: 0
Reputation: 3001
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.
Upvotes: 4