<?php
namespace Czech\Controller;
use App\Exception\Central\Client\ClientInactiveException;
use App\Exception\Central\User\UserInactiveException;
use App\Exception\Central\User\UserNotFoundException;
use App\Service\Central\User\UserPasswordManager;
use Czech\Form\Type\ForgotPasswordType;
use Czech\Model\ForgotPasswordModel;
use Czech\Service\MailerManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Contracts\Translation\TranslatorInterface;
class SecurityController extends AbstractController
{
public function login(AuthenticationUtils $authenticationUtils)
{
if ($this->getUser()) {
return $this->redirectToRoute('czech_homepage');
}
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('czech/security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
]);
}
public function logout()
{
}
public function forgotPassword(
Request $request,
UserPasswordManager $userPasswordManager,
FlashBagInterface $flashBag,
TranslatorInterface $translator,
MailerManager $mailerManager
)
{
if ($this->getUser()) {
return $this->redirectToRoute('czech_homepage');
}
$forgotPassword = new ForgotPasswordModel();
$form = $this->createForm(ForgotPasswordType::class, $forgotPassword);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
try {
$user = $userPasswordManager->createResetPasswordToken($forgotPassword->email);
$mailerManager->sendResetPassword($user);
$flashBag->add('success', $translator->trans('email.forgot_password.send'));
} catch (UserNotFoundException $userNotFoundException) {
$flashBag->add('error', $translator->trans('user.email_not_exist', [], 'validators'));
} catch (ClientInactiveException $userClientInactiveException) {
$flashBag->add('error', $translator->trans('client.inactive', [], 'validators'));
} catch (UserInactiveException $userClientInactiveException) {
$flashBag->add('error', $translator->trans('user.inactive', [], 'validators'));
}
}
return $this->render('czech/security/forgot_password.html.twig', [
'form' => $form->createView()
]);
}
public function resetPassword(
Request $request,
UserPasswordManager $userPasswordManager,
MailerManager $mailerManager,
FlashBagInterface $flashBag,
TranslatorInterface $translator
)
{
$resetPasswordToken = $request->get('token');
try {
$user = $userPasswordManager->generateNewPassword($resetPasswordToken);
$mailerManager->sendNewPassword($user);
$flashBag->add('success', $translator->trans('user.new_password_generated'));
} catch (\Exception $exception) {
$flashBag->add('error', $translator->trans('user.reset_password_failed'));
}
return $this->redirectToRoute('czech_login');
}
}