<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\User;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class UserMailSubscriber implements EventSubscriberInterface
{
private $mailer;
private $encoder;
private LoggerInterface $logger;
public function __construct(MailerInterface $mailer, UserPasswordEncoderInterface $encoder, LoggerInterface $logger)
{
$this->mailer = $mailer;
$this->encoder = $encoder;
$this->logger = $logger;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['sendMail', EventPriorities::PRE_WRITE],
];
}
public function sendMail(ViewEvent $event): void
{
$this->logger->debug("SENDING EMAIL BEFORE CHECK");
$user = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$user instanceof User || Request::METHOD_POST !== $method) {
return;
}
$this->logger->debug($user->getEmail());
$random = $this->generateRandomString(5);
$password = $random;
$passHash = $this->encoder->encodePassword($user, $password);
$this->logger->debug("SENDING EMAIL AFTER CHECK");
$user->setPassword($passHash);
$message = (new Email())
->from('noreplay@akoulagroupe.com')
->cc('figux01@gmail.com')
->to($user->getEmail())
->subject('MOT DE PASSE ESPACE ADMINISTRATION HOGES')
->html('Vous avez été ajouter à la liste des administrateurs du backoffice de l\'application Hoges. Voici votre mot de passe : '.$password);
try{
$this->mailer->send($message);
}catch (\Exception $e){
$this->logger->error($e->getMessage());
}
}
function generateRandomString($length = 5) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
}