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:
Is there anyone out there who's hit upon and solved this very scenario?
Thanks very much,
James.
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With