Logging members out automatically?

I have created a members only dashboard, which works well. I would like to have the members logged out, if they close the browser or tab connecting them to the site or time out after a certain period of inactivity. Is there some way to do that?

Thanks!

I can see a few challenges here…
first you need to have a timer or some session variable so when the users first logged, the variable can store the initial logon time.
then when the timer expired (how?) or when user clicked on something after long idle time, your code checks the session variable, compared with current time to decide if time expired, then log the user out if already expired.
you will also need to do this check on each and every members only pages.
according to “wix-storage-frontend - Velo API Reference - Wix.com” “The session ends when the user closes the browser tab or window”
so the session variable thing should work, but not sure about how to do timer.

Hope this helps

this post talked about timer, might be helpful? https://www.wix.com/code/home/forum/questions-answers/one-time-pop-up-timer

Hmm. I was looking at wix-storage as maybe being the answer. Basically what I want to avoid is someone walking away from their computer (whether logged in at the time or not) and another user going to the site in the browser and being able to see the users pages without having to login. I have data that I don’t want unauthorized users to see.

What I’m seeing now is that if I log in to my members only dashboard, close my browser without logging out, open the browser again and go to the same page, Wix still sees me as logged in and presents the page without prompting for a login. If I can check the time of their initial login and put that in storage it might work…

What I’m trying to duplicate is the kind of functionality you see on bank websites (i.e., if you haven’t done anything in X amount of time, your session ends). Can I check for activity to keep resetting the timer? I wouldn’t want a user to just get logged out after 5 minutes (or whatever time I choose), if they are still actively using the site…

What I mean by “(whether logged in at the time or not)” is whether they have logged in and closed their browser without logging out or if they have left it open logged in… I hope that makes it clearer.

You can check the session with wix-storage . From the API description:

Session — Data in session storage is available while the user’s web session is active. The session ends when the user closes the browser tab or window. When the session ends, all the data in session storage is lost. Reloading or restoring the page does not affect session storage data.

So, we can take advantage of the behavior of session storage…

When the user logs in, store a session value like this:

session.setItem("active", "true");

When the page is closed, the session values (including the active session value) are cleared.

When opening the page in the browser, check for this value. In the onReady() routine for the page, get the active session value:

let value = session.getItem("active");

If this value is null or undefined, then you can forcibly logout the user.

I hope this helps.

Hy Yisrael, there’s a way to observe the user inactivity (or on PC or in window site browser) ?
In this way you could get automatically logged out by the pc after a certain time period.

I’m not aware of a way to do this in Wix Code. Feel free to post a Feature Request .

Hi gaspar.al,
to reset the timer on every action you will need a trigger setup in every page/button/link or something like that. should be easier if just use the session variable.

you also need to balance between user friendliness and security, as you wouldn’t want to piss off your users by kicking them out too often or make your site so secured that’s it’s hard/annoying to use…

And I think it’s going to be very difficult to enforce/control/convince users to lock their machine or start screen saver when machine not in use for over X minutes. Normally most corporates or users who have strong sense of privacy/security will do that or have some sort of company policy/Windows AD group policy to enforce that. For other users…well, I won’t be surprise when some news report shows in certain police departments, after been enforced to use strong password, people just write down the password on a post-it note and stick it on the screen… Really not much you can do about that other than have a well written “terms and conditions” and/or “privacy statements” to legally protect yourself against users who have no knowledge/awareness about security…

Hi,

I was able to get the session variable to do as I wanted.  I added this to the beginning of my onReady() function handling the button presentation to my members: 
if (wixUsers.currentUser.loggedIn &&
		!session.getItem('isLoggedInThisSession')) {
		wixLocation.to('/');
		return wixUsers.logout();
	}

And on the “then” side of my wixUsers.promptLogin, I added this:

session.setItem('isLoggedInThisSession', 'yes'); //set session variable

Now, every new session starts with the session variable unset; so the user is logged out, if it is a new session and must login again to reset the session variable. Good. I wanted that.

I then wanted to be able to timeout and logout after X amount of time, so I placed this immediately after I set the session variable:

let timeoutID = setTimeout(wixUsers.logout(), 60000);

Mind you, I’m just testing here; if I can get this to work, I would set a much longer time and maybe reset when they clicked on certain buttons (hence establishing the timeoutID variable). Unfortunately, the setTimeout seems to do exactly nothing. As soon as I login, I immediately get logged out as if I had no timer set at all. What am I missing here? I was trying to follow what was being done here:

https://www.wix.com/code/home/forum/questions-answers/deactivate-function

and here:

Do I need to set a “guard” as described in the Wix forum post, or what? I tried putting the setTimeOut in a separate function and called it after I set the session variable, but then it doesn’t do anything at all… (FYI, I put all of this code on the site side as my buttons are all in my header and available site wide).

Thanks!

Try this:

setTimeout(() => {
    console.log("logout");
    wixUsers.logout();
}, 60000);


I didn’t try this in the Site side (just on Page) but I don’t see any reason it shouldn’t work.

Good luck,

Yisrael

I tried it, but without any luck. Here’s what I have on my site side now. The behavior at the moment is that the session variable works, but the page behaves as if there is no timer at all. I tried using those two unused functions at the end (startTimer and clearOut), but they didn’t do anything either. The only thing that has actually caused a logout (unfortunately immediately) was to place “let timeoutID = setTimeout(wixUsers.logout(), 60000);” where I placed the code you suggested (in bold below), which is immediately after I set the session variable.

import wixUsers from 'wix-users';
import wixData from 'wix-data';
import wixLocation from 'wix-location';
import {session} from 'wix-storage';

$w.onReady(() => {
	// We check if the user is logged in from another session, send then to the home page, and log them out
	if (wixUsers.currentUser.loggedIn &&
		!session.getItem('isLoggedInThisSession')) {
		//wixLocation.to('/');
		return wixUsers.logout().then(() => {
			wixLocation.to('/');
		});
	}

	if (wixUsers.currentUser.loggedIn) {
		$w("#button8").label = "Logout";
		$w("#button9").show();
		$w("#button14").show();

	} else {
		$w("#button8").label = "Login";
		$w("#button9").hide();
		$w("#button14").hide();
	}
});

export function button8_onclick() {
	// user is logged in
	if (wixUsers.currentUser.loggedIn) {
		// log the user out
		wixUsers.logout()
			.then(() => {
				// update buttons accordingly
				$w("#button8").label = "Login";
				$w("#button9").hide();
				$w("#button14").hide();
				wixLocation.to('/');
			});
	}
	// user is logged out
	else {
		let userId;
		let userEmail;

		// prompt the user to log in 
		wixUsers.promptLogin({
				"mode": "login"
			})
			.then((user) => {
				session.setItem('isLoggedInThisSession', 'yes'); //set session variable
				setTimeout(() => {
					console.log("logout");
					wixUsers.logout();
				}, 6000);
				userId = user.id;
				return user.getEmail();
			})
			.then((email) => {
				// check if there is an item for the user in the collection
				userEmail = email;
				return wixData.query("Test")
					.eq("_id", userId)
					.find();
			})
			.then((results) => {
				// if an item for the user is not found
				if (results.items.length === 0) {
					// create an item
					const toInsert = {
						"_id": userId,
						"email": userEmail
					};
					// add the item to the collection
					wixData.insert("Test", toInsert)
						.catch((err) => {
							console.log(err);
						});
				}
				// update buttons accordingly
				$w("#button8").label = "Logout";
				$w("#button9").show();
				$w("#button14").show();
				wixLocation.to(`/Clients/Update/${wixUsers.currentUser.id}`);
			})
			.catch((err) => {
				console.log(err);
			});
	}
}

export function button9_onclick() {
	wixLocation.to(`/Clients/Update/${wixUsers.currentUser.id}`);
}

export function clearOut() {
	$w("#button8").label = "Login";
	$w("#button9").hide();
	$w("#button14").hide();
	wixLocation.to('/');
	return wixUsers.logout();
}

export function startTimer() {
	//let timeoutID = setTimeout(wixUsers.logout(), 6000);
	/*setTimeout(() => {
		wixUsers.logout();
	}, 6000);*/
	setTimeout(() => {
		console.log("logout");
		wixUsers.logout();
	}, 6000);

}

Any thoughts, Yisrael?

Thanks!

well, I have found one rather draconian and obnoxious way to do sort of what I want. Embed this html in the header:

<script> var timer = null;
function auto_logout()
{
     window.top.close();
} </script>  <body onload="timer = setTimeout('auto_logout()',XXXXXX);">

XXXXXX is the time out in milliseconds. This closes the window after that amount of time elapses. The session variable ensures that, if the user returns to the page, they will have to login again… Like I said, rather obnoxious…

If I could somehow import wixUsers and wixlocation into the embedded html, I’d be able to log the user out and return them to the home page, but I don’t see a way to do that since those libraries need to be in the front end code…

Anyone else have some ideas?

–Al

Please anyone ccan help me?

How can i avoid one member are logged at 2 ou more PCs at same time??

Many thanks

Yah i need something like this, when 1 computer is log on , all others session log out automatically

hey, im still looking for something that works fro a time out function? has anyone found a way to set this up so that after the person is inactive they are kicked out of the members area and have to log back in.

This seems to be working fine. But is it possible to store this code as a file and import this into every Onready() function on every page?

@s-krishnan-kannaiyan You can create a file in the Public section of your site where you can keep functions to be called from wherever you want in your client code.

I guess an alternative to do the auto-logout (and not logout when closing the browser) would be to store a local variable instead of session. Such local variable would store the current time from when the user logged in (or even the future time for when the user should be auto-logged out). Then in the site’s onReady() or within a SetTimeout function you would compare the local variable against the current time and logout the user if the condition is met.