<?php
namespace App\Controller;
use App\Controller\CoreController;
use App\Entity\User;
use App\Form\ChangePasswordFormType;
use App\Form\ResetPasswordRequestFormType;
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\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
/**
* @Route("/password/reset-password")
*/
class ResetPasswordController extends CoreController
{
use ResetPasswordControllerTrait;
/**
* Display & process form to request a password reset.
*
* @Route("", name="app_forgot_password_request")
* @Route("/front/{myflix}", name="app_forgot_password_request_myflix")
*/
public function request(ResetPasswordHelperInterface $resetPasswordHelper): Response
{
$myflix = $this->requestStack->getCurrentRequest()->attributes->get('myflix');
if(!is_null($myflix)) {
$getMyflix = $this->repository->MyflixRepository->findOneBy(['slug' => $myflix]);
if (!$getMyflix) {
return $this->redirectToRoute('error_404');
}
}
$form = $this->createForm(ResetPasswordRequestFormType::class);
$form->handleRequest($this->requestStack->getCurrentRequest());
if ($form->isSubmitted() && $form->isValid()) {
return $this->processSendingPasswordResetEmail(
$this->requestStack->getCurrentRequest(),
$form->get('email')->getData(),
$myflix,
$resetPasswordHelper
);
}
if(!is_null($myflix)) {
return $this->render('security/reset_password/request_myflix.html.twig', [
'requestForm' => $form->createView(),
'myflix' => $myflix
]);
}else{
return $this->render('security/reset_password/request.html.twig', [
'requestForm' => $form->createView(),
]);
}
}
/**
* Confirmation page after a user has requested a password reset.
*
* @Route("/check-email", name="app_check_email")
* @Route("/check-email/{myflix}", name="app_check_email_myflix")
*/
public function checkEmail(): Response
{
$myflix = $this->requestStack->getCurrentRequest()->attributes->get('myflix');
if(!is_null($myflix)) {
$getMyflix = $this->repository->MyflixRepository->findOneBy(['slug' => $myflix]);
if (!$getMyflix) {
return $this->redirectToRoute('error_404');
}
}
// We prevent users from directly accessing this page
if (null === ($resetToken = $this->getTokenObjectFromSession())) {
if(!is_null($myflix)) {
return $this->redirectToRoute('app_forgot_password_request_myflix', ['myflix' => $myflix]);
}else {
return $this->redirectToRoute('app_forgot_password_request');
}
}
if(!is_null($myflix)) {
return $this->render('security/reset_password/check_email_myflix.html.twig', [
'resetToken' => $resetToken,
'myflix' => $myflix
]);
}else{
return $this->render('security/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")
* @Route("/reset/{token}/{myflix}", name="app_reset_password_myflix")
*/
public function reset(string $token = null, ResetPasswordHelperInterface $resetPasswordHelper): Response
{
$session = $this->requestStack->getSession();
$myflix = $this->requestStack->getCurrentRequest()->attributes->get('myflix');
if(!is_null($myflix)) {
$getMyflix = $this->repository->MyflixRepository->findOneBy(['slug' => $myflix]);
if (!$getMyflix) {
return $this->redirectToRoute('error_404');
}
}
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);
$myflix_reset_password = !is_null($myflix) ? $myflix : '';
$session->set('myflix_reset_password', $myflix_reset_password);
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 {
$user = $resetPasswordHelper->validateTokenAndFetchUser($token);
} catch (ResetPasswordExceptionInterface $e) {
$pos = strpos($e->getReason(), 'The reset password link is invalid');
if ($pos === false) {
$msg = $e->getReason();
} else {
$msg = $this->translator->trans('text.msg_eroor_lien_reset_request');
}
$this->addFlash('reset_password_error', sprintf(
$this->translator->trans('text.msg_eroor_validating_reset_request').' - %s',
$msg
));
if($session->get('myflix_reset_password') != '') {
$session->set('myflix_reset_password', null);
return $this->redirectToRoute('app_forgot_password_request_myflix', ['myflix' => $session->get('myflix_reset_password')]);
}else {
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($this->requestStack->getCurrentRequest());
if ($form->isSubmitted() && $form->isValid()) {
// A password reset token should be used only once, remove it.
$resetPasswordHelper->removeResetRequest($token);
// Encode the plain password, and set it.
$hashedPassword = $this->passwordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
);
$user->setPassword($hashedPassword);
$passwordEncrypt = $this->encryptPassword($form->get('plainPassword')->getData());
$user->setPasswordEncrypt($passwordEncrypt);
$myflix_slug = $this->requestStack->getCurrentRequest()->get('slug_myflix');
$this->update();
// The session is cleaned up after the password has been changed.
$this->cleanSessionAfterReset();
$this->addFlash('success', $this->translator->trans('text.msg_success_password_successfully_changed'));
if(!empty($myflix_slug)){
return $this->redirectToRoute('app_login_membre', ['myflix' => $myflix_slug]);
}else{
return $this->redirectToRoute('app_login');
}
}
if(!empty($session->get('myflix_reset_password'))){
return $this->render('security/reset_password/reset_myflix.html.twig', [
'resetForm' => $form->createView(),
'myflix' => $session->get('myflix_reset_password')
]);
}else{
return $this->render('security/reset_password/reset.html.twig', [
'resetForm' => $form->createView(),
'myflix' => $session->get('myflix_reset_password')
]);
}
}
private function processSendingPasswordResetEmail($request, string $emailFormData, $myflix, ResetPasswordHelperInterface $resetPasswordHelper): RedirectResponse
{
$user = $this->repository->UserRepository->findOneBy([
'email' => $emailFormData,
]);
// Do not reveal whether a user account was found or not.
if (!$user) {
if(!is_null($myflix)) {
return $this->redirectToRoute('app_check_email_myflix', ['myflix' => $myflix]);
}else {
return $this->redirectToRoute('app_check_email');
}
}
try {
$resetToken = $resetPasswordHelper->generateResetToken($user);
/** send mail to partner **/
$data_mess = [
'resetToken' => $resetToken,
'myflix' => $myflix
];
$mailerSender = $this->getParameter('mailer.support_email');
$template = 'back/default/emails/notif_reset_password.html.twig';
$subject = $this->translator->trans('text.msg_eroor_lien_reset_request');
$sendingMailOperation = $this->mailer->send($mailerSender,
trim($emailFormData),
$template,
$subject,
null,
$data_mess
);
} 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', sprintf(
// 'There was a problem handling your password reset request - %s',
// $e->getReason()
// ));
if(!is_null($myflix)) {
return $this->redirectToRoute('app_check_email_myflix', ['myflix' => $myflix]);
}else {
return $this->redirectToRoute('app_check_email');
}
}
// Store the token object in session for retrieval in check-email route.
$this->setTokenObjectInSession($resetToken);
if(!is_null($myflix)) {
return $this->redirectToRoute('app_check_email_myflix', ['myflix' => $myflix]);
}else {
return $this->redirectToRoute('app_check_email');
}
}
}