<?php
namespace Harmonizely\Core\Security\Subscriber;
use Doctrine\ORM\EntityManagerInterface;
use Harmonizely\Core\Security\Contract\ISecurityHelper;
use Harmonizely\Core\Security\Event\UserSecondFactorEvent;
use Harmonizely\Model\UserInterface;
use Harmonizely\Service\Base\Crypt\Contract\ICrypt;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Class CancelSubscriptionSubscriber
* @package Harmonizely\Service\Subscription\Subscriber
*/
class SetSecondFactorPassedSubscriber implements EventSubscriberInterface
{
/**
* @var RequestStack
*/
private RequestStack $requestStack;
/**
* @var EntityManagerInterface
*/
private EntityManagerInterface $entityManager;
/**
* @var ICrypt
*/
private ICrypt $crypt;
/**
* ReceiveSubscriptionSubscriber constructor.
* @param RequestStack $requestStack
* @param EntityManagerInterface $entityManager
* @param ICrypt $crypt
*/
public function __construct(
RequestStack $requestStack,
EntityManagerInterface $entityManager,
ICrypt $crypt
)
{
$this->requestStack = $requestStack;
$this->entityManager = $entityManager;
$this->crypt = $crypt;
}
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return [
UserSecondFactorEvent::NAME => 'onSecondFactorPassed',
];
}
/**
* @param UserSecondFactorEvent $event
* @return void
*/
public function onSecondFactorPassed(UserSecondFactorEvent $event): void
{
if ($event->isPassed()) {
$user = $event->getToken()->getUser();
if ($user instanceof UserInterface) {
$request = $this->requestStack->getCurrentRequest();
$code = $request->get('code');
if ($code && strlen($code) === 6) {
$codeWithSalt = $this->crypt->encrypt($code);
$user->setLastTwoFactorCode($codeWithSalt);
setcookie(ISecurityHelper::LAST_TWO_FACTOR_CODE, $codeWithSalt, [
'expires' => time() + 86400,
'path' => '/',
'secure' => true,
'httponly' => true,
]);
$this->entityManager->flush();
}
}
}
}
}