简体   繁体   中英

CodeIgniter Flexi Auth - immediately redirect user when login expires

Using the CodeIgniter Flexi Auth library, how can I, when the user session expires, immediately redirect the user to the login in page (with a message saying: "Your login has expired, please login again") instead of that only happening on page load.

I am thinking that I will need to user JavaScript and a timed function to check if the user is still logged in every couple of seconds. But how can I do that using JavaScript?

The session expiry is information which is maintained on the server. Unless you use Server-sent events , the only way to initiate the redirect will be through client action.

If you are using jQuery, and want to set up the system you described, then you can set up a loop to ping the server as follows:

var ping_timeout = 120000; // 2 Minute interval

function checkSession() {
    $.get('/session/check/URL?t=' + Math.random(), {}, function(response) {
         // ... interpret the server response
         if (session_active) {  // Still active so check again later
             setTimeout(checkSession, ping_timeout);
         }
         else {
             window.location = '/login/url';
         } 
    });
}

setTimeout(checkSession, ping_timeout);

The t parameter is set to a random value to avoid the browser cacheing the response.

A problem with this scheme is that your server will be hit by these requests by every user every ping_timeout milliseconds. Realizing that the server knows when the session is expected to expire, we can modify the logic so that instead of simply answering true or false , the server can tell the client to check again when the server thinks the session will have expired.

Implementing this simply requires changing the logic so that the server responds with the number of milliseconds until expiry. The inner function will then be something like:

function processResponse(response) {
    var session_expiry = parseInt(response);
    if (session_expiry > 0) {
        setTimeout(checkSession, session_expiry);
    }
    else {
        window.location = '/login/url';
    }
}

Now, in the ideal case there would only be two AJAX requests per session:

  1. get the expiry time
  2. to check whether the session has really expired and then make the user log in again

We do a check before renewing the session because a different AJAX request or other server-side event might have extended this, depending on your application logic. We can reduce this to only one request, if when the page is loaded, the expected session expiry time is loaded along with it in a hidden input field or something. Of course there is plenty of other code you'll have to put in for errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM