<?php
namespace MedBrief\MSR\Controller;
use Doctrine\ORM\EntityManagerInterface;
use MedBrief\MSR\Entity\User;
use MedBrief\MSR\Form\ChangePasswordFormType;
use MedBrief\MSR\Form\ResetPasswordRequestFormType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordToken;
use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
/**
* @Route("/reset-password")
*/
class ResetPasswordController extends AbstractController
{
use ResetPasswordControllerTrait;
public function __construct(private ResetPasswordHelperInterface $resetPasswordHelper, private EntityManagerInterface $entityManager)
{
}
/**
* Display & process form to request a password reset.
*
* @Route("", name="forgot_password_request")
*
* @Template("reset_password/request.html.twig")
*
* @param Request $request
* @param MailerInterface $mailer
* @param TranslatorInterface $translator
*
* @throws TransportExceptionInterface
*
* @return Response|array
*/
public function request(Request $request, MailerInterface $mailer, TranslatorInterface $translator): RedirectResponse|array
{
$form = $this->createForm(ResetPasswordRequestFormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
return $this->processSendingPasswordResetEmail(
$form->get('email')->getData(),
$mailer
);
}
return [
'requestForm' => $form->createView(),
];
}
/**
* Confirmation page after a user has requested a password reset.
*
* @Route("/check-email", name="check_email")
*
* @Template("reset_password/check_email.html.twig")
*/
public function checkEmail(): array
{
// Generate a fake token if the user does not exist or someone hit this page directly.
// This prevents exposing whether a user was found with the given email address or not
if (!($resetToken = $this->getTokenObjectFromSession()) instanceof ResetPasswordToken) {
$resetToken = $this->resetPasswordHelper->generateFakeResetToken();
}
return [
'resetToken' => $resetToken,
];
}
/**
* Validates and process the reset URL that the user clicked in their email.
*
* @Route("/reset/{token}", name="reset_password")
*
* @Template("reset_password/reset.html.twig")
*
* @param Request $request
* @param UserPasswordEncoderInterface $userPasswordEncoder
* @param TranslatorInterface $translator
* @param ?string $token
*
* @return Response|array
*/
public function reset(Request $request, UserPasswordEncoderInterface $userPasswordEncoder, TranslatorInterface $translator, ?string $token = null): RedirectResponse|array
{
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('reset_password');
}
$token = $this->getTokenFromSession();
if ($token === null) {
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', sprintf(
'%s - %s',
$translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
$translator->trans($e->getReason(), [], 'ResetPasswordBundle')
));
return $this->redirectToRoute('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()) {
// A password reset token should be used only once, remove it.
$this->resetPasswordHelper->removeResetRequest($token);
// Encode(hash) the plain password, and set it.
$encodedPassword = $userPasswordEncoder->encodePassword(
$user,
$form->get('plainPassword')->getData()
);
$this->addFlash('success', 'Your password has been successfully reset.');
$user->setPassword($encodedPassword);
$user->setEnabled(true);
$this->entityManager->flush();
// The session is cleaned up after the password has been changed.
$this->cleanSessionAfterReset();
return $this->redirectToRoute('login');
}
return [
'resetForm' => $form->createView(),
];
}
/**
*
*
*
* @param string $emailFormData
* @param MailerInterface $mailer
*
* @throws TransportExceptionInterface
*/
private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer): RedirectResponse
{
$user = $this->entityManager->getRepository(User::class)->findOneBy([
'email' => $emailFormData,
]);
// Do not reveal whether a user account was found or not.
if (!$user) {
return $this->redirectToRoute('check_email');
}
try {
$resetToken = $this->resetPasswordHelper->generateResetToken($user);
} catch (ResetPasswordExceptionInterface) {
// If you want to tell the user why a reset email was not sent, uncomment
// the lines below and change the redirect to 'forgot_password_request'.
// Caution: This may reveal if a user is registered or not.
//
// $this->addFlash('reset_password_error', sprintf(
// '%s - %s',
// $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
// $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
// ));
return $this->redirectToRoute('check_email');
}
$email = (new TemplatedEmail())
->from(new Address($this->getParameter('mailer_from_address'), $this->getParameter('mailer_from_name')))
->to($user->getEmail())
->subject('Your password reset request')
->htmlTemplate('reset_password/email.html.twig')
->context([
'resetToken' => $resetToken,
'user' => $user,
])
;
$mailer->send($email);
// Store the token object in session for retrieval in check-email route.
$this->setTokenObjectInSession($resetToken);
return $this->redirectToRoute('check_email');
}
}