To avoid me 403 errors when a user tries to access a forbidden area and avoid user sign in into that area I need to prevent users from logging if do not have the proper credentials.
Let me explain a little better, suppose I'm the X
user ROLE_USER
, user X
can access the frontend but should not be able to log into the backend, just as we have the user Y
and ROLE_ADMIN
, user Y
could log into the backend but not in the frontend, do understand me? How I can accomplish this?
lets assume that I'm user Adam with role 'ROLE_ADMIN'. I can't login to frontend.
You should simple add this code to your controllers:
if( $this->get('security.context')->isGranted('YOUR ROLE') )
return new Response('yea!');
So, If you want to secure BackendController and let to login users with 'ROLE_ADMIN' you should add this code:
if( $this->get('security.context')->isGranted('ROLE_ADMIN') )
return new Response('You are granted to see this site.');
This code checks if current user (me) has role ROLE_ADMIN. If you want to check if user has 'ROLE_ADMIN' AND doesn't have 'ROLE_USER' just add:
$security = $this->get('security.context');
if( $security->isGranted('ROLE_ADMIN') && !$security->isGranted('ROLE_USER') )
return new Response('You are not granted to see this site.');
Assuming that your routes are correctly secured, you have to hide / show links to restricted areas in your twig templates.
From the Symfony2 doc :
{% if is_granted('ROLE_ADMIN') %}
<a href="...">LogIntoBackend</a>
{% endif %}
Related :
- Symfony2 security functions in Twig? How to check the user's role?
- Symfony2: How to hide link in Twig based on permissions