Question

I have: SPA application, which means it can even do offline-processing. It means my app ask server only if it needs some additional info or wants to save something.

I holds user connections in Guava Cache with expired policy. It means I shouldn't worry about session destruction after timeout.

Crucial point: Each time user do some request I reset timeout to avoid session destruction. When user is inactive during some specified period, Guava Cache just throw his session away.

Problem: The problem is linked with SPA. With SPA, if user don't send any requests it doesn't mean that he's inactive.

I want: Automatically close user session an log out him after timeout.

Question: How can I know if user is active or not in SPA?

Was it helpful?

Solution

The first what comes in mind - is to use something like expired cache on server-side, and send each e.g. 5 minutes keep_alive request from the client to indicate that client is active. But it seems to be overengineering. Plus we clog the server with hundreds of unnecessary requests.

So I found (no mean to be pioneer) the better solution: client calculate an inactive period by his own, and send the appropriate request if inactive_period is greater than timeout.

activityListener = {

    timeout: null,

    activityHandler: function () {
        $.cookie('last_activity', new Date().getTime());
    },

    initialize: function (timeout) {
        this.timeout = timeout;
        $.cookie('last_activity', new Date().getTime());
        if ($.cookie('do_activity_check') != true) {
            $.cookie('do_activity_check', true);
            setInterval(this.activityCheck, timeout / 2);
        }
        addEventListener('click', this.activityHandler, false);
        addEventListener('scroll', this.activityHandler, false);
    },

    handleTimeout: function () {
        if (oLoginPage.authorities != null) {
            le.send({
                "@class": "UserRequest$Logout",
                "id": "UserRequest.Logout"
            });
        }
    },

    activityCheck: function () {
        var after_last_activity_ms = new Date().getTime() - $.cookie('last_activity');
        if (after_last_activity_ms > activityListener.timeout) activityListener.handleTimeout();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top