Symfony:如何将每次成功登录保存到数据库表
我正在使用诸如 用于api身份验证的FosRestBundle、FosUserBundle和Lexik JWT 我需要在我的应用程序中保存每个成功登录。所以我创建了一个登录实体 (user_id,loginDate),但我不知道如何使用它,因为登录是从Lexik处理的 有人知道我怎么做吗Symfony:如何将每次成功登录保存到数据库表,symfony,authentication,symfony4,lexikjwtauthbundle,Symfony,Authentication,Symfony4,Lexikjwtauthbundle,我正在使用诸如 用于api身份验证的FosRestBundle、FosUserBundle和Lexik JWT 我需要在我的应用程序中保存每个成功登录。所以我创建了一个登录实体 (user_id,loginDate),但我不知道如何使用它,因为登录是从Lexik处理的 有人知道我怎么做吗 谢谢您可以使用安全。交互式登录事件。更多信息可从官方文件中找到: 创建侦听器并注册它: namespace App\EventListener; use App\Component\EntityManage
谢谢您可以使用
安全。交互式登录
事件。更多信息可从官方文件中找到:
创建侦听器并注册它:
namespace App\EventListener;
use App\Component\EntityManagerAwareTrait;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
/**
* @package App\EventListener
*/
class SecuritySubscriber implements EventSubscriberInterface
{
/**
* @param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
SecurityEvents::INTERACTIVE_LOGIN => 'onSecurityInteractiveLogin',
];
}
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event): void
{
$user = $event->getAuthenticationToken()->getUser();
if ($user instanceof User) {
$user->setLoginDate(new \DateTime());
$this->em->persist($user);
$this->em->flush();
}
}
}
您可以使用
security.interactive\u login
事件进行此操作。更多信息可从官方文件中找到:
创建侦听器并注册它:
namespace App\EventListener;
use App\Component\EntityManagerAwareTrait;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
/**
* @package App\EventListener
*/
class SecuritySubscriber implements EventSubscriberInterface
{
/**
* @param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
SecurityEvents::INTERACTIVE_LOGIN => 'onSecurityInteractiveLogin',
];
}
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event): void
{
$user = $event->getAuthenticationToken()->getUser();
if ($user instanceof User) {
$user->setLoginDate(new \DateTime());
$this->em->persist($user);
$this->em->flush();
}
}
}
你的意思是只记录登录活动吗?因为将登录数据持久化到数据库让我感觉非常不自在。您需要保存用户登录信息吗?我们的客户希望看到每日登录次数等统计信息。所以我们必须有一个登录历史记录。我知道这是无用的逻辑,但对于我们的客户来说,这是一个必须具备的功能。请不要因为我客户的需要而否决我。你的意思是只记录登录活动吗?因为将登录数据持久化到数据库让我感觉非常不自在。您需要保存用户登录信息吗?我们的客户希望看到每日登录次数等统计信息。所以我们必须有一个登录历史记录。我知道这是无用的逻辑,但对于我们的客户来说,这是一个必须具备的功能。请不要因为我客户的需要而投票否决我。