Check server-side response (session validity/isset)

Check server-side response (session validity/isset)

TronikTronik Posts: 120Questions: 27Answers: 1

I saw another thread about this but it had no answer.

Im using php sessions server-side to grant / deny users access to certain fields.
Problem occurs when the user has been inactive for some time (24mins i think session lifetime), come back to do a table search which will result in a "invalid json response" due to the session variables not set in server-side script.

On other pages I do a header location redirect to login page, and I would like to do the same in this case.

I was thinking I could check server side for active session and if not then return a 0 / false or whatever, return that to client and if so do a window.location redirect.
But how can I check this in client side before datables tries to render the table?

Answers

  • rf1234rf1234 Posts: 2,806Questions: 85Answers: 406
    edited January 2023

    But how can I check this in client side before datables tries to render the table?

    You could make a synchronous ajax call to check - or a promise.

    I found this in my code somewhere ...

    $.ajax({
        type: "POST",
        url: 'actions.php?action=checkValidLogin',
        async: false,
        data: {
               ....
        },
        dataType: "json",
        success: function(data) {
            if (data.validLogin) {
                loginSettings(data);
            } else {
                notLoggedInSettings();
            }
        }
    });
    
  • TronikTronik Posts: 120Questions: 27Answers: 1

    I could do that, but then I need to execute that with every search/edit?
    Just seems a bit unnecessary instead of checking valid sessions server side which is done anyway, and send back a false response

  • allanallan Posts: 61,669Questions: 1Answers: 10,096 Site admin

    Have the server return valid JSON such as:

    {
      "data" : [],
      "sessionExpired": true
    }
    

    And listen for xhr which will check for the sessionExpired and perform whatever action you need (reload to a login page for example).

    Allan

  • TronikTronik Posts: 120Questions: 27Answers: 1

    Yes, I found another thread dealing with the same issue which was solved with xhr event.

    This is my solution

    in PHP

    session_start();
    
    if (!isset($_SESSION['user']))
    {
        $data['code'] = 401;
        $data['data'] = [];
        $data['message'] = 'Session expired';
        echo json_encode($data);
        die();
    }
    

    And on client

    $("#table").on('xhr.dt', function ( e, settings, json, xhr ) {
        if (json.code === 401) 
        {           
            location.href = '../login/'
        }
        else
            console.log('valid session')        
        });
    
Sign In or Register to comment.