<?php
namespace Aqarmap\Bundle\UserBundle\EventListener;
use Aqarmap\Bundle\UserBundle\Entity\User;
use Aqarmap\Bundle\UserBundle\Services\UserManager;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\UserEvent;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Model\UserManagerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ChangeUserPasswordSubscriber implements EventSubscriberInterface
{
private UserManager $userManager;
private UserManagerInterface $fosUserManager;
private EventDispatcherInterface $eventDispatcher;
public function __construct(
UserManager $userManager,
UserManagerInterface $fosUserManager,
EventDispatcherInterface $eventDispatcher
) {
$this->userManager = $userManager;
$this->fosUserManager = $fosUserManager;
$this->eventDispatcher = $eventDispatcher;
}
/**
* @throws \Exception
*/
public function expireTokens(FilterUserResponseEvent $event): void
{
$this->userManager->expireAccessTokensByUser($event->getUser());
$this->userManager->expireRefreshTokensByUser($event->getUser());
}
public function onResettingResetRequest(FormEvent $event): void
{
$event->getRequest();
/** @var User $user */
$user = $event->getForm()->getData();
$plainPassword = $event->getForm()->get('plainPassword')->getData();
if ($user instanceof User && $user->getLegacy() && !empty($plainPassword)) {
$user->setPlainPassword($plainPassword);
$user->setLegacy(false);
$this->fosUserManager->updateUser($user);
$event = new UserEvent($user, $event->getRequest());
$this->eventDispatcher->dispatch($event, FOSUserEvents::USER_PASSWORD_CHANGED);
}
}
public function onResettingPassword(UserEvent $event): void
{
/** @var User|null $user */
$user = $event->getUser();
$plainPassword = $event->getRequest()->get('password');
if ($user instanceof User && !empty($plainPassword)) {
$user->setPlainPassword($plainPassword);
$user->setLegacy(false);
$this->fosUserManager->updateUser($user);
$event = new UserEvent($user, $event->getRequest());
$this->eventDispatcher->dispatch($event, FOSUserEvents::USER_PASSWORD_CHANGED);
}
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
FOSUserEvents::CHANGE_PASSWORD_COMPLETED => 'expireTokens',
FOSUserEvents::RESETTING_RESET_SUCCESS => 'onResettingResetRequest',
'aqarmap.user.password.reset' => 'onResettingPassword',
];
}
}