Dealing with a Zend Authentication Failure Using an AJAX Request

I am currently using the Zend Controller plugin for authentication. It probably looks like this:

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());
            }
        }
    }
}

I'm not sure if this is the best way to handle an AJAX request that is not authenticated. Tell me, someone is trying to log in using the form submitted via AJAX, how should Javascript know that you really need to redirect the user to the login page?

My first thought is to check if the request is an AJAX request and then a JSON echo object with details about where to redirect the user: Javascript can then look for a specific property in the returned JSON object and use this as the URL for "location. href "user.

There are two problems with the above:

  • , - , , JSON, AJAX.
  • Zend- -.

-, ?

,

.

+5
1

json- .

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());
       }
    }
}

- :

{"auth":false,"url":"http:\/\/foo.bar\/login"}
+1

All Articles