I am using FosUserBundle in Symfony 3.4. I want to redirect users based on their roles. For example, if the role is Client, the user will be redirected to the clients page. If the user is an Admin, then the user will be redirected to the admin dashboard page. How can I do this with FosUserBundle?
Asked
Active
Viewed 1,186 times
1 Answers
1
Redirect them both to a controller named indexAction() and Redirect them in the controller based on the role. Something like this:
/**
* @Route("/secure-area", name="homepage")
*/
public function indexAction()
{
if($this->getUser()->hasRole('ROLE_ADMIN'))
return $this->redirect($this->generateUrl('admin_area'));
elseif($this->getUser()->hasRole('ROLE_USER'))
return $this->redirect($this->generateUrl('client_area'));
throw new \Exception(AccessDeniedException::class);
}
EDIT: You should set the default_target_path to the path above
Puya Sarmidani
- 1,226
- 9
- 26
-
Yes it does. take a look at https://stackoverflow.com/questions/18783381/fosuserbundle-redirect-from-login-page-after-logged-in – Puya Sarmidani Apr 15 '19 at 13:22
-
i have tried your solution i changed the roles attribute of a random user in the fos_user table in my database and tried to login with it but i got "Authentication request could not be processed due to a system problem" due to it's role – CoderTn Apr 15 '19 at 15:28
-
1In Symfony 4 I had to do this like below: `if ( in_array( 'ROLE_ADMIN', $this->getUser()->getRoles(), true) ) ...` – Harkály Gergő Nov 22 '21 at 10:33