<?php declare(strict_types=1);
namespace App\Controller\ForgotPassword;
use App\Email\ResetPassword;
use App\Entity\PasswordReset;
use App\Entity\User;
use App\Form\Type\RequestPasswordResetType;
use App\Security\RandomGenerator;
use DateTime;
use Doctrine\Persistence\ManagerRegistry;
use Sindrive\EmailSenderBundle\Service\EmailSender;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class RequestPasswordLinkController extends AbstractController
{
private ManagerRegistry $doctrine;
private RandomGenerator $randomGenerator;
private EmailSender $emailSender;
private int $resetPasswordTTL;
public function __construct(ManagerRegistry $doctrine, RandomGenerator $randomGenerator, EmailSender $emailSender)
{
$this->doctrine = $doctrine;
$this->randomGenerator = $randomGenerator;
$this->emailSender = $emailSender;
}
public function sendPasswordRequest(Request $request): Response
{
$hideForm = false;
$form = $this->createForm(RequestPasswordResetType::class)->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$userRepository = $this->doctrine->getRepository(User::class);
$user = $userRepository->findOneBy(['email' => $form->get('email')->getData()]);
if (null !== $user) {
$dateGone = DateTime::createFromFormat('U', (string) (time() + $this->resetPasswordTTL));
if (false === $dateGone) {
$dateGone = new DateTime('+4 hours');
}
$passwordReset = new PasswordReset(
$user,
$this->randomGenerator->generateToken(22),
$dateGone
);
$link = $this->generateUrl(
'reset_password_new',
['hash' => $passwordReset->getCode()],
UrlGeneratorInterface::ABSOLUTE_URL
);
$this->doctrine->getManager()->persist($passwordReset);
$this->doctrine->getManager()->flush();
$this->emailSender->sendType(new ResetPassword($user, $link));
}
return $this->render('forgot_password/request_complete.html.twig');
}
return $this->render('forgot_password/request.html.twig', ['form' => $form->createView(), 'hideForm' => $hideForm]);
}
/**
* @required
*/
public function setResetPasswordTTL(int $resetPasswordTTL): void
{
$this->resetPasswordTTL = $resetPasswordTTL;
}
}