<?php
namespace Acme\SudcmsBundle\Controller;
use Acme\SudcmsBundle\Entity\AuthUser;
use Acme\SudcmsBundle\Entity\EcoCustomers;
use Acme\SudcmsBundle\Form\Ecommerce\CustomerFrontType;
use Acme\SudcmsBundle\Form\Ecommerce\FrontLoginType;
use Acme\SudcmsBundle\Form\ResetPassType;
use Acme\SudcmsBundle\Repository\AuthUserRepository;
use Acme\SudcmsBundle\Service\ApiService;
use Acme\SudcmsBundle\Service\MailerService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
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\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityFrontController extends AbstractController
{
private ApiService $apiService;
public function __construct(ApiService $apiService)
{
$this->apiService = $apiService;
}
#[Route(path: '/connexion', name: 'front_app_login')]
public function login(AuthenticationUtils $authenticationUtils, Request $request): Response
{
if (!$this->apiService->testConnexion()) {
$this->addFlash('danger', 'Une erreur est survenue, veuillez réessayer ultérieurement.');
return $this->redirectToRoute('front_home');
}
if ($this->getUser()) {
return $this->redirectToRoute('front_shopping_categorie');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
// init formulaire de création de compte
$formCreateAccount = $this->createForm(CustomerFrontType::class, new EcoCustomers(), []);
// init formulaire connexion
$formLogin = $this->createForm(FrontLoginType::class, new AuthUser());
$request->getSession()->set('previous_route', 'front_app_login');
return $this->render('@main-app/security_front/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
'form' => $formCreateAccount->createView(),
'formLogin' => $formLogin->createView(),
'pageAccount' => 'Connexion',
]);
}
#[Route(path: '/deconnexion', name: 'front_app_logout', methods: ['GET'])]
public function logout()
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
/**
* @throws \Exception
*/
#[Route(path: '/mot-de-passe-oublie', name: 'front_forgotten_password')]
public function forgotten_password(Request $request, AuthUserRepository $users,
MailerService $mailerService): Response
{
// On initialise le formulaire
$form = $this->createForm(ResetPassType::class);
// On traite le formulaire
$form->handleRequest($request);
// Si le formulaire est valide
if ($form->isSubmitted() && $form->isValid()) {
// On récupère les données
$donnees = $form->getData();
// On cherche un utilisateur ayant cet e-mail
$user = $users->findOneBy(['email' => $donnees['email']]);
// Si l'utilisateur n'existe pas
if ($user === null) {
// On envoie une alerte disant que l'adresse e-mail est inconnue
$this->addFlash('danger', 'Cette adresse e-mail est inconnue');
// On retourne sur la page de connexion
return $this->redirectToRoute('front_app_login');
}
// On génère un token
$token = bin2hex(random_bytes(60));
// On essaie d'écrire le token en base de données
try {
$user->setResetToken($token);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
} catch (\Exception $e) {
$this->addFlash('danger', $e->getMessage());
return $this->redirectToRoute('front_app_login');
}
// On génère l'URL de réinitialisation de mot de passe
$url = $this->generateUrl('front_app_reset_password_front', array('token' => $token),
UrlGeneratorInterface::ABSOLUTE_URL);
$mailerService->fromEmail = $user->getEmail();
$mailerService->fromName = $this->getParameter('SITE' . CURRENT_SITE_ID . '_HOST');
$mailerService->subject = 'Mot de passe oublié - ' . $this->getParameter('SITE' . CURRENT_SITE_ID . '_HOST');
$allRecipients[] = [
"nom" => $user->getLastName(),
"prenom" => $user->getFirstName(),
"email" => $user->getEmail(),
"type" => "to"
];
$htmlContent = $this->renderView("layouts/layouts_emails/forgotten_password.html.twig", [
'url' => $url
]);
$mailerService->sendMail($allRecipients, $htmlContent, [], null);
// On crée le message flash de confirmation
$this->addFlash('success', 'Un e-mail pour réinitialiser votre mot de passe vous a été envoyé !');
// On redirige vers la page de login
return $this->redirectToRoute('front_app_login');
}
// On envoie le formulaire à la vue
// return $this->render('security_front/forgotten_password.html.twig', ['emailForm' => $form->createView()]);
return $this->render('@main-app/front/front_customer_account/forgot_password.html.twig', [
'pageAccount' => 'mdpOublie',
'form' => $form->createView()
]);
}
#[Route(path: '/nouveau-mot-de-passe-front/{token}', name: 'front_app_reset_password_front')]
public function resetPassword(Request $request, string $token, UserPasswordEncoderInterface $passwordEncoder)
{
// On cherche un utilisateur avec le token donné
$user = $this->getDoctrine()->getRepository(AuthUser::class)->findOneBy(['reset_token' => $token]);
// Si l'utilisateur n'existe pas
if ($user === null) {
// On affiche une erreur
$this->addFlash('danger', 'Token Inconnu');
return $this->redirectToRoute('front_app_login');
}
// Si le formulaire est envoyé en méthode post
if ($request->isMethod('POST')) {
// On supprime le token
$user->setResetToken(null);
// On chiffre le mot de passe
$user->setPassword($passwordEncoder->encodePassword($user, $request->request->get('password')));
// On stocke
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
// On crée le message flash
$this->addFlash('success', 'Mot de passe mis à jour');
// On redirige vers la page de connexion
return $this->redirectToRoute('front_app_login');
} else {
// Si on n'a pas reçu les données, on affiche le formulaire
return $this->render('@main-app/security_front/reset_password.html.twig', ['token' => $token]);
}
}
}