src/Controller/User/SecurityController.php line 146

Open in your IDE?
  1. <?php
  2. namespace App\Controller\User;
  3. use App\Entity\User\User;
  4. use App\Form\User\InscriptionType;
  5. use App\Repository\Fiche\FicheBatimentRepository;
  6. use App\Repository\User\UserRepository;
  7. use App\Security\User\FormLoginAuthenticator;
  8. use Doctrine\Persistence\ManagerRegistry;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  11. use Symfony\Component\Form\FormError;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\Mailer\MailerInterface;
  15. use Symfony\Component\Mime\Email;
  16. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  17. use Symfony\Component\Routing\Annotation\Route;
  18. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  19. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  20. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  21. use App\Form\User\LoginType;
  22. use App\Form\User\MotDePasseOublieType;
  23. #[Route(path'/'name'user_security_')]
  24. class SecurityController extends AbstractController
  25. {
  26.     const MSG_ERROR_MAIL_INEXISTANT 'Cette adresse mail n\'est pas enregistrée dans la base de données.';
  27.     const MSG_PASSWORD_CHANGED 'Votre mot de passe a été modifié et envoyé à votre adresse mail.';
  28.     const MSG_ACTIVATION_SUCCESS 'Votre compte a bien été activé.';
  29.     const MSG_ACTIVATION_ERROR 'L\'activation n\'a pas pû être effectuée.';
  30.     private $pathAuthenticationHome;
  31.     public function __construct(ParameterBagInterface $theParameterBag)
  32.     {
  33.         $this->pathAuthenticationHome 'postConnexion';
  34.     }
  35.     #[Route(path'/login'name'login')]
  36.     public function login(
  37.         AuthenticationUtils $authenticationUtils,
  38.         Request $theRequest,
  39.         FicheBatimentRepository $theFicheBatimentRepository
  40.     ): Response
  41.     {
  42.         if ($this->getUser() != null) {
  43.             return $this->redirectToRoute($this->pathAuthenticationHome);
  44.         }
  45.         $theEM $this->getDoctrine()->getManager();
  46.         // retrouver une erreur d'authentification s'il y en a une
  47.         $error $authenticationUtils->getLastAuthenticationError();
  48.         // retrouver le dernier identifiant de connexion utilisé
  49.         $lastUsername $authenticationUtils->getLastUsername();
  50.         $theForm $this->createForm(LoginType::class, null, array('username' => $lastUsername));
  51.         $theForm->handleRequest($theRequest);
  52.         if ($theForm->isSubmitted()) {
  53.         }
  54.         if ($error != null) {
  55.             $theForm->addError(new FormError($error->getMessageKey()));
  56.         }
  57.         return $this->render('user/security/login.html.twig', [
  58.                 'theForm' => $theForm->createView(),
  59.                 'last_username' => $lastUsername,
  60.             ]
  61.         );
  62.     }
  63.     #[Route(path'/activation/{activationToken}'name'activation')]
  64.     public function activation(UserRepository $theUserRepositoryManagerRegistry $theManagerRegistry $activationToken)
  65.     {
  66.         $theUser $theUserRepository->findByActivationToken($activationToken);
  67.         if ($theUser != null) {
  68.             $theUser->setIsEnabled(true);
  69.             $theUser->setActivationToken(null);
  70.             $theManagerRegistry->getManager()->flush();
  71.             $this->addFlash('success'self::MSG_ACTIVATION_SUCCESS);
  72.         } else {
  73.             $this->addFlash('danger'self::MSG_ACTIVATION_ERROR);
  74.         }
  75.         return $this->redirectToRoute('user_security_login');
  76.     }
  77.     #[Route(path'/inscription'name'inscription')]
  78.     public function inscription(
  79.         Request $theRequest,
  80.         ManagerRegistry $theManagerRegistry,
  81.         UserPasswordHasherInterface $theUserPasswordHasherInterface,
  82.         TokenStorageInterface $theTokenStorage,
  83.         FormLoginAuthenticator $theFormLoginAuthenticator,
  84.         MailerInterface $theMailer
  85.     ): Response
  86.     {
  87.         if ($this->getUser() != null) {
  88.             return $this->redirectToRoute($this->pathAuthenticationHome);
  89.         }
  90.         $theUser = new User();
  91.         $theForm $this->createForm(InscriptionType::class, $theUser);
  92.         $theForm->handleRequest($theRequest);
  93.         if ($theForm->isSubmitted() && $theForm->isValid()) {
  94.             $theUser->setPassword(
  95.                 $theUserPasswordHasherInterface->hashPassword($theUser$theUser->getPlainPassword())
  96.             );
  97.             $theUser->setActivationToken(bin2hex(random_bytes(16)));
  98.             $theUser->setRolePrincipal('ROLE_UTILISATEUR');
  99.             $theEM $theManagerRegistry->getManager();
  100.             $theEM->persist($theUser);
  101.             $theEM->flush();
  102.             $theEmail $this->getTheEmailInscription($theUser);
  103.             $theMailer->send($theEmail);
  104.             $theToken = new UsernamePasswordToken($theUsernull'main'$theUser->getRoles());
  105.             $theTokenStorage->setToken($theToken);
  106.             $theRequest->getSession()->set('_security_main'serialize($theToken));
  107.             return $theFormLoginAuthenticator->onAuthenticationSuccess($theRequest$theToken'app_user_provider');
  108.         } else {
  109.             $theResponse $this->render('user/security/inscription.html.twig', [
  110.                     'theForm' => $theForm->createView(),
  111.                 ]
  112.             );
  113.         }
  114.         return $theResponse;
  115.     }
  116.     /**
  117.      * @param Request $theRequest
  118.      * @param UserRepository $theUserRepository
  119.      * @return Response
  120.      */
  121.     #[Route(path'/mot-de-passe-oublie'name'mot_de_passe_oublie')]
  122.     public function motDePasseOublie(
  123.         Request $theRequest,
  124.         UserRepository $theUserRepository,
  125.         UserPasswordHasherInterface $theUserPasswordHasherInterface,
  126.         MailerInterface $theMailer,
  127.         ManagerRegistry $theManagerRegistry
  128.     )
  129.     {
  130.         $theForm $this->createForm(MotDePasseOublieType::class);
  131.         $theForm->handleRequest($theRequest);
  132.         if ($theForm->isSubmitted() && $theForm->isValid()) {
  133.             $email $theForm->get('email')->getData();
  134.             $theUser $theUserRepository->findOneByEmail($email);
  135.             if ($theUser == null) {
  136.                 $theForm->addError(new FormError(self::MSG_ERROR_MAIL_INEXISTANT));
  137.             } else {
  138.                 $theUser->setPlainPassword(bin2hex(random_bytes(8)));
  139.                 $theEmail $this->getTheEmailMotDePasseOublie($theUser);
  140.                 $theMailer->send($theEmail);
  141.                 $encodedPassword $theUserPasswordHasherInterface->hashPassword($theUser$theUser->getPlainPassword());
  142.                 $theUser->setPassword($encodedPassword);
  143.                 $theManagerRegistry->getManager()->flush();
  144.                 $this->addFlash('success'self::MSG_PASSWORD_CHANGED);
  145.             }
  146.         }
  147.         return $this->render('user/security/mot-de-passe-oublie.html.twig', array(
  148.             'theForm' => $theForm->createView()
  149.         ));
  150.     }
  151.     private function getTheEmailMotDePasseOublie(User $theUser)
  152.     {
  153.         $theEmail = new Email();
  154.         $theEmail
  155.             ->subject('SOBRO - Nouveau mot de passe')
  156.             ->text($this->renderView('user/security/mot-de-passe-oublie.txt.twig', array(
  157.                 'theUser' => $theUser
  158.             )))
  159.             ->addTo($theUser->getEmail())
  160.             ->addFrom('admin@sobro.fr');
  161.         return $theEmail;
  162.     }
  163.     private function getTheEmailInscription(User $theUser)
  164.     {
  165.         $theEmail = new Email();
  166.         $theEmail
  167.             ->subject('SOBRO - Inscription')
  168.             ->text($this->renderView('user/security/inscription.txt.twig', array(
  169.                 'theUser' => $theUser
  170.             )))
  171.             ->addTo($theUser->getEmail())
  172.             ->addCc('admin@sobro.fr')    
  173.             ->addFrom('admin@sobro.fr');
  174.         return $theEmail;
  175.     }
  176.     #[Route(path'/logout'name'logout')]
  177.     public function logout(Request $theRequest): void
  178.     {
  179.         throw new \Exception('This should never be reached!');
  180.     }
  181. }