I have two bundles userBundle and xxxBundle. I want after authenticating a user in the user bundle to redirect it to the xxxBundle. But, depending on roles (ROLE_ADMIN and ROLE_USER), I will redirect him to two different routes (route1, route2).
I added this controller to my userBundle
class SecurityController extends Controller
{
public function loginAction()
{
if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
return $this->redirect($this->generateUrl('route1'));
}
if ($this->get('security.context')->isGranted('ROLE_USER')) {
return $this->redirect($this->generateUrl('route2'));
}
$request = $this->getRequest();
$session = $request->getSession();
// On vérifie s'il y a des erreurs d'une précédent soumission du formulaire
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
} else {
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
return $this->render('UserBundle:Security:login.html.twig', array(
// Valeur du précédent nom d'utilisateur rentré par l'internaute
'last_username' => $session->get(SecurityContext::LAST_USERNAME),
'error' => $error,
));
}
But, this does not give the appropriate result: for a correct username and password, the user is redirected to the welcome symfony page. Does anybody have an explanation for that?
I found in the symfony documentation that I can control the redirect from the login form using the hiddden field as follow:
{# src/Acme/SecurityBundle/Resources/views/Security/login.html.twig #}
{% if error %}
<div>{{ error.message }}</div>
{% endif %}
<form action="{{ path('login_check') }}" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="_username" value="{{ last_username }}" />
<label for="password">Password:</label>
<input type="password" id="password" name="_password" />
<input type="hidden" name="_target_path" value="account" />
<input type="submit" name="login" />
</form>
Question : how could I parametrise the route to be responsible for user and admin.
route1
androute2
exist? Symfony may be providing you with the welcome URL for routes that do not exist. Perhaps add some debugging (var_dump/die) to see what's going on? – Phill Sparks