Andrew P. Andrew P. - 16 days ago 4
PHP Question

CakePHP 3: Different login redirection depending on user roles

I'm using CakePHP 3 and trying to change the default route after user is logged in. I want to set default route different depends on user's

role_id
.

I found a solution but it's only for CakePHP 2.
I can't use it in CakePHP 3, I can't use Session component in bootstrap.

So I tried this in my AppController

public $redirects = [
'admin' => ['controller' => 'Clients', 'action' => 'statistics'],
'user' => ['controller' => 'Clients', 'action' => 'index'],
];
public function initialize()
{
parent::initialize();
...
if ($this->Auth->user())
Configure::write('Route.default', $this->redirects[$this->Auth->user('role_id')]);
else
Configure::write('Route.default', ['controller' => 'Users', 'action' => 'login']);
Router::scope('/', function($routes) {
$routes->connect('/', Configure::read('Route.default'));
$routes->fallbacks('InflectedRoute');
});
}


My default route is

$routes->connect('/', \Cake\Core\Configure::read('Route.default'));


And I defined
Route.default
in bootstrap.php as

Configure::write('Route.default', ['controller' => 'Users', 'action' => 'login']);


But when I open the
/
page I still see the
users/login
page even if I have already logged in

So I added the redirection before
Router::scope


if (
$this->Auth->user()
&& $this->request->params['controller'] == 'Users'
&& $this->request->params['action'] == 'login'
) {
$this->redirect(Configure::read('Route.default'));
}


Could anyone help me with that?

Answer

hey i found a solution!

create an file in App\Routing\Filter like that:

  <?php
namespace App\Routing\Filter;

use Cake\Event\Event;
use Cake\Routing\DispatcherFilter;

class HFilter extends DispatcherFilter {

    public function beforeDispatch(Event $event) {
        $request = $event->data['request'];
        if (isset($request->url) && $request->url == '') {
            if ($request->session()->read('Auth.User')){
                $request->params['controller'] = 'Users';
                $request->params['action'] = 'index';
            } else { 
                $request->params['controller'] = 'Pages';
                $request->params['action'] = 'home';
            } 
        }
    }
}
?>

after add it into the bootstrap.php file without the Filter in the name like that

DispatcherFactory::add('H');
DispatcherFactory::add('Asset');
DispatcherFactory::add('Routing');
DispatcherFactory::add('ControllerFactory');
Comments