<?php
namespace App\Controller\Front;
use App\Entity\User;
use App\Form\RegisterType;
use App\Form\RemindPasswordType;
use App\Form\ResetPasswordType;
use App\Security\LoginFormAuthenticator;
use App\Service\EmailSender\ResetPasswordSender;
use App\Service\TokenGenerator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
/**
* @Route("/login/", name="login")
*/
public function login(AuthenticationUtils $authenticationUtils)
{
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('front/security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error
]);
}
/**
* @Route("/rejestracja/", name="register")
*/
public function register(Request $request, EntityManagerInterface $entityManager, UserPasswordEncoderInterface $encoder, LoginFormAuthenticator $login, GuardAuthenticatorHandler $guard)
{
$user = new User();
$form = $this->createForm(RegisterType::class, $user);
$forms = $form->handleRequest($request);
if ($forms->isSubmitted() && $forms->isValid()) {
$user = $forms->getData();
$plainPassword = $forms->get('password')->getData();
$encodedPassword = $encoder->encodePassword($user, $plainPassword);
$user->setPassword($encodedPassword);
if ($user->getRole() == User::ROLE_DOCTOR) {
$user->setActive(false);
}
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash('success', 'Konto zostało utworzone.');
return $guard->authenticateUserAndHandleSuccess($user, $request, $login, 'main');
}
return $this->render('front/security/register.html.twig', [
'form' => $form->createView()
]);
}
/**
* @Route("/logout/", name="logout")
*/
public function logout(AuthenticationUtils $authenticationUtils)
{
}
/**
* @Route("/remind-password/", name="remind_password")
*/
public function remindPasswordAction(Request $request, ResetPasswordSender $mailer)
{
$form = $this->createForm(RemindPasswordType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$email = $form->get('email')->getData();
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->addFlash('danger', 'Niepoprawny format email.');
return $this->redirectToRoute('remind_password');
}
$user = $this->getDoctrine()->getRepository(User::class)->findOneByEmail($email);
if (!$user) {
$this->addFlash('danger', 'Podany e-mail nie istnieje w bazie klientów.');
return $this->redirectToRoute('remind_password');
}
$emailSend = $this->sendResetPassEmailAndUpdateUser($user, $mailer);
if (!$emailSend) {
$this->addFlash('danger', 'Coś poszło nie tak.');
return $this->redirectToRoute('remind_password');
}
$this->addFlash('success', 'Wiadomość została wysłana na twój adres e-mail.<br/>Zawiera ona odnośnik do strony umożliwiającej dokończenie procedury.');
return $this->redirectToRoute('remind_password');
}
return $this->render('front/security/remind-password.html.twig', [
'form' => $form->createView(),
]);
}
private function sendResetPassEmailAndUpdateUser(User $user, ResetPasswordSender $resetPasswordSender)
{
$user->setPasswordToken(TokenGenerator::generate(12));
$user->setPasswordTokenCreatedAt(new \DateTime());
$this->getDoctrine()->getManager()->persist($user);
$this->getDoctrine()->getManager()->flush();
return $resetPasswordSender->send($user, USER::REMIND_PASSWORD_FRONT);
}
/**
* @Route("/reset-password/", name="reset_password")
*/
public function resetPasswordAction(Request $request, UserPasswordEncoderInterface $encoder)
{
if (!$request->query->has('token')) {
return $this->redirectToRoute('profile');
}
$token = $request->query->get('token');
$user = $this->getDoctrine()->getRepository(User::class)->findOneByPasswordToken($token);
if (!$user) {
$this->addFlash('danger', 'Niepoprawny link');
return $this->redirectToRoute('main');
}
$tokenCreatedAt = $user->getPasswordTokenCreatedAt();
$interval = $tokenCreatedAt->diff(new \DateTime());
if ($interval->format('%h') > 24 || $interval->format('%d') > 0) {
$this->addFlash('danger', 'Twój token do zmiany hasła wygasł');
return $this->redirectToRoute('main');
}
$form = $this->createForm(ResetPasswordType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$plainPassword = $form->get('password')->getData();
$encodedPassword = $encoder->encodePassword($user, $plainPassword);
$user->setPassword($encodedPassword);
$user->setPasswordToken(null);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->addFlash('success', 'Hasło zostało zmienione');
return $this->redirectToRoute('profile');
}
return $this->render('front/security/reset-password.html.twig', [
'form' => $form->createView()
]);
}
}