Silex: redirect admin to admin-home path after login

放肆的年华 提交于 2019-12-08 03:17:19

问题


How in Silex redirect admin (ROLE_ADMIN) to /admin page after successful login and user (ROLE_USER) to / page after successful login? My config so far:

$app['security.firewalls'] = array(
    'login' => array(
    'pattern' => '^/login$',
     ),
     'secured' => array(
        'pattern' => '^.*$',
        'form' => array('login_path' => '/login', 'check_path' => '/login_check'),
        'logout' => array('logout_path' => '/logout'),
        'users' => $app->share(function() use ($app) {
                 return new App\User\UserProvider($app['db']);
        }),
      ),
);
$app['security.access_rules'] = array(
array('^/admin', 'ROLE_ADMIN', 'http'),
    array('^.*$', 'ROLE_USER'),
);

Thx in advance


回答1:


I think there are a few ways to do this - I would recommend adding a new controller for /login/redirect and then sending people there after login. The controller can then perform the logic for where to send users based on their roles.

class LoginRedirect implements ControllerProviderInterface {

    public function connect(Application $app) {
        $controller = $app['controllers_factory'];
        $controller->get('/', array($this, 'index'))->bind('login-redirect');
        return $controller;
    }

    public function index(Application $app) {

        if ($app['security']->isGranted('ROLE_ADMIN')) {
            return $app->redirect($app['url_generator']->generate('admin-home'));
        }

        return $app->redirect($app['url_generator']->generate('non-admin-home'));
    }

}

Add a route for it:

$app->mount('/login/redirect', new Controller\LoginRedirect());

And then in your security firewall settings add the options in the form section to use this route as the default target path - i.e. where all users are redirected to after login. Note that with this setting, you will loose the feature where users are redirected to the HTTP referer.

...
    'form' => array(
        'login_path' => '/login',
        'check_path' => '/login_check',
        'always_use_default_target_path' => true,
        'default_target_path' => '/login/redirect'
    ),
...


来源:https://stackoverflow.com/questions/25594243/silex-redirect-admin-to-admin-home-path-after-login

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