2012-01-02 174 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