<?php
namespace App\Controller\Account\ForgotPassword;
use App\Repository\Account\UserRepository;
use App\Service\Mailer\MailerService;
use Doctrine\ORM\EntityManagerInterface;
use Nellapp\Bundle\SDKBundle\Routing\Utils\ChannelMainDomainUtils;
use Nellapp\Bundle\SDKBundle\Sync\Exception\ExceptionInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Uid\Uuid;
class AskController extends AbstractController
{
const SESSION_EMAIL_KEY = __CLASS__;
public function __construct(
private AuthenticationUtils $authenticationUtils,
private UserRepository $userRepository,
private SessionInterface $session,
private EntityManagerInterface $entityManager,
private MailerService $mailerService,
private ChannelMainDomainUtils $channelMainDomainUtils,
)
{
}
#[Route(path: '/forgot-password/ask', name: 'forgot_password_ask')]
public function __invoke(Request $request): Response
{
if ($this->isGranted('ROLE_USER')) {
return $this->redirectToRoute('account_home');
}
$email = $request->request->get('email');
if ($request->isMethod(Request::METHOD_POST) && null !== $email) {
if (null === $user = $this->userRepository->findOneBy(['email' => $email])) {
$error = 'app.security.forgotPassword.ask.user.notFound';
} else {
try {
$user->setPasswordToken(Uuid::v1());
$user->setPasswordTokenAt(new \DateTimeImmutable());
$this->entityManager->persist($user);
$this->entityManager->flush();
$sended = $this->mailerService->sendForgotPasswordMail($user);
if ($sended) {
// Add user email to session to print it in success page.
$this->session->set(self::SESSION_EMAIL_KEY, $user->getEmail());
return $this->redirectToRoute('forgot_password_ask_success');
}
// Remove token if cannot send email.
$user->setPasswordToken(null);
$user->setPasswordTokenAt(null);
$this->entityManager->persist($user);
$this->entityManager->flush();
$error = 'app.security.forgotPassword.ask.mail.cannotSend';
} catch (ExceptionInterface $e) {
$error = 'app.security.forgotPassword.ask.token.alreadyRequested';
}
}
}
$lastUsername = $email ?: $this->authenticationUtils->getLastUsername();
return $this->render('account/ForgotPassword/ask.html.twig', [
'error' => $error ?? false,
'last_username' => $lastUsername,
'channel' => $this->channelMainDomainUtils->getChannelFromRequest(),
]);
}
}