<?php
/*
* This file is part of EC-CUBE
*
* Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
*
* http://www.ec-cube.co.jp/
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Customize\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
use Doctrine\ORM\EntityManagerInterface;
use Customize\Entity\LoggedinHistory;
use Eccube\Entity\Customer;
use Exception;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
/**
* ログイン成功時のイベントリスナー。
* ログインした時間をセッションとDBに登録する。
*/
class AuthenticationSuccessListener implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
protected $entityManager;
/**
* @var SessionInterface
*/
private $session;
public function __construct(EntityManagerInterface $entityManager, SessionInterface $session)
{
$this->entityManager = $entityManager;
$this->session = $session;
}
/**
* 対応するメソッドと優先度を登録する。
* 数値が高いほど優先度高。
*
* @see https://symfony.com/doc/4.4/event_dispatcher.html
* @see https://symfony.com/doc/4.4/components/security/authentication.html
*
* @return array
*/
public static function getSubscribedEvents()
{
return [
SecurityEvents::INTERACTIVE_LOGIN => [
['registerLoggedinTime', 0]
]
];
}
/**
* セッションにログイントークン、データベースにユーザ情報とログイントークンを保存する。
*
* @param InteractiveLoginEvent $event
* @return void
*/
public function registerLoggedinTime(InteractiveLoginEvent $event)
{
try {
$request = $event->getRequest();
$customer = $event->getAuthenticationToken()->getUser();
if (!$customer instanceof Customer) {
return;
}
$loggedinHistory = new LoggedinHistory();
$loginToken = md5(microtime());
$ip = $request->getClientIp();
$userAgent = $request->headers->get('User-Agent');
$loginDate = new \Datetime('now', new \DateTimeZone('Asia/Tokyo'));
$loggedinHistory->setCustomer($customer);
$loggedinHistory->setLoginToken($loginToken);
$loggedinHistory->setIp($ip);
$loggedinHistory->setUserAgent($userAgent);
$loggedinHistory->setLoginDate($loginDate);
$this->session->set('login_token', $loginToken);
$this->entityManager->persist($loggedinHistory);
$this->entityManager->flush();
} catch (Exception $e) {
log_error('[AuthenticationSuccessListener Error]: ' . $e->getMessage());
throw $e;
}
}
}