6

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.

MikO
  • 18,243
  • 12
  • 77
  • 109
Creasixtine
  • 740
  • 3
  • 11
  • 33

2 Answers2

2

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.

MikO
  • 18,243
  • 12
  • 77
  • 109
2

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:

Community
  • 1
  • 1
xurshid29
  • 4,172
  • 1
  • 20
  • 25
  • Thank you a lot. I think I shall use the `success_handler` method. Now I am thinking about creating a new service named FlashMessages that would handle most flash messages used in my application. But for now I am struggling to create and register that service. – Creasixtine Jun 06 '15 at 17:40
  • 1
    @LeBarde It's very simple to create and use services. Read about them [here](http://symfony.com/doc/current/book/service_container.html). – xurshid29 Jun 06 '15 at 17:56
  • Thanks @xurshid29 for your answer. Now I have my services. Now I have a `LoginSuccessHandler` service. But here `$request->getUser()` is `null` inside the `onAuthenticationSuccess()` method. I cannot understand why. Going on searching... – Creasixtine Jun 11 '15 at 07:30
  • OK I have succeeded by injecting `"@security.token_storage"` in my service. Afterwhat I call a `$this->security->getToken()->getUser()->getUsername()`. fffff... – Creasixtine Jun 11 '15 at 07:57