2

In this case, after a successful login, I need to update the user's login time into the underlying table.

The User entity currently implements UserInterface and is doing fine. Just want to add some extra code to log the login date time of the user.

Searched the site and seemed to me to use an EventListener etc is a bit heavy. Other lighter alternatives?

TaylorR
  • 3,746
  • 5
  • 25
  • 42

1 Answers1

2

You can implement a Success Hander.

  1. Write a class that implement the AuthenticationSuccessHandlerInterface:
  2. Define it as a service (you can inject other services like doctrine or the security context, in your case the Session)

Add the handler service in the security config like:

firewalls:
dev:
    pattern:  ^/(_(profiler|wdt)|css|images|js)/
    security: false

secured_area:
    pattern:   ^/
    anonymous: ~
    form_login:
        login_path:  login
        check_path:  login_check
        success_handler: some.service.id
    logout:
        path: logout
        target: /

Check this for a complete example and the reference doc for all the symfony2 security configuration options (you can configure the failure_handler also).

In my working solutions I implements the method onSecurityInteractiveLogin in my listener as:

public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) 
    {
        $user = $event->getAuthenticationToken()->getUser();

        $user->setLastLogin(new \Datetime());
        // Entity manager injected by container in the service definition
        $this->em->persist($user); 
        $this->em->flush();


    }

Hope this help

Community
  • 1
  • 1
Matteo
  • 37,680
  • 11
  • 100
  • 115
  • This should be the way to handle login success/failure. – Stefan Van den Heuvel Feb 09 '15 at 07:13
  • Hi @TaylorR if this or any answer has solved your question please consider [accepting it](http://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – Matteo Mar 17 '15 at 09:12