I have been following this tutorial from the Symfony Book to manage my users.
Now, I would like to set a flash message after the login has succeeded OR if somebody attempts to access a forbidden area.
What I understand is that authentication and authorization are not managed inside controllers. As a consequence, I do not know where to put my code to display a simple "Sorry, you are not connected" message.
It will take some time and some coding just to display a simple message. If you want to do it by Symfony way you should look at this security configuration first, especially these ones:
entry_point
(under firewall) - which usually redirects users to login page whenever they try to access the secured pages. You can set flash messages here.success_handler
under form_login
(if you're using it) to show your successful login messagesuccess_handler
under logout
to show your logout message Some references:
You can access the SecurityContext
from your Controller
. So, assuming your forbidden area require a role SOME_ROLE
, you can do something like:
if (!$this->get('security.context')->isGranted('SOME_ROLE')) {
$this->get('session')->getFlashBag()->add('error', 'Access forbidden');
// maybe return a RedirectResponse to another page the user can access...
}
Note that the SecurityContext
has been deprecated since Symfony 2.6. It will still work, but if you want to learn how to adapt to future versions, you can check this.
As for the messages when users are/aren't logged in, you can use the AuthorizationChecker
, very similar to the previous one:
if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
// Add flash message here...
}
You can find more information here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With