<?php
namespace App\Controller;
use App\Entity\User;
use App\Event\PortalUserEvent;
use App\Factory\Platform\MailerFactory;
use App\Form\Type\ChangePasswordFormType;
use App\Form\Type\ResetPasswordRequestFormType;
use App\Services\Common\Email\MailTypes;
use App\Services\Common\MailerService;
use App\Services\Common\User\WorkflowUser;
use App\Services\DTV\YamlConfig\YamlReader;
use App\Services\Portal\PortalService;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Psr\Log\LoggerInterface;
use ReflectionException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
/**
* Controller pour la gestion de la réinitialisation du mot de passe
*
* @Route("/reset-password")
*/
class ResetPasswordController extends AbstractController
{
use ResetPasswordControllerTrait;
private ResetPasswordHelperInterface $resetPasswordHelper;
private LoggerInterface $logger;
private MailerService $mailerService;
private YamlReader $yamlReader;
private EntityManagerInterface $em;
private PortalService $portalService;
private EventDispatcherInterface $dispatcher;
private TranslatorInterface $translator;
private WorkflowUser $workflowUser;
public function __construct(
ResetPasswordHelperInterface $resetPasswordHelper,
LoggerInterface $logger,
MailerService $mailerService,
YamlReader $yamlReader,
EntityManagerInterface $em,
PortalService $portalService,
EventDispatcherInterface $dispatcher,
TranslatorInterface $translator,
WorkflowUser $workflowUser
) {
$this->resetPasswordHelper = $resetPasswordHelper;
$this->logger = $logger;
$this->mailerService = $mailerService;
$this->yamlReader = $yamlReader;
$this->em = $em;
$this->portalService = $portalService;
$this->dispatcher = $dispatcher;
$this->translator = $translator;
$this->workflowUser = $workflowUser;
}
/**
* Affiche et traite le formulaire de demande de réinitialisation du mot de passe.
*
* @Route("", name="app_forgot_password_request")
*
* @param Request $request
*
* @return Response
*
* @throws ClientExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ReflectionException
* @throws ServerExceptionInterface
*/
public function request(Request $request): Response
{
$form = $this->createForm(ResetPasswordRequestFormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
return $this->processSendingPasswordResetEmail(
$form->get('email')->getData(),
);
}
return $this->render('security/request.html.twig', [
'requestForm' => $form->createView(),
]);
}
/**
* Redirige vers la page de vérification de l'e-mail.
*
* @param string $emailFormData
*
* @return RedirectResponse
*
* @throws ReflectionException
* @throws ClientExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
* @throws Exception
*/
private function processSendingPasswordResetEmail(string $emailFormData): RedirectResponse
{
$user = $this->em->getRepository(User::class)->findOneBy(
[
'email' => $emailFormData,
],
);
// Do not reveal whether a user account was found or not.
if ($user === NULL) {
return $this->redirectToRoute('app_check_email');
}
$mailer = $this->yamlReader->getMailer();
// Check les CGU
if (is_null($user->getCguAt()) && $user->getStatus() === User::STATUS_CGU_PENDING) {
$this->workflowUser->resendCGU($user);
$this->addFlash(
'danger',
$this->translator->trans(
"cgu_pending_message %contact_email%",
["%contact_email%" => $mailer[ 'contact_email' ]]
)
);
return $this->redirectToRoute('app_login');
}
try {
$resetToken = $this->resetPasswordHelper->generateResetToken($user);
} catch (ResetPasswordExceptionInterface $e) {
// If you want to tell the user why a reset email was not sent, uncomment
// the lines below and change the redirect to 'app_forgot_password_request'.
// Caution: This may reveal if a user is registered or not.
$this->addFlash(
'reset_password_error',
'il y a eu un problème lors du traitement de votre demande de réinitialisation du mot de passe - ' . $e->getReason(
),
);
return $this->redirectToRoute('app_check_email');
}
$this->mailerService->createApiMailRequest(MailTypes::RESET_PASSWORD)
->addRecipientToRequest(
$user,
MailerFactory::buildResetPassword($resetToken->getToken()),
)
->send()
;
// Store the token object in session for retrieval in check-email route.
$this->setTokenObjectInSession($resetToken);
return $this->redirectToRoute('app_check_email');
}
/**
* Page de confirmation après qu'un utilisateur a demandé une réinitialisation du mot de passe.
*
* @Route("/check-email", name="app_check_email")
*/
public function checkEmail(): Response
{
return $this->render('security/check_email.html.twig', [
'resetToken' => $this->getTokenObjectFromSession(),
]);
}
/**
* Valide et traite l'URL de réinitialisation que l'utilisateur a cliqué dans son e-mail.
*
* @Route("/reset/{token}", name="app_reset_password")
*/
public function reset(Request $request, UserPasswordHasherInterface $passwordEncoder, string $token = NULL): Response
{
if ($token) {
// We store the token in session and remove it from the URL, to avoid the URL being
// loaded in a browser and potentially leaking the token to 3rd party JavaScript.
$this->storeTokenInSession($token);
return $this->redirectToRoute('app_reset_password');
}
$token = $this->getTokenFromSession();
if (NULL === $token) {
throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
}
try {
/** @var User $user */
$user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
} catch (ResetPasswordExceptionInterface $e) {
$this->addFlash(
'reset_password_error',
$this->translator->trans(
'il y a eu un problème lors de la validation de votre demande de réinitialisation - %s %reason%',
['%reason%' => $e->getReason()]
),
);
return $this->redirectToRoute('app_forgot_password_request');
}
// The token is valid; allow the user to change their password.
$form = $this->createForm(ChangePasswordFormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$isPortal = $this->portalService->isOnPortal();
// A password reset token should be used only once, remove it.
$this->resetPasswordHelper->removeResetRequest($token);
// Encode the plain password, and set it.
$encodedPassword = $passwordEncoder->hashPassword(
$user,
$form->get('plainPassword')->getData(),
);
// Si on est sur un portail (parent), on propage le nouveau mot de passe sur tous les sites enfants
if ($isPortal && $this->portalService->isAParent()) {
$user->setPlainPassword($form->get('plainPassword')->getData());
$portalUserEvent = new PortalUserEvent($user);
$this->dispatcher->dispatch($portalUserEvent, $portalUserEvent::NAME);
}
$user->setPassword($encodedPassword);
$user->setFailedAttempts(0);
$user->setLastFailedAttempt(null);
$this->em->flush();
// The session is cleaned up after the password has been changed.
$this->cleanSessionAfterReset();
$this->addFlash(
'success',
$this->translator->trans('votre nouveau mot de passe a bien été enregistré !')
);
return $this->redirectToRoute('app_login');
}
return $this->render('security/reset.html.twig', [
'resetForm' => $form->createView(),
]);
}
/**
* Indique si on doit mettre à jour le mot de passe de l'utilisateur
*
* @Route("/{id}", name="app_need_refresh_password")
*
*
* @param User $user
*
* @return Response
*
* @throws ClientExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ReflectionException
* @throws ServerExceptionInterface
* @throws Exception
* @throws Exception
*/
public function needRefreshPassword(User $user): Response
{
try {
$resetToken = $this->resetPasswordHelper->generateResetToken($user);
} catch (ResetPasswordExceptionInterface $e) {
return $this->render('security/need_refresh_password.html.twig');
}
$this->mailerService->createApiMailRequest(MailTypes::RESET_PASSWORD)
->addRecipientToRequest(
$user,
MailerFactory::buildResetPassword(
$resetToken->getToken(),
),
)
->send()
;
// Store the token object in session for retrieval in check-email route.
$this->setTokenObjectInSession($resetToken);
return $this->render('security/need_refresh_password.html.twig', [
'resetToken' => $resetToken,
]);
}
}