src/Controller/User/SecurityController.php line 102

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