Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Security and login on a Symfony 2 based project

I'm developing a web application based on the Symfony 2 PHP framework.

It has a login page for the users registered. I want to execute some custom logic for every user logging into the system.

Basicaly, I want to log whenever any user logs into the system, but I don't want to do it on the main page's controller, because it would log every time the user reloads the main page.

I also want to implement a function that gets called when the user logs into the system so I can decide wether the access is granted or not for any user (based on a full set of information stored on the user's database).

How can I achieve this?

like image 984
ButterDog Avatar asked Feb 02 '26 15:02

ButterDog


1 Answers

For the first part of your question, I had something similar (eg store the last date & time of a user's login). I went down the route of a service which was fired upon an event. In your services config (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 mentioned class in the appropriate place in your bundle:

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's login
        }
    }
}

I would imagine that you could extend this to the second part of your question, however I've not done this :-)

like image 65
richsage Avatar answered Feb 05 '26 03:02

richsage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!