Cakephp3在成功登录用户

时间:2015-08-04 05:47:58

标签: php cakephp cakephp-3.0

我在蛋糕php3中有一个小应用程序,它有一个前端和一个管理员后端。我正在尝试保护管理员后端中的控制器以在用户继续操作之前要求身份验证但是在关注cakephp3 http://book.cakephp.org/3.0/en/controllers/components/authentication.html上的教程之后,我发现$ this-> Auth-> user()返回null并且用户会立即重定向回登录页面。

我在/src/Controller/Admin/UsersController.php中的登录功能

public function login() {
     if ($this->request->is ( 'post' )) {
        $user = $this->Auth->identify ();
        if ($user) {
                die(var_dump($user));// returns the user details correctly
                $this->Auth->setUser ( $user );             
                return $this->redirect($this->Auth->redirectUrl()); 
        }            
        $this->Flash->error ( __ ( 'Invalid username or password, try again' ) );

     }          
}



public function beforeFilter(Event $event) {
    parent::beforeFilter ( $event );
    $this->Auth->allow ( [  'logout'    ] );
}

在我的路线中我有

 Router::prefix ( 'admin', function ($routes) {
$routes->connect ( '/', [ 
        'controller' => 'Admin',
        'action' => 'dashboard' 
]);
$routes->connect ( '/pages/*', [
        'controller' => 'Admin',
        'action' => 'dashboard'
] );

$routes->fallbacks ( 'InflectedRoute' );

});

在我的APPController中,我有这个

public function initialize() {
    $this->loadComponent ( 'Flash' );
    // $this->loadComponent('Auth');
    $this->loadComponent ( 'Auth', [ 
            'authorize' => ['Controller'], // Added this line
            'loginRedirect' => [ 
                    'controller' => 'Admin',
                    'action' => 'dashboard' 
            ],
            'logoutRedirect' => [ 
                    'controller' => 'Users',
                    'action' => 'login' 
            ],
            'authenticate'=> [
            'Form' => [
                    'fields' => [
                            'username' => 'email',
                            'password' => 'password'
                    ]
                    ]
                ]
    ] );


}
public function beforeFilter(Event $event) {

    if ((isset ( $this->request->prefix ) && ($this->request->prefix === 'admin'))) {
        $this->layout = 'admin';
    }


    //exit(var_dump($this->Auth->user()));

    if ($this->request->prefix !== 'admin') {
        $this->Auth->allow (); //allow all other parts of the site to work
    }



}

public function isAuthorized($user) {

    if (isset ( $user ['role'] ) && $user ['role'] === 'admin') {
        return true;
    }

    // Default deny
    return false;
}

在我的/src/COntroller/Admin/AdminController.php中,我有这个;

    public function beforeFilter(Event $event) {
    parent::beforeFilter ( $event );

}

public function index() {

    return $this -> render('TestView/index');

}

public function dashboard(){

}

我得到的任何帮助都值得赞赏。我已经破解并在网上搜索了几天了。我是cakephp的新手,但我相信我一定做错了。如果需要,我可以提供更多的代码见解。提前谢谢。

0 个答案:

没有答案