Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with Zend Authentication failure via AJAX request

I'm currently using a Zend Controller Plugin to check authentication. The following probably looks familiar:

class SF_Plugin_Member_Auth extends Zend_Controller_Plugin_Abstract {

    public function preDispatch(Zend_Controller_Request_Abstract $request) {

        if (!SF_Auth::getInstance('Member')->hasIdentity()) {
            if ($request->getControllerName() !== 'auth' && $request->getControllerName() !== 'error') {
                $r = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
                $r->gotoSimpleAndExit('login', 'auth', $request->getModuleName());
            }
        }
    }
}

What I'm unsure of is the best way of dealing with an AJAX request that isn't authenticated. So say someone tries to login using a form that's sent over AJAX, how should the Javascript know that it actually needs to redirect the user to the login page?

My first thought is to check to see if the request is an AJAX request, and then echo out a JSON object with details of where to redirect the user to - the Javascript can then look for a particular property in the returned JSON object and use that as the URL to "location.href" the user to.

There are two problems with the above:

  1. I'm not sure how to stop the request from being dispatched - all I want to do is echo out a simple JSON string if it's an AJAX request.
  2. It doesn't feel like a Zend-like way of doing things.

Is there anyone out there who's hit upon and solved this very scenario?

Thanks very much,

James.

like image 372
James Avatar asked Nov 15 '22 08:11

James


1 Answers

You can set your json values in the response object and gracefully stop the request with the redirector.

if (!SF_Auth::getInstance('Member')->hasIdentity()) {
    if ($request->getControllerName() !== 'auth' && $request->getControllerName() !== 'error') {
        if ($request->isXmlHttpRequest()) {
            $json = Zend_Json::encode(array('auth' => false, 'url' => 'http://foo.bar/login'));

            // Prepare response
            $this->getResponse()
                 ->setHttpResponseCode(200) // Or maybe HTTP Status 401 Unauthorized
                 ->setBody($json)
                 ->sendResponse();

            // redirectAndExit() cleans up, sends the headers and stopts the script
            Zend_Controller_Action_HelperBroker::getStaticHelper('redirector')->redirectAndExit();
        } else {        
            $r = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
            $r->gotoSimpleAndExit('login', 'auth', $request->getModuleName());
       }
    }
}

This will output something like this:

{"auth":false,"url":"http:\/\/foo.bar\/login"}
like image 137
Benjamin Cremer Avatar answered Dec 22 '22 06:12

Benjamin Cremer