2010-08-02 68 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"}