<?php
namespace App\Controller;
use DateTimeImmutable;
use App\Entity\Forgotten;
use App\Form\PasswordType;
use App\Form\ForgottenType;
use App\Services\MailerService;
use App\Repository\UidRepository;
use App\Repository\ForgottenRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;
class SecurityController extends AbstractController
{
/**
* @Route("/login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
if ($this->getUser()) {
// On redirige l'utilisateur en fonction de son rôle
$role = strtolower(str_replace('ROLE_', '', $this->getUser()->getRoles()[0]));
$route = $role . '_dashboard';
return $this->redirectToRoute("dashboard");
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', ['current'=> 'login','last_username' => $lastUsername, 'error' => $error]);
}
/**
* @Route("/logout", name="app_logout")
*/
public function logout(SessionInterface $session): void
{
unset($session);
}
/**
* @Route("/mot-de-passe-oublie", name="app_forgotten")
*/
public function forgotten(
Request $request,
UidRepository $uidRepository,
ForgottenRepository $forgottenRepository,
TokenGeneratorInterface $tokenGenerator,
UserPasswordHasherInterface $encoder,
MailerService $mailer
): Response
{
$error = [];
$params = [];
$lastUsername = '';
/** Confirmation de la demande */
if ($request->query->get("_t")) {
$token = $request->query->get("_t");
$forgotten = $forgottenRepository->findOneBy(["token" => $token]);
$form = $this->createForm(PasswordType::class)->handleRequest($request);
/** Demande trouvée */
if ($forgotten) {
if ($form->isSubmitted() && $form->isValid()) {
$uid = $uidRepository->find($forgotten->getUid());
$data = $form->getData();
$password = $data["password"];
$uid->setPassword($encoder->hashPassword($uid, $password));
$uid->setUpdatedAt(new DateTimeImmutable());
/** Suppression de la demande de modification */
$this->manager->remove($forgotten);
$this->manager->flush();
$this->addFlash("success", "Votre mot de passe à bien été changé. Vous pouvez dès à présent vous connecter.");
return $this->redirectToRoute("app_login");
}
}
else {
$this->addFlash("danger", "Une erreur est survenue.");
return $this->redirectToRoute("app_forgotten");
}
return $this->render('security/new_password.html.twig', [
'current' => '',
'error' => $error,
'form' => $form->createView(),
]);
}
else {
$form = $this->createForm(ForgottenType::class)->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$email = $data['email'];
$lastUsername = $email;
$existUid = $uidRepository->findOneBy(["email" => $email]);
/** Utilisateur valide */
if (null !== $existUid) {
$existForgotten = $forgottenRepository->findOneBy(['uid' => $existUid]);
if(!$existForgotten){
$forgotten = new Forgotten();
$forgotten->setUid($existUid);
$forgotten->setCreatedAt(new DateTimeImmutable());
$token = $tokenGenerator->generateToken();
$forgotten->setToken($token);
$this->manager->persist($forgotten);
$this->manager->flush();
$params = [
'user' => $existUid,
'token' => $forgotten->getToken(),
];
$mailer->send("Demande de ré-initialisation de votre mot de passe - LOTICA", [$email], "forgot",$params);
$this->addFlash("success", "Un e-mail avec un lien de ré-initialisation pour votre mot de passe vient de vous être envoyé.");
return $this->redirectToRoute("app_forgotten");
}
else {
$this->addFlash("danger", "Demande de ré-initialisation déjà enregistrée. Un e-mail avec un lien de confirmation vous à été envoyé.");
}
}
else {
$this->addFlash("danger", "Adresse e-mail inconnue.");
}
}
return $this->render('security/forgotten.html.twig', [
'current' => '',
'lastUsername' => $lastUsername,
'error' => $error,
'form' => $form->createView(),
]);
}
}
}