<?php
namespace Eckinox\SecurityBundle\Controller;
use App\Entity\Security\User;
use App\Entity\Security\AppUser;
use Eckinox\SecurityBundle\Form\ChangePasswordFormType;
use Eckinox\SecurityBundle\Form\ResetPasswordRequestFormType;
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\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment;
class ResetPasswordController extends AbstractController
{
use ResetPasswordControllerTrait;
/**
* @var UserPasswordHasherInterface
*/
private $passwordHasher;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(TranslatorInterface $translator, RequestStack $requestStack, Environment $twig, ResetPasswordHelperInterface $userResetPasswordHelper, ResetPasswordHelperInterface $appUserResetPasswordHelper)
{
$this->translator = $translator;
$this->request = $requestStack->getCurrentRequest();
$this->firewall = $this->request->attributes->get('_firewall_context');
$this->twig = $twig->getLoader();
$this->userClass = $this->firewall == 'security.firewall.map.context.app' ? AppUser::class : User::class;
$this->resetPasswordHelper = $this->firewall == 'security.firewall.map.context.app' ? $appUserResetPasswordHelper : $userResetPasswordHelper;
}
/**
* Display & process form to request a password reset.
*/
public function request(MailerInterface $mailer): Response
{
$template = $this->firewall == 'security.firewall.map.context.app' && $this->twig->exists('@EckinoxSecurity/app_reset_password/request.html.twig') ? '@EckinoxSecurity/app_reset_password/request.html.twig' : '@EckinoxSecurity/reset_password/request.html.twig';
$form = $this->createForm(ResetPasswordRequestFormType::class);
$form->handleRequest($this->request);
if ($form->isSubmitted() && $form->isValid()) {
return $this->processSendingPasswordResetEmail(
$form->get('email')->getData(),
$mailer
);
}
return $this->render($template, [
'requestForm' => $form->createView(),
]);
}
/**
* Confirmation page after a user has requested a password reset.
*/
public function checkEmail(): Response
{
$redirectRouteParameter = $this->firewall == 'security.firewall.map.context.app' ? 'eckinox_security_app_forgot_password_request' : 'eckinox_security_forgot_password_request';
$template = $this->firewall == 'security.firewall.map.context.app' && $this->twig->exists('@EckinoxSecurity/app_reset_password/check_email.html.twig') ? '@EckinoxSecurity/app_reset_password/check_email.html.twig' : '@EckinoxSecurity/reset_password/check_email.html.twig';
// We prevent users from directly accessing this page
if (null === ($resetToken = $this->getTokenObjectFromSession())) {
return $this->redirectToRoute($redirectRouteParameter);
}
return $this->render($template, [
'resetToken' => $resetToken,
]);
}
/**
* Validates and process the reset URL that the user clicked in their email.
*/
public function reset(UserPasswordHasherInterface $passwordHasher, string $token = null): Response
{
$redirectResetRouteParameter = $this->firewall == 'security.firewall.map.context.app' ? 'eckinox_security_app_reset_password' : 'eckinox_security_reset_password';
$redirectForgotRouteParameter = $this->firewall == 'security.firewall.map.context.app' ? 'eckinox_security_app_forgot_password_request' : 'eckinox_security_forgot_password_request';
$redirectLoginRouteParameter = $this->firewall == 'security.firewall.map.context.app' ? 'eckinox_security_app_login' : 'eckinox_security_login';
$template = $this->firewall == 'security.firewall.map.context.app' && $this->twig->exists('@EckinoxSecurity/app_reset_password/reset.html.twig') ? '@EckinoxSecurity/app_reset_password/reset.html.twig' : '@EckinoxSecurity/reset_password/reset.html.twig';
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($redirectResetRouteParameter);
}
$token = $this->getTokenFromSession();
if (null === $token) {
throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
}
try {
$user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
} catch (ResetPasswordExceptionInterface $e) {
$this->addFlash('reset_password_error', sprintf(
'There was a problem validating your reset request - %s',
$e->getReason()
));
return $this->redirectToRoute($redirectForgotRouteParameter);
}
$form = $this->createForm(ChangePasswordFormType::class);
$form->handleRequest($this->request);
if ($form->isSubmitted() && $form->isValid()) {
$this->resetPasswordHelper->removeResetRequest($token);
$encodedPassword = $passwordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
);
$user->setPassword($encodedPassword);
$this->getDoctrine()->getManager()->flush();
$this->cleanSessionAfterReset();
$this->addFlash('success', $this->translator->trans('eckinox_security.messages.your_password_has_been_reset'));
return $this->redirectToRoute($redirectLoginRouteParameter);
}
return $this->render($template, [
'resetForm' => $form->createView(),
]);
}
private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer): RedirectResponse
{
$redirectRouteParameter = $this->firewall == 'security.firewall.map.context.app' ? 'eckinox_security_app_forgot_password_request' : 'eckinox_security_forgot_password_request';
$redirectCheckEmailRouteParameter = $this->firewall == 'security.firewall.map.context.app' ? 'eckinox_security_app_check_email' : 'eckinox_security_check_email';
$resetPasswordRouteParameter = $this->firewall == 'security.firewall.map.context.app' ? 'eckinox_security_app_reset_password' : 'eckinox_security_reset_password';
$template = $this->firewall == 'security.firewall.map.context.app' && $this->twig->exists('@EckinoxSecurity/app_reset_password/email.html.twig') ? '@EckinoxSecurity/app_reset_password/email.html.twig' : '@EckinoxSecurity/reset_password/email.html.twig';
$user = $this->getDoctrine()->getRepository($this->userClass)->findOneBy([
'email' => $emailFormData,
]);
// Do not reveal whether a user account was found or not.
if (!$user) {
return $this->redirectToRoute($redirectCheckEmailRouteParameter);
}
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 'eckinox_security_forgot_password_request'.
// Caution: This may reveal if a user is registered or not.
$this->addFlash('reset_password_error', $this->translator->trans('eckinox_security.messages.' . $e->getReason()));
return $this->redirectToRoute($redirectRouteParameter);
}
$email = (new TemplatedEmail())
->from(new Address($this->getParameter('eckinox_security.sender_email'), $this->getParameter('eckinox_security.sender_name')))
->to($user->getEmail())
->subject($this->translator->trans('eckinox_security.messages.your_password_reset_request'))
->htmlTemplate($template)
->context([
'resetToken' => $resetToken,
'reset_password_route' => $resetPasswordRouteParameter
]);
$mailer->send($email);
$this->setTokenObjectInSession($resetToken);
return $this->redirectToRoute($redirectCheckEmailRouteParameter);
}
}