cakePHP- setting loginRedirect from beforeFilter for admin role

五迷三道 提交于 2019-12-25 02:36:10

问题


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


回答1:


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
        );
    }
}



回答2:


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

Its less complicated



来源:https://stackoverflow.com/questions/21734175/cakephp-setting-loginredirect-from-beforefilter-for-admin-role

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!