I am having a problem on getting roles of a user that has logged in. I tried to override the SecurityController and have the following code :
public function loginAction(Request $request)
{
$userManager = $this->get('fos_user.user_manager');
$userId = $this->get('security.context')->getToken()->getUser()->getId();
$user = $userManager->findUserBy(array('id'=>$userId));
if( $user->hasRole('ROLE_ADMIN') && $this->get('security.context')->isGranted('IS_AUTHENTICATED_ANONYMOUSLY') ){
return new RedirectResponse($this->generateUrl('adminpage'));
}
if($user->hasRole('ROLE_ACCOUNTING') && $this->get('security.context')->isGranted('IS_AUTHENTICATED_ANONYMOUSLY') ){
return new RedirectResponse($this->generateUrl('accountingpage'));
}
....
The problem here is that getId() throws an error like so:
Error: Call to a member function getId() on string
I tried another approach with the following code like so:
if($this->get('security.context')->isGranted('ROLE_ADMIN') && $this->get('security.context')->isGranted('IS_AUTHENTICATED_ANONYMOUSLY') ){
return new RedirectResponse($this->generateUrl('adminpage'));
}
if($this->get('security.context')->isGranted('ROLE_ACCOUNTING') && $this->get('security.context')->isGranted('IS_AUTHENTICATED_ANONYMOUSLY') ){
return new RedirectResponse($this->generateUrl('accountingpage'));
}
But it always evaluates to ROLE_ADMIN even I logged in a user with ROLE_ACCOUNTING thus giving me a Access Denied message.
How can I fix this?
Thank you very much!
PS. I used Symfony 2.7