Is there a way I can store when was the last time a user logged in?
I\'m using symfony2, and everything\'s working alright with the security configuration.
I
You can create an AuthenticationHandler that Symfony will call when user login successfully, you can save the login time into a User entity property (supposing that you have this scenario).
First, create the success authentication handler:
namespace Acme\TestBundle\Handler;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\DependencyInjection\ContainerAware;
class AuthenticationHandler extends ContainerAware implements AuthenticationSuccessHandlerInterface
{
function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
$token->getUser()->setLoginTime(new \DateTime());
$this->container->get('doctrine')->getEntityManager()->flush();
return new RedirectResponse($this->container->get('router')->generate('login_success'));
}
}
Then you need to register the authentication handler as a service in a configuration file, for example, src/Acme/TestBundle/resources/Config/services.yml
services:
authentication_handler:
class: Acme\TestBundle\Handler\AuthenticationHandler
calls:
- [ setContainer, [ @service_container ] ]
And configure the login form to use the created handler, check out your security.yml
form_login:
success_handler: authentication_handler
Obviously, for this to work, you need to have a User entity with a loginTime property and the corresponding setter. And you need to configure the login to use the User entity repository as user provider and the DaoAuthenticationProvider, as explained here: http://symfony.com/doc/current/book/security.html#loading-users-from-the-database.
A quite simple solution would be to implement FOSUserBundle in your application as each user entry in the database has (amongst other things) a "last_login" field.