<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\ResetPasswordType;
use App\Services\APIMailer;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
class SecurityController extends AbstractController
{
/**
* @Route("/", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
if ($this->getUser()) {
return $this->redirectToRoute('app_coupons');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
// if($lastUsername){
// return $this->redirectToRoute("app_coupons");
// }
return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
/**
* @Route("/logout", name="app_logout")
*/
public function logout()
{
throw new Exception('This method can be blank - it will be intercepted by the logout key on your firewall');
}
/**
* @Route("/mot-de-passe-oublie", name="forgot_password")
* @throws Exception
* @throws TransportExceptionInterface
*/
public function forgotPassword(Request $request, APIMailer $mailer, EntityManagerInterface $entityManager, ParameterBagInterface $parameterBag, UrlGeneratorInterface $urlGenerator): Response
{
$email = $request->request->get('email');
if ('' !== $email && null !== $email) {
$user = $entityManager->getRepository(User::class)->findOneBy(['email' => $email]);
if ($user instanceof User) {
$token = md5(random_bytes(20));
$user
->setToken($token)
->setTokenCreated(new \DateTime())
;
$entityManager->persist($user);
$entityManager->flush();
$result = $mailer->sendEmail(
$parameterBag->get('email_reset_password'),
['email' => $email, 'link' => $urlGenerator->generate('reset_password', ['token' => $token], UrlGeneratorInterface::ABSOLUTE_URL)]
);
}
$this->addFlash('success', 'Un message a été envoyé dans votre boîte de réception');
}
return $this->render('security/forgotten_password.html.twig');
}
/**
* @Route("/reset-mot-de-passe/{token}", name="reset_password")
*/
public function resetPassword(string $token, Request $request, EntityManagerInterface $entityManager, UserPasswordEncoderInterface $passwordEncoder): Response
{
if ('' === $token) {
return $this->redirectToRoute('app_login');
}
$user = $entityManager->getRepository(User::class)->findOneBy(['token' => $token]);
if (!$user instanceof User) {
return $this->redirectToRoute('app_login');
}
$interval = strtotime((new \DateTime())->format("Y-m-d H:i:s")) - strtotime($user->getTokenCreated()->format("Y-m-d H:i:s"));
if (1 < ($interval / (60 * 60 * 24))) {
$user
->setToken(null)
->setTokenCreated(null);
}
$form = $this->createForm(ResetPasswordType::class);
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
$data = $form->getData();
$password = $data['password'];
$user
->setToken(null)
->setTokenCreated(null);
$user->setPassword($passwordEncoder->encodePassword(
$user,
$password
));
$entityManager->flush();
$this->addFlash('success', 'Votre nouveau mot de passe a été enregistré avec succès');
}
}
$entityManager->flush();
return $this->render('security/reset_password.html.twig', [
'form' => $form->createView()
]);
}
}