Security and Logon Based on Symfony 2

I am developing a web application based on the Symfony 2 framework.

The user has a login page for registered users. I want to execute some user logic for every user logging in to the system.

Basically, I want to register whenever a user logs in, but I do not want to do this on the controller of the main page, because he will register every time the user reloads the main page.

I also want to implement a function that is called when the user logs in, so I can decide whether access will be granted or not for any user (based on the full set of information stored in the user database).

How can i achieve this?

+3
source share
1 answer

In the first part of your question, I had something similar (for example, save the last date and time the user logged in). I went along the service route, which was fired for the event. In the services configuration (XML example here):

<services>

    <service id="my.login.listener" class="My\OwnBundle\Event\LoginEventListener">
      <tag name="kernel.event_listener" event="security.interactive_login" />
    </service>

</services>

and then create the above class in the appropriate place in your kit:

namespace My\OwnBundle\Event;

use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use My\OwnBundle\User\User as MyUser;

class LoginEventListener
{
    /**
     * Catches the login of a user and does something with it
     *
     * @param \Symfony\Component\Security\Http\Event\InteractiveLoginEvent $event
     * @return void
     */
    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
    {
        $token = $event->getAuthenticationToken();
        if ($token && $token->getUser() instanceof MyUser)
        {
            // You can do something here eg
            // record the date & time of the user login
        }
    }
}

I would suggest that you can extend this to the second part of your question, but I did not :-)

+10
source

All Articles