2012-01-02 160 views
0

剛開始學習CakePHP框架。我正在使用Auth組件,並且所有需要用戶登錄的操作都會重定向到用戶/登錄名,而不是登錄名/登錄名(我的非標準控制器)。任何人都知道我可以在哪裏更改此設置?另外,auth組件如何在多個控制器上工作?我需要在每個控制器中重新定義這種自動重定向嗎?覆蓋登錄重定向

<?php 
    class LoginController extends AppController { 

    public $name = 'Login'; 

    public $components = array('Auth'); 

    public $helpers = array('Html', 'Form'); 

    function beforeFilter() { 
      // tell Auth not to check authentication when doing the 'register' action 
      $this->Auth->allow('register'); 
      $this->Auth->userModel = 'Login'; 
    } 

    function register() { 
      if (!empty($this->data)){ 
        if ($this->Login->save($this->params['data'])) { 
          $this->flash('Your registration information was accepted. Welcome!'); 
          $this->Auth->login($this->data); 
          $this->redirect(array('action' => 'index')); 
        } else { 
          $this->flash('There was a problem with your registration', '/login/knownusers'); 
        } 
      }  

    } 

    function createprofile() { 



    } 

    function knownusers() { 
      $this->set('knownusers', $this->Login->find(
        'all', 
        array(
          'fields' => array('id','username', 'password', 'fk_profile_id'), 


          $this->redirect(array('action' => 'index')); 
        } else { 
          $this->flash('There was a problem with your registration', '/login/knownusers'); 
        } 
      }  

    } 

    function createprofile() { 



    } 

    function knownusers() { 
      $this->set('knownusers', $this->Login->find(
        'all', 
        array(
          'fields' => array('id','username', 'password', 'fk_profile_id'), 
          'order' => 'id DESC' 
        ) 
      )); 
    }  

    function login() { 
    } 

    function logout() { 
      $this->redirect($this->Auth->logout('login/login')); 
    } 

} 
?> 

回答

2

如果你的整個網站都必須受到保護,那麼你就可以在你的AppController定義Auth分量將導致這些規則適用於從該對象繼承的每個控制器(即您網站上的所有控制器)。

CakePHP Authentication Documentation概述了您所需的所有參數,以完成您正在嘗試執行的操作。您應該能夠在設置Auth組件時定義登錄重定向:

public $components = array(
    'Auth' => array(
     'loginAction' => array('controller' => 'User', 'action' => 'login') 
    ) 
); 
+0

完美,謝謝。我必須說,我很驚訝這種自定義會在應用程序目錄之外。感覺像給我打亂了核心庫。 – 2012-01-02 22:27:55

+0

這應該在app目錄中完成,無論是在您的AppController.php文件還是您的自定義控制器中。這絕對不是對lib目錄的改變! – 2012-01-02 22:31:39

1

你可以把這個聲明在您的beforeFilter()

$this->Auth->loginAction = array('admin' => false, 'controller' => 'login', 'action' => 'login'); 

而且你不需要在每一個控制器來進行定義。如果您需要執行的每個控制器的任何邏輯,我把它放在AppController中的beforeFilter()...

+0

+1使用類層次結構建議 – 2012-01-02 22:28:34