0

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

iamjc015
  • 2,127
  • 6
  • 25
  • 61

1 Answers1

0

You can try the following:

$user= $this->get('security.context')->getToken()->getUser();
$userId = $user->getId();

or

$user = $this->getUser();
$userId = $user->getId();

or, using FOSUserBundle

$userManager = $this->container->get('fos_user.user_manager');
$user = $userManager->findUserByUsername($this->container
          ->get('security.context')->getToken()->getUser());
$userId = $user->getId();

Then do the role check.

The error you get, where you get a string instead of an object, is because the base User class has a __toString() method where it returns the username.

See this answer https://stackoverflow.com/a/12663880/5043552 for a similar question.

Also your first check, using ->hasRole() is not recommended, see below an excerpt from the User Model of FOSUserBundle

/**
 * Never use this to check if this user has access to anything!
 *
 * Use the SecurityContext, or an implementation of AccessDecisionManager
 * instead, e.g.
 *
 *         $securityContext->isGranted('ROLE_USER');
 *
 */
public function hasRole($role)

Your second role check should work just fine.

Community
  • 1
  • 1
Alex Andrei
  • 7,315
  • 3
  • 28
  • 42