Topic: Session check for all requests

Hi all,

the user BigBadaBoom wrote a nice example for checking session on each request. Here's a short summary:


You certainly know that $xajax->register() supports different 'types' of functions... like XAJAX_FUNCTION, XAJAX_CALLABLE_OBJECT and so on... There's also one magic constant for registering Events "XAJAX_PROCESSING_EVENT". In combination with XAJAX_PROCESSING_EVENT_BEFORE, xajax will always call a certain (xajax) function before it processes the requested function(s). This way, you can add a session check before the real processing starts and abort the further processing if needed (for instance when the session is invalid).

// register the function "loginstatus" as PROCESSING_EVENT before the real processing starts
$xajax->register(XAJAX_PROCESSING_EVENT, XAJAX_PROCESSING_EVENT_BEFORE, "loginstatus");
 
// the function which is called before processing
function loginstatus(&$callnext)
{
   
    // Check if session is valid or not
    if (!$GLOBALS['user']->isLoggedIn())
    {
      // If the session is not valid, set callnext to false in order to skip the further request processing
           $callnext = array(false);
        
           // create a new xajaxResponse(); object and redirect the user to the login page
           $objResponse = new xajaxResponse();
        $objResponse->loadCommands(myLogoutFunction());
        // Return the response object with instructions
        return $objResponse;
       }
}

Re: Session check for all requests

Hi q_no,

I tried this and works great for me, except that I had to move the return on the loginstatus function outside the "if", otherwise I kept getting <cmd cmd="dbg">SAn invalid response was returned while processing this request.</cmd>.  Always returning the xajaxResponse object works well for me.  I added the myLogoutFunction implementation, it might help someone else saving some extra time checking the docs for the loadCommands method, cheers.

function myLogoutFunction() {
  $objResponse = new xajaxResponse();
  $sURL = Configuration::APP_URL."/login.php?logout=1";
  $objResponse->redirect($sURL);
  return $objResponse;
}

// the function which is called before processing
function loginstatus(&$callnext) {
// create a new xajaxResponse(); object and redirect the user to the login page
  $objResponse = new xajaxResponse();
  
  // Check if session is valid or not
  if (!$GLOBALS['user']->isLoggedIn()) {
  // If the session is not valid, set callnext to false in order to skip the further request processing
    $callnext = array(false);
    
    $objResponse->loadCommands(myLogoutFunction());
  }
  // Return the response object with instructions
  return $objResponse;
}

--
I'm using xajax 0.5 final