2010-08-02 149 views
5

我目前使用Zend控制器插件来检查身份验证。下面可能看起来很熟悉:通过AJAX请求处理Zend身份验证失败

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

什么我不能确定的是处理未经过身份验证的AJAX请求的最佳方式。所以说有人试图使用通过AJAX发送的表单登录,Javascript应该如何知道它实际上需要将用户重定向到登录页面?

我的第一个想法是检查请求是否是一个AJAX请求,然后回显出一个JSON对象,其中包含将用户重定向到哪里的详细信息 - 然后,Javascript可以在返回的JSON中查找特定属性对象并将其用作用户所访问的“location.href”的URL。

有两个问题与上面:

  1. 我不知道如何从分派停止要求 - 所有我想要做的就是呼应了一个简单的JSON字符串,如果它是一个AJAX请求。
  2. 它不觉得像Zend一样的做事方式。

有没有人遇到过并解决了这种情况?

非常感谢,

詹姆斯。

+0

通常情况下,如果你正在做一个AJAX请求,我假设你将一些标准响应(IG:{错误:0,消息: “ok”,response:{}} - 其中'response'是来自请求的实际响应对象,'error'和'message'是服务器错误代码和消息)? – 2010-08-03 04:16:40

回答

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"}