5

有没有一种方法可以存储用户上次登录的时间?

我正在使用 symfony2,安全配置一切正常。

我已经看到这个Security and login on a Symfony 2 based project,这是一个类似的问题,但它不符合我的需要。

还有其他解决方案吗?

4

2 回答 2

15

您可以创建一个AuthenticationHandlerSymfony 将在用户成功登录时调用,您可以将登录时间保存到User实体属性中(假设您有这种情况)。

首先,创建成功认证处理程序:

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'));
    }
}

然后你需要将身份验证处理程序注册为配置文件中的服务,例如,src/Acme/TestBundle/resources/Config/services.yml

services:
    authentication_handler:
        class: Acme\TestBundle\Handler\AuthenticationHandler
        calls:
            - [ setContainer, [ @service_container ] ] 

并配置登录表单以使用创建的处理程序,查看您的security.yml

form_login:
    success_handler: authentication_handler

显然,要使其工作,您需要有一个User具有属性的实体loginTime和相应的设置器。并且您需要配置登录以使用User实体存储库作为用户提供程序和DaoAuthenticationProvider,如下所述:http: //symfony.com/doc/current/book/security.html#loading-users-from-the-database

于 2012-06-06T22:17:15.583 回答
5

一个非常简单的解决方案是在您的应用程序中实现FOSUserBundle,因为数据库中的每个用户条目(除其他外)都有一个“last_login”字段。

于 2012-06-07T10:11:51.643 回答