<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\ChangePasswordFormType;
use App\Form\ResetPasswordRequestFormType;
use Doctrine\ORM\EntityManagerInterface;
use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
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\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Contracts\Translation\TranslatorInterface;
#[Route('reset-password')]
class ResetPasswordController extends AbstractController
{
use ResetPasswordControllerTrait;
private $translator;
public function __construct(
private ResetPasswordHelperInterface $resetPasswordHelper,
private EntityManagerInterface $entityManager,
TranslatorInterface $translator
) {
$this->translator = $translator;
}
/**
* Display & process form to request a password reset.
*/
#[Route('/email', name: 'app_forgot_password_request')]
public function request(Request $request, MailerInterface $mailer, TranslatorInterface $translator): Response
{
// Create a form for the password reset request.
$form = $this->createForm(ResetPasswordRequestFormType::class);
$form->handleRequest($request);
// Check if the form is submitted and valid.
if ($form->isSubmitted() && $form->isValid()) {
// Process the sending of the password reset email.
return $this->processSendingPasswordResetEmail(
$form->get('email')->getData(),
$mailer,
$translator
);
}
$error = '';
// Check if the email field is empty and display a custom error message.
if ($form->get('email')->getData() === "") {
$error = throw new CustomUserMessageAuthenticationException(
$translator->trans('You are not an active user')
);
}
// Render the password reset request page with the form and error (if any).
return $this->render('reset_password/request.html.twig', [
'flash_error' => $error,
'requestForm' => $form->createView(),
]);
}
/**
* Confirmation page after a user has requested a password reset.
*/
#[Route('/check-email', name: 'app_check_email')]
public function checkEmail(): Response
{
// Generate a fake token if the user does not exist or someone hit this page directly.
// This prevents exposing whether or not a user was found with the given email address or not
if (null === ($resetToken = $this->getTokenObjectFromSession())) {
$resetToken = $this->resetPasswordHelper->generateFakeResetToken();
// $this->resetPasswordHelper->getTokenLifetime(60);
}
return $this->render('reset_password/check_email.html.twig', [
'resetToken' => $resetToken,
]);
}
/**
* Validates and process the reset URL that the user clicked in their email.
*/
#[Route('/reset/{token}', name: 'app_reset_password')]
public function reset(Request $request, UserPasswordHasherInterface $passwordHasher, TranslatorInterface $translator, string $token = null): Response
{
// If a token is provided in the URL, store it in the session and redirect to the reset route without the token.
if ($token) {
$this->storeTokenInSession($token);
return $this->redirectToRoute('app_reset_password');
}
// Retrieve the token from the session.
$token = $this->getTokenFromSession();
// If no token is found in the session, throw a NotFoundException.
if (null === $token) {
throw $this->createNotFoundException($this->translator->trans('message.modules.home.error.reset_token'));
}
try {
// Validate the token and fetch the user associated with it.
$user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
// $this->resetPasswordHelper->getTokenLifetime(60);
} catch (ResetPasswordExceptionInterface $e) {
// Handle validation exceptions by adding a flash message and redirecting to the forgot password request page.
$this->addFlash('reset_password_error', sprintf(
'%s - %s',
$translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
$translator->trans($e->getReason(), [], 'ResetPasswordBundle')
));
return $this->redirectToRoute('app_forgot_password_request');
}
// Create the change password form.
$form = $this->createForm(ChangePasswordFormType::class);
$form->handleRequest($request);
// Process form submission and update user password if the form is valid.
if ($form->isSubmitted() && $form->isValid()) {
$this->resetPasswordHelper->removeResetRequest($token);
// $this->resetPasswordHelper->getTokenLifetime(60);
// Hash the new password and update the user's password in the database.
$encodedPassword = $passwordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
);
/* if($encodedPassword==$user->getPassword()){
return new JsonResponse([
'status' => 'error',
'statusCode' => '400',
'errors' => $this->translator->trans('message.modules.error.new_password_same', [], 'api'),
], 200);
} */
$user->setPassword($encodedPassword);
$this->entityManager->flush();
// Add a success flash message and clean the session after a successful password reset.
$this->addFlash('success', $this->translator->trans('message.modules.success.pwd_reset'));
$this->cleanSessionAfterReset();
// Redirect to the home page.
return $this->redirectToRoute('home');
}
// Render the password reset form.
return $this->render('reset_password/reset.html.twig', [
'resetForm' => $form->createView(),
]);
}
// Process the sending of a password reset email.
private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer, TranslatorInterface $translator): RedirectResponse
{
// Find a user with the given email address.
$user = $this->entityManager->getRepository(User::class)->findOneBy([
'email' => $emailFormData,
]);
// If no user is found, redirect to the check email page.
if (!$user) {
return $this->redirectToRoute('app_check_email');
}
try {
// Generate a reset token using the ResetPasswordHelper service.
$resetToken = $this->resetPasswordHelper->generateResetToken($user);
$this->resetPasswordHelper->getTokenLifetime(60);
} catch (ResetPasswordExceptionInterface $e) {
// Handle exceptions during token generation by redirecting to the check email page.
return $this->redirectToRoute('app_check_email');
}
// Create and send a templated email containing the reset token.
$email = (new TemplatedEmail())
->from(new Address('harita.raba00@gmail.com'))
->to($user->getEmail())
->subject('Your password reset request')
->htmlTemplate('reset_password/email.html.twig')
->context([
'resetToken' => $resetToken,
]);
$mailer->send($email);
// Set the reset token object in the session and redirect to the check email page.
$this->setTokenObjectInSession($resetToken);
return $this->redirectToRoute('app_check_email');
}
}