user2879565 user2879565 - 6 months ago 27
PHP Question

Symfony redirect to login via controller

I'm in the middle of a Symfony 2.5 project.
My firewall is set to ask the autentication to every route that have /secured/ prefix.
I have different types of users ADMIN_ROLE , USER_ROLE and anonymous.
My need is to redirect each of them to a different page, if logged and to the login screen if anonymous if the try to enter on the path /web/app.php/

I've created the following route:

my_home_redirect:
pattern: /
defaults: { _controller: MyHomeBundle:Default:redirect }


And i've created the folowing controller:

public function redirectAction(){
if ($this->get('security.context')->isGranted('ROLE_ADMIN')){
$render = $this->forward('MyHomeBundle:Installation:selectInstallation', array('userId'=>$user=$this->get('security.context')->getToken()->getUser()->getId()) );
}
elseif($this->get('security.context')->isGranted('ROLE_USER')){
$render = $this->forward('MyHomeBundle:Installation:selectInstallation', array('userId'=>$user=$this->get('security.context')->getToken()->getUser()->getId()) );
}
else {
// INSERT FORWARD TO THE LOGIN SCREEN
}
return $render;
}


In the "else" of the function i shoud punt the redirect to the login screen if the user is not an admin and not an user, but the login is managed by the firwall of symfony defined in the security.yml and i have no route to that. How che redirect to the url .../login without having an explicit countroller loginAction?

Answer

In the security.yml you can specify a login_path, in example:

my_firewall:
    pattern: ^/(secured_area)/
    provider: my_provider
    anonymous: ~
    form_login:
        login_path:  my_login_path
        default_target_path: /dashboard

And in the routing.yml you can map the route as:

my_login_path:
    pattern:   /my/relative/url/for/login
    defaults:  { _controller: MySecurityBundle:Security:login }

then you can use an a normal route, in you specific case:

return $this->forward($this->generateUrl('my_login_path'));

Hope this help

Comments