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)