<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\ChangePasswordFormType;
use App\Form\ResetPasswordRequestFormType;
use Doctrine\ORM\EntityManagerInterface;
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\Routing\Matcher\Dumper\StaticPrefixCollection;
use Symfony\Contracts\Translation\TranslatorInterface;
use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
class ResetPasswordController extends AbstractController
{
use ResetPasswordControllerTrait;
private $resetPasswordHelper;
private $entityManager;
private $hasher;
public function __construct(ResetPasswordHelperInterface $resetPasswordHelper, EntityManagerInterface $entityManager, UserPasswordHasherInterface $hasher)
{
$this->resetPasswordHelper = $resetPasswordHelper;
$this->entityManager = $entityManager;
$this->hasher = $hasher;
}
/**
* Display & process form to request a password reset.
*
* @Route("/{slug}/reset-password", name="app_forgot_password_request")
*/
public function resetPwdrequest(Request $request, MailerInterface $mailer, TranslatorInterface $translator,string $slug): Response
{
$form = $this->createForm(ResetPasswordRequestFormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
return $this->processSendingPasswordResetEmail(
$form->get('email')->getData(),
$mailer,
$translator,
$slug
);
}
$template = 'reset_password/front/request.html.twig';
if ($slug == "client") {
$template = 'reset_password/v2/request.html.twig';
}
return $this->render($template, [
'requestForm' => $form->createView(),
'slug' => $slug
]);
}
/**
* Confirmation page after a user has requested a password reset.
*
* @Route("/{slug}/check-email", name="app_check_email")
*/
public function checkEmail(string $slug): 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();
}
$slug = str_replace("specialist", "expert", $slug);
$template = 'reset_password/front/check_email.html.twig';
if ($slug == "client") {
$template = 'reset_password/v2/check_email.html.twig';
}
return $this->render($template, [
'resetToken' => $resetToken,
'slug' => $slug
]);
}
/**
* Validates and process the reset URL that the user clicked in their email.
*
* @Route("/{slug}/reset/{token}", name="app_reset_password")
*/
public function reset(Request $request, UserPasswordHasherInterface $userPasswordHasher,
TranslatorInterface $translator, string $slug, 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', ['slug' => $slug]);
}
$token = $this->getTokenFromSession();
if (null === $token) {
throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
}
$prefix = 'front';
$returnPage = 'app_login_admin';
try {
$user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
if ($user->hasRole(User::ROLE_CLIENT)) {
$prefix = "front";
$returnPage = 'app_login_client';
} elseif ($user->hasRole(User::ROLE_SPECIALIST)) {
$prefix = "front";
$returnPage = 'app_login_specialist';
} elseif ($user->hasRole(User::ROLE_COMPANY)) {
$prefix = "front";
$returnPage = 'app_login_company';
}
} 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('app_forgot_password_request');
}
// The token is valid; allow the user to change their password.
$form = $this->createForm(ChangePasswordFormType::class);
$form->handleRequest($request);
$prefix = 'front';
$returnPage = 'app_login_admin';
if ($user->hasRole(User::ROLE_CLIENT)) {
$prefix = "v2";
$returnPage = 'app_login_client';
} elseif ($user->hasRole(User::ROLE_SPECIALIST)) {
$prefix = "front";
$returnPage = 'app_login_specialist';
} elseif ($user->hasRole(User::ROLE_COMPANY)) {
$prefix = "front";
$returnPage = 'app_login_company';
}
if ($form->isSubmitted() && $form->isValid()) {
try {
// Encode(hash) the plain password, and set it.
$user->setPassword($this->hasher->hashPassword($user, $form->get('plainPassword')->getData()));
$this->entityManager->persist($user);
$this->entityManager->flush();
// A password reset token should be used only once, remove it.
$this->resetPasswordHelper->removeResetRequest($token);
// The session is cleaned up after the password has been changed.
$this->cleanSessionAfterReset();
$this->addFlash("success", "Mot de passe modifié");
} catch (\Throwable $th) {
throw $th;
}
return $this->redirectToRoute($returnPage);
}
return $this->render("reset_password/$prefix/reset.html.twig", [
'resetForm' => $form->createView(),
'slug' => $slug
]);
}
private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer, TranslatorInterface $translator, string $slug): RedirectResponse
{
$slug = str_replace("expert", "specialist", $slug);
$user = $this->entityManager->getRepository(User::class)->findOneBy([
'email' => $emailFormData,
'category' => $slug
]);
$slug = str_replace("specialist", "expert", $slug);
$redirect = $this->redirectToRoute('app_check_email', ['slug' => $slug]);
// if (in_array($slug, [User::GROUP_ADMIN])) {
// $redirect = $this->redirectToRoute('app_check_email_backoffice', [
// 'slug' => $slug
// ]);
// }
// Do not reveal whether a user account was found or not.
if (!$user) {
return $redirect;
}
try {
$resetToken = $this->resetPasswordHelper->generateResetToken($user);
} catch (ResetPasswordExceptionInterface $e) {
return $redirect;
}
$email = (new TemplatedEmail())
->from(new Address('hello@ulteam.app', 'ULTEAM'))
->to($user->getEmail())
->subject('Demande de reinitialisation de mot de passe')
->htmlTemplate('reset_password/front/email.html.twig')
->context([
'resetToken' => $resetToken,
'slug' => $slug
]);
$mailer->send($email);
// Store the token object in session for retrieval in check-email route.
$this->setTokenObjectInSession($resetToken);
return $redirect;
}
}