<?php
namespace Diplix\KMGBundle\Service;
use Diplix\Commons\DataHandlingBundle\Entity\SysLogEntry;
use Diplix\Commons\DataHandlingBundle\Repository\SysLogRepository;
use Diplix\KMGBundle\Controller\User\WorkTimeController;
use Diplix\KMGBundle\Entity\Role;
use Diplix\KMGBundle\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Http\Authenticator\InteractiveAuthenticatorInterface;
use Symfony\Component\Security\Http\Authenticator\JsonLoginAuthenticator;
use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
use Symfony\Component\Security\Http\Event\LogoutEvent;
class LoginSuccessHandler implements
\Symfony\Component\EventDispatcher\EventSubscriberInterface
{
public function __construct(
protected RouterInterface $router,
protected AuthorizationCheckerInterface $authChecker,
protected EntityManagerInterface $em)
{
}
public function onAuthenticationSuccess(LoginSuccessEvent $event): void
{
$authenticator = $event->getAuthenticator();
if (method_exists($authenticator,'getAuthenticator')) // happens for example with TraceableAuthenticator in debug mode
{
$authenticator = $authenticator->getAuthenticator();
}
if ($authenticator instanceof JsonLoginAuthenticator)
{
// no redirect for json login
return;
}
/** @var User $u */
$u = $event->getUser();
SysLogRepository::logMessage($this->em->getConnection(),SysLogEntry::SYS_LOGIN,"Login",[
"ip"=>$event->getRequest()->getClientIp(),
"userAgent"=>$event->getRequest()->headers->get('User-Agent')
],$u->getId());
WorkTimeController::fromLogin($this->em,$u);
$home = $this->router->generate("kmg_home");
if ($this->authChecker->isGranted(Role::DISPO))
{
$home = $this->router->generate('dispatch-dashboard2');
}
if ($u->getCustomer() !== null)
{
$event->setResponse(new RedirectResponse($this->router->generate("admin-switch-customer",
array( "customerId"=>$u->getCustomer()->getId(),
"referTo"=>$home))));
return;
}
$event->setResponse(new RedirectResponse($home));
return;
}
public function onLogout(LogoutEvent $logoutEvent): void
{
$request = $logoutEvent->getRequest();
$token = $logoutEvent->getToken();
/** @var User $u */
$u = $token->getUser();
SysLogRepository::logMessage($this->em->getConnection(),SysLogEntry::SYS_LOGOUT,"Logout",[
"ip"=>$request->getClientIp()
],$u->getId());
WorkTimeController::fromLogout($this->em,$u);
}
/**
* @return array<string, mixed>
*/
public static function getSubscribedEvents(): array
{
return [
LoginSuccessEvent::class => 'onAuthenticationSuccess',
LogoutEvent::class => 'onLogout'
];
}
}