Check if signed user have a specific role in Symfony 2 & 3

Check if signed user have a specific role in Symfony 2 & 3

Symfony's security system is incredibly powerful and it allows you to add roles to your users. When a user logs in, they receive a set of roles (e.g. ROLE_ADMIN), These are probably stored on a column in your table (or in memory) and declared in the security.yml file of your project.

In the view (Twig)

In the view, if you use twig as your prefered template engine, you can use the following code to check if the session have the required roles.

{#
   We will use the is_granted twig function, this will return a boolean according to the statement, to check a specific role use :
#}

{% if is_granted('ROLE_ADMIN') %}
  Do something here
{%endif%}

For example, if you want to create a sign in and sign out menu for all the users (all roles), you'll be able create one so :

{% if is_granted("IS_AUTHENTICATED_REMEMBERED") %}
     <a href="{{ path('fos_user_security_logout') }}">
         Sign out
     </a>
{% else %}
     <a href="{{ path('fos_user_security_login') }}">Sign in</a>
{% endif %}

In the controller (.php files)

To check an active user role in the controllers, we will use the isGranted method, which can be retrieved from the security context of Symfony. Use the following code to check for a role in php.

// If you are in a symfony controller
if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
   // Execute some php code here
}

// Or if you are using a symfony extension (and you are injecting the container)

//Note that you need to have a variable defined as the symfony container (for example in a symfony extension you send it as parameter)
$container = someMethodThatRetrievesTheSymfonyContainer();

if($this->container->get('security.context')->isGranted('ROLE_ADMIN')){
  //Execute some php code
}


// If you just want to prevent that a user without a specific role enter to some area, you can use the latest shortcut in the controllers:

$this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page :( you are not admin');

If user have role in the database

If the user is not active (logged) and you need to check if the user have a specific role from the database, you can use this function to figure it out.

The function expects as first parameter the id of the user and as second parameter the name of the role , remember that your user structure may be different and you need to change the way of search for example, search by other field and not by id.

/**
 * @string|int $id 
 * @string $role
 */
public function userHasRole($id ,$role) {
    // Entity manager
    $em= $this->getDoctrine()->getManager()
    $qb = $em->createQueryBuilder();
        
    $qb->select('u')
            ->from('userBundle:User', 'u') // Change this to the name of your bundle and the name of your mapped user Entity
            ->where('u.id = :user') 
            ->andWhere('u.roles LIKE :roles')
            ->setParameter('user', $id)
            ->setParameter('roles', '%"' . $role . '"%');
        
    $user = $qb->getQuery()->getResult();
        
    if(count($user) >= 1){
       return true;
    }else{
       return false;
    }
}

// Then you can use it like :

$devId = 123;

if(userHasRole($devId,"ROLE_DEVELOPER")){
 // Send mail to DEVELOPERS
}
Become a more social person