<?php
namespace App\Controller\User;
use App\Form\Type\ChangePasswordType;
use App\Form\Type\EmailRecoverPasswordType;
use App\Service\User\UserService;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Translation\TranslatorInterface;
class UserController extends AbstractController
{
private $translator;
private $userService;
private $adminUrlGenerator;
public function __construct(
TranslatorInterface $translator,
UserService $userService,
AdminUrlGenerator $adminUrlGenerator
) {
$this->translator = $translator;
$this->userService = $userService;
$this->adminUrlGenerator = $adminUrlGenerator;
}
public function recoverPassword(Request $request): Response
{
$form = $this->createForm(EmailRecoverPasswordType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$email = $form['email']->getData();
if (!$this->userService->checkIfExistsEmail($email) || !$this->userService->checkIfUserIsActive($email)) {
$this->addFlash(
'danger',
$this->translator->trans('pages.recover_password.error-email-no-exist')
);
return $this->render('pages/password/recover.html.twig', [
'form' => $form->createView(),
'page_title' => $this->translator->trans('pages.recover_password.title'),
]);
}
$this->userService->assignTokenToUserByEmail($email);
$this->userService->sendRecoverPasswordEmail($email);
$this->addFlash(
'success',
$this->translator->trans('pages.recover_password.send-email')
);
return $this->redirectToRoute('app_login');
}
return $this->render('pages/password/recover.html.twig', [
'form' => $form->createView(),
'page_title' => $this->translator->trans('pages.recover_password.title'),
]);
}
public function changePasswordByRecoveryEmail(Request $request, string $token): Response
{
if (!$this->userService->checkIfCanChangePassword($token)) {
throw $this->createNotFoundException($this->translator->trans('error_pages.exception.not_found'));
}
$form = $this->createForm(ChangePasswordType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$firstPassword = $form['password']->getData();
if ($this->userService->isNewPasswordSameAsOldPasswordByToken($firstPassword, $token)) {
$this->addFlash(
'danger',
$this->translator->trans('pages.change_password.same')
);
return $this->render('pages/password/change.html.twig', [
'form' => $form->createView(),
'page_title' => $this->translator->trans('pages.recover_password.title'),
]);
}
$this->userService->updatePasswordByToken($firstPassword, $token);
$this->addFlash(
'success',
$this->translator->trans('pages.change_password.correct')
);
return $this->redirectToRoute('app_login');
}
return $this->render('pages/password/change.html.twig', [
'form' => $form->createView(),
'page_title' => $this->translator->trans('pages.recover_password.title'),
]);
}
}