【问题标题】:CakePHP Auth component redirect issueCakePHP Auth 组件重定向问题
【发布时间】:2011-02-07 20:10:05
【问题描述】:

我无法让 Auth 组件在 CakePHP 1.2.6 应用程序中执行我想要的重定向。

我有一个显示在所有页面上的登录表单,我想让用户留在他登录的页面上。例如,如果他正在查看另一个用户的个人资料,我想在登录后将他保留在那里,而不是将他重定向到 $this->Auth->loginRedirect 操作。另外,关于我的应用程序的另一件事是我没有“仅经过身份验证的访问”页面,每个人都可以访问每个页面,但是如果您已登录,您将获得其他功能。

我通过阅读documentation 了解到,我需要将autoRedirect 设置为false 才能执行login() 函数中的代码:

class UsersController extends AppController {    
    var $name = 'Users';
    var $helpers = array('Html', 'Form','Text');

    function beforeFilter() {
        $this->Auth->autoRedirect = false;
    }

    function login() {
        $this->redirect($this->referer());
    }

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

    /* [...] */
}

这目前破坏了我的身份验证。我注意到(从日志中)如果我在登录函数中保留重定向并将 autoRedirect 设置为 false,则 login() 函数中 $this->data 中的密码字段显示为空。

下面,我贴出了AppController中与Auth组件相关的内容:

public function beforeFilter() {

    $this->Auth->fields = array(
        'username' => 'email',             
        'password' => 'password'            
    );

    $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');     
    $this->Auth->loginRedirect = array('controller' => 'usercars', 'action' => 'homepage');

    $this->allowAccess();

    // build wishlist if the user is logged in
    if ($currentUser = $this->Auth->user()) {
        $wishlists = $this->buildWishlist($currentUser);
        $this->set('wishlists', $wishlists);
    }

}

private function allowAccess() {
      if(in_array($this->name, /* all my controller names */)) {
          $this->Auth->allow('*');
      }
}

我似乎无法理解我做错了什么。

【问题讨论】:

    标签: php model-view-controller authentication redirect cakephp-1.2


    【解决方案1】:

    将此代码放入您的控制器:

    function beforeFilter() {
        $this->Auth->allow('login', 'logout');
        $this->Auth->autoRedirect = false;
        parent::beforeFilter();
    }
    

    并且,为登录页面添加这个:

    function login() {
        if($this->Auth->User()) {
            $this->redirect(array('action'=>'welcome'), null, true);
        }
    }
    

    【讨论】:

      【解决方案2】:

      添加父级::beforeFilter();到用户控制器中的 beforeFilter:

      function beforeFilter() {
          $this->Auth->autoRedirect = false;
          parent::beforeFilter();
      }
      

      您还可以将重定向替换为用户控制器的登录方法:

      $this->redirect($this->Auth->redirect());
      

      Auth->redirect() 返回用户在被带到登录页面或 Auth->loginRedirect 之前登陆的 url。

      【讨论】:

        猜你喜欢
        • 2011-11-28
        • 1970-01-01
        • 2011-05-09
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多