cakePHP- setting loginRedirect from beforeFilter f

2019-08-22 07:40发布

I am facing this weird problem. I am trying to change the default loginRedirect of the admin role from that of normal user.

U have the auth key in the AppController's component variable set up as follows :

'Auth' => array(
            'loginRedirect' => array(  
                'controller' => 'donors',
                'action' => 'index'
            )
    )

Now in the beforeFilter callback I have this set up:

if($this->Auth->user('role') == 'admin'){
        $this->Auth->loginRedirect = array(
            'controller'=>'users',
            'action'=>'admin_index',
            'prefix'=>'admin',
            'admin'=>true
        );
}

However, this does not work and the if condition is never met. I am expecting this to run when the user logs in. If I add an else condition and repeat the same code shown above, it works and the admin is redirect to the desired page.

Can anyone instruct how I am able to do this correctly ? Thanks in advance

2条回答
叼着烟拽天下
2楼-- · 2019-08-22 08:19

If the user is not logged in, $this->Auth->user() will return null. beforeFilter() will run before any action is run, so your login() action has still not been called.

Do the redirecting after $this->Auth->login() has been called and is successful. E.g. in your UsersController::login() action (or whichever action you use to login):

if ($this->Auth->login()) {
    if($this->Auth->user('role') == 'admin') {
        $this->redirect(array(
            'controller'=>'users',
            'action'=>'admin_index',
            'prefix'=>'admin',
            'admin'=>true
        );
    }
}
查看更多
We Are One
3楼-- · 2019-08-22 08:27

Instead of $this->Auth->loginRedirect use $this->redirect( array('controller' => 'users', 'action' => 'admin_index');

Its less complicated

查看更多
登录 后发表回答