User logout when browser is closed but leave logged in when tab is closed (like old PHP apps)

When I want the behaviour that the user is logged out, when the browser closes or crashes, this was quite easy in PHP. But in meteor I searched a long time for a way to do this.

  • First thing I tried is to do some connection.onClose Magic but I have no loginToken assigned anymore when this function is called.
  • second try was to use some onunload. but that logs me out even when I reload the page or close another tab.
  • my final Idea was to simulate exactly what happens in PHP:

In PHP, I can do a

session_set_cookie_params(0);
session_start();

which sets the lifetime of the cookie to Session Only an so the cookie is present until the browser closes. As I want to have the functionality Toggelable in the user profile, I am also using a localstorage.setItem() to store if the user wants this behaviour.

some helpers:

window.setCookie = function (name,value,sec) {
    if (sec) {
        var date = new Date();
        date.setTime(date.getTime()+(sec*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

window.getCookie = function(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}

the solution:

if localStorage.getItem("logoutOnResume") == "true"
	unless getCookie("resume")
		console.log "Logging out User on Resume"
		localStorage.clear("Meteor.loginToken")
		localStorage.clear("Meteor.userId")
		localStorage.clear("Meteor.loginTokenExpires")
		Meteor.logout()

setCookie("resume","true",false)
window.localStorage.setItem("logoutOnResume", true)

We will start a little blog about the stuff we find out according to meteor:

Thanks @kellertobi for posting this. nicely done!

hi,

Im just new in meteor. And I am not quite sure where to place the code above. In my understanding it would be on the login. But I am thinking that the if statement should be run whenever user navigates to any page in the application

run the code on client sided startup.

@kellertobi is it possible to create a meteor package or perhaps an npm package for this? just a thought =)

thanks for sharing