2011-09-15 25 views
1

我有一個CakePHP項目,我修改了「app/config/routes.php」,以便根指向「用戶」控制器的「儀表板」操作。換句話說,這兩個網址去同一個地方:CakePHP:防止主頁上的Auth組件的「authError」消息

http://example.com/

http://example.com/users/dashboard

我有「驗證」組件在我的「應用程序」控制器設置像這樣:

class AppController extends Controller { 
    var $components = array('Auth', 'Session'); 

    function beforeFilter() { 
     $this->Auth->authorize = 'controller'; 
     $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'dashboard'); 

     if ($this->Auth->user()) { 
      $this->set('logged_in', true); 
     } 
     else { 
      $this->set('logged_in', false); 
     } 
    } 
} 

我希望如果一個未經過身份驗證的用戶直接進入http://example.com/users/dashboard,他們將被帶到登錄頁面「Auth」組件的「authError」消息顯示,但如果他們去http://example.com/,他們被帶到登錄頁面而沒有顯示「Auth」組件的「authError」消息。這可能嗎?

回答

1

我通過把下面的代碼在我的「用戶」控制的「登陸」行動解決了這個:

if ($this->Session->read('Auth.redirect') == $this->webroot && $this->Session->read('Message.auth.message') == $this->Auth->authError) { 
    $this->Session->delete('Message.auth'); 
} 
0

嗯,我不明白爲什麼有時你會顯示錯誤,爲什麼有時候不會......但你可以負擔得起創建一個isAuthorized方法並修改默認AuthComponent行爲的所有邏輯。

打開您的Auth組件並檢查方法「startup()」。在那裏,在它的最後一行,你會SE這樣的:

$this->Session->setFlash($this->authError, $this->flashElement, array(), 'auth'); 
$controller->redirect($controller->referer(), null, true); 

這是負責顯示錯誤的部分。

它之前,你會本身...

if ($this->isAuthorized($type)) { 
    return true; 
} 

所以,你可以改變你的isAuthorized方法,當你想改變這個消息。

對於(我想..)很多工作都沒有。

PS。有可能是一個更簡單的方式來不理我

+1

感謝您的建議!想想看。有人前往您的網站主頁,他們看到的第一件事是一條說「拒絕訪問」的消息。在我看來,不是很友善。 – Nick

0

一直在尋找這樣的財產以後很長一段時間!謝謝。

我不得不做出變化不大然後$this->webroot不是「/」:

if (str_replace("//","/",$this->webroot.$this->Session->read('Auth.redirect')) == $this->webroot && $this->Session->read('Message.auth.message') == $this->Auth->authError) { 
    $this->Session->delete('Message.auth'); 
} 
0

如果你真的想要阻止在主頁和簡單的重定向authError消息到登錄頁面,那麼你必須把false作爲參數的authError

class AppController extends Controller { 

    public function initialize() { 
     parent::initialize(); 

     $this->loadComponent('RequestHandler'); 
     $this->loadComponent('Flash'); 
     $this->loadComponent('Auth', [ 
      'authError' => false 
     ]); 
    } 

}