Cakephp,修改auth-class';用户未登录时的行为


Cakephp, modify auth class's behavior when the user is not logged in

默认情况下,如果查看者未登录并试图访问被拒绝的页面,cakehp-Auth类会将其重定向到首页。

我希望服务器在发生这种情况时运行一些代码(设置一些变量和其他东西)。当Auth类由于缺乏身份验证而将用户重定向到主页时,我该如何修改它的行为。

根据你的问题,你需要指定应用程序允许的操作,然后测试身份验证,如果用户没有登录,则调用你的方法。如果你想在应用程序范围内进行,请放在AppController中。

如果用户未登录,Auth::user()将返回null。

class AppController extends Controller {
    var $components = array('Auth', 'Session');
    function beforeFilter() {
        parent::__construct();
        // Your app-wide beforeFilter code, if any
        $this->Auth->allow('index', 'view', 'register', 'whatever');
        if ($this->Auth->user() == null) {
            $this->_attemptRestricted();
        }
    }
    function _attemptRestricted() {
        // set your variables, etc...
    }
}

Auth的所有默认设置都可以根据应用程序的需要进行自定义。

有关Auth::user()的详细信息--http://book.cakephp.org/view/1264/user

关于AuthComponent的所有信息--http://book.cakephp.org/view/1250/Authentication

首先,更改Auth组件代码本身不是一个好主意,因为在更新中,您会丢失所有更改。

您应该编写自己的组件来扩展内置组件,如下所示:

// /app/controllers/components/my_auth.php
App::import('Component', 'Auth');
class MyAuthComponent extends AuthComponent {
    function redirect($url = null) {
        //have a look in the original auth-component to see how to change this behaviour
    }
}

通过这种方式,您现在可以将新组件与扩展的重定向方法一起使用。

不幸的是,您现在必须将每个$this->Auth更改为$this->MyAuth。如果你不想,你可以在你的AppController中做这样的事情:

public function constructClasses() {
    parent::constructClasses();
    $this->Auth = $this->MyAuth;
}