Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display flash messages after login/logout

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.

like image 500
Creasixtine Avatar asked Jun 06 '15 10:06

Creasixtine


2 Answers

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:

  1. 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.
  2. success_handler under form_login (if you're using it) to show your successful login message
  3. success_handler under logout to show your logout message

Some references:

  • SecurityBundle Configuration ("security")
  • Symfony2: why access_denied_handler doesn't work
  • What is the best way to notify a user after an access_control rule redirects?
  • Redirect Symfony2 LogoutSuccessHandler to original logout target
  • Adding a Flash Message
like image 91
xurshid29 Avatar answered Nov 08 '22 11:11

xurshid29


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.

like image 32
MikO Avatar answered Nov 08 '22 11:11

MikO