src/Controller/RegistrationController.php line 53

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Entity\UserEnseignantDocument;
  5. use App\Form\RegistrationFormType;
  6. use App\Security\EmailVerifier;
  7. use App\Security\LoginFormAuthenticator;
  8. use App\Repository\UserRepository;
  9. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\Mime\Address;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. #use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  17. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface as UserPasswordEncoderInterface;
  18. #use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
  19. use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
  20. use Symfony\Component\Security\Core\Exception\UserNotFoundException;
  21. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
  22. use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
  23. use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
  24. use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
  25. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\PasswordUpgradeBadge;
  26. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
  27. use App\Event\InscriptionFormateurEvent;
  28. use App\Event\InscriptionEleveEvent;
  29. use Symfony\Component\EventDispatcher\EventDispatcher;
  30. //use App\EventListener\AdminUserEventListener;
  31. use App\EventSubscriber\UserEventSubscriber;
  32. use App\Exception\FlashableException;
  33. use App\Service\FileUploader;
  34. class RegistrationController extends AbstractController {
  35.     private $emailVerifier;
  36.     private $dispatcher;
  37.     public function __construct(\Doctrine\ORM\EntityManagerInterface $entityManagerEmailVerifier $emailVerifier,  UserRepository $userRepositoryUserEventSubscriber $userEventSubscriber) {
  38.         $this->emailVerifier $emailVerifier;
  39.         // Émetteur des évènements Application Utilisateur
  40.         $this->dispatcher = new EventDispatcher();
  41.         $this->dispatcher->addSubscriber($userEventSubscriber);
  42.         $this->entityManager $entityManager;
  43.     }
  44.     /**
  45.      * @Route("/register", name="app_register")
  46.      */
  47.     public function register(Request $requestUserPasswordEncoderInterface $passwordEncoderLoginFormAuthenticator $authenticatorFileUploader $fileUploader): Response {
  48.         $entityManager $this->entityManager;
  49.         $entityManager->getConnection()->beginTransaction(); // Annuler l'auto-commit pour faire un rollback si le mailing se passe mal
  50.         $user = new User();
  51.         $form $this->createForm(RegistrationFormType::class, $user);
  52.         $form->handleRequest($request);
  53.         $retour = array();
  54.         $retour['isNonVerified'] = false;
  55.         $retour['registrationForm'] = $form;
  56.         if ($form->isSubmitted()) {
  57.         try{
  58.             $client = new \Symfony\Component\HttpClient\CurlHttpClient();
  59.             if ($form->get('email2')->getData()) {
  60.                 return $this->redirectToRoute('app_register');
  61.             }
  62.             $response $client->request('POST''https://www.google.com/recaptcha/api/siteverify', ['body'=>['secret'=>$_ENV['RECAPTCHA_API_secret'], 'response'=>$request->request->get('g-recaptcha-response')]])->toArray();
  63.             $valid $form->isValid();
  64.             if(!$valid)throw new FlashableException('Le formulaire n\'est pas valide.');
  65.             // if(!$response['success']){
  66.             //     $this->addFlash(
  67.             //         'error',
  68.             //         'Échec recaptcha'
  69.             //     );
  70.             //     $valid = false;
  71.             // }
  72.             if($_ENV['APP_ENV'] == 'dev'){
  73.                 // throw new \Exception('recaptcha failing : '.implode(', ', $response['error-codes']));
  74.             }
  75.             // encode the plain password
  76.             $user->setPassword(
  77.                 $passwordEncoder->hashPassword(
  78.                     $user,
  79.                     $form->get('plainPassword')->getData()
  80.                 )
  81.             );
  82.             // L'utilisateur a-t-il au minimum 16 ans ? Eg: conduite accompagnée ?
  83.             $user->setIsSuspend(0);
  84.             $statut $form->get('statut')->getData();
  85.             $autorisation $form->get('autorisation')->getData();
  86.             if ($autorisation) {
  87.                 $fileUploader->setDuplicateModeReplace();
  88.                 $fileUploader->setTargetDirectoryByUser($user);
  89.                 $fileUploader->setUpload($autorisation);
  90.                 $Document = new UserEnseignantDocument;
  91.                 $Document->setDoc('autorisation');
  92.                 $user->addUserEnseignantDocument($Document);
  93.                 $fileUploader->setDocument($Document);
  94.                 $fileUploader->setTargetDirectoryByDocument($Document);
  95.                 $uploaded $fileUploader->upload();
  96.                 if(!$uploaded){
  97.                     $this->addFlash(
  98.                         'error',
  99.                         $fileUploader->getError()
  100.                     );
  101.                 }
  102.                 $entityManager->persist($Document);
  103.             }
  104.             $num_autorisation $form->get('num_autorisation')->getData();
  105.             if($num_autorisation){
  106.                 $Document = new UserEnseignantDocument;
  107.                 $Document->setDoc('num_autorisation');
  108.                 $Document->setType('text');
  109.                 $Document->setContenu($num_autorisation);
  110.                 $user->addUserEnseignantDocument($Document);
  111.                 $entityManager->persist($Document);
  112.             }
  113.             
  114.             $Event false;
  115.             // Inscription d'un nouvel élève
  116.             if ($statut == '0'
  117.             {
  118.                 $user->setRoles(array('ROLE_ELEVE'));
  119.                 $Event = new InscriptionEleveEvent($user);
  120.             }
  121.             // Inscription d'un nouveau formateur
  122.             elseif ($statut == '1'
  123.             {
  124.                 $user->setRoles(array('ROLE_PROF'));
  125.                 $Event = new InscriptionFormateurEvent($user);
  126.             }
  127.             if(empty($user->getRoles())){
  128.                 throw new FlashableException('Aucun rôle n\'a été attribué à l\'utilisateur.');
  129.             }
  130.             // Tentative de génération du lien de confirmation et mail à l'utilisateur
  131.             $entityManager->persist($user);
  132.             $entityManager->flush();
  133.             if ($Event) {// Dispatch de l'évènement de l'inscription => maj de app_user_event
  134.                 $this->dispatcher->dispatch($Event$Event::NAME);
  135.             }
  136.             try {
  137.                 $response $this->sendConfirmationEmail($user$request);
  138.                 $data json_decode($response->getContent(), true);
  139.                 if (!empty($data['success'])) {
  140.                     $this->addFlash('success'$data['success']);
  141.                 }
  142.                 if (!empty($data['error'])) {
  143.                     throw new \Exception($data['error']);
  144.                 }
  145.                 $entityManager->getConnection()->commit();
  146.                 // On redirige l'utilisateur vers le formulaire de connexion
  147.                 return $this->redirectToRoute('app_login');
  148.             }
  149.             catch(\Exception $e)
  150.             {
  151.                 // On annule la transaction, l\'emailing n'a pas fonctionné
  152.                 $entityManager->getConnection()->rollback();
  153.                 throw new FlashableException($e->getMessage());
  154.             }
  155.                 
  156.             $userRepository $entityManager->getRepository(User::class);
  157.             $qb $userRepository->createQueryBuilder();
  158.             $qb $userRepository->ByMail($qb$form->get('email')->getData());
  159.             $qb $userRepository->notVerified($qb);
  160.             $qb->select('count('.$userRepository::ALIAS.'.id)');
  161.             $retour['isNonVerified'] = $qb->getQuery()->getSingleScalarResult()>0;
  162.         }
  163.         catch(FlashableException $e) {
  164.             $this->addFlash('error''Une erreur est survenue durant le traitement du formulaire : '.$e->getMessage());
  165.             // On annule la transaction, quelque chose n'a pas fonctionné
  166.             // return $this->redirectToRoute('app_register');
  167.         }
  168.         }
  169.         foreach($form->getErrors()as$error){
  170.             echo$error->getMessage().'<br>'.PHP_EOL;
  171.             $this->addFlash('error'$error->getMessage());
  172.         }
  173.         if (!$form->isSubmitted()) {
  174.             $form->get('agreeTerms')->setData(false);
  175.         }
  176.         return $this->renderForm('registration/register.html.twig'$retour);
  177.     }
  178.     /**
  179.      * @Route("/register/send_confirm/{email}", name="app_send_confirm")
  180.      * Security("is_granted('ROLE_SUPER_ADMIN') or is_granted('ROLE_ADMIN') or is_granted('ROLE_ELEVE')", statusCode=404, message="Ressource non trouvée")
  181.      */
  182.     public function sendConfirmationEmail(User $userRequest $request):Response
  183.     {
  184.         if($this->getUser() and $this->getUser()->isEleve() and $this->getUser()->getId() != $user->getId())
  185.             throw $this->createNotFoundException();
  186.         $data = array();
  187.         try {
  188.             $this->emailVerifier->sendEmailConfirmation(
  189.                 'app_verify_email',
  190.                 $user,
  191.                 (new TemplatedEmail())
  192.                     ->to($user->getEmail())
  193.                     ->subject('Confirmation d\'adresse mail')
  194.                     ->htmlTemplate('registration/confirmation_email.html.twig')
  195.             );
  196.             $data['success'] = "Un mail vous a été envoyé à l'adresse \"".$user->getEmail()."\", merci de bien vouloir cliquer sur le lien pour valider votre compte.";
  197.         }
  198.         catch(\Exception $e)
  199.         {
  200.             $data['error'] = "L'email renseigné n'est pas valide.";
  201.         }
  202.         if($request->isXmlHttpRequest() || $request->getPreferredFormat()=='json') {
  203.             return $this->json($data);
  204.         }
  205.         if (!empty($data['error'])) {
  206.             $this->addFlash('error'$data['error']);
  207.         }
  208.         if (!empty($data['success'])) {
  209.             $this->addFlash('success'$data['success']);
  210.         }
  211.         return $this->redirectToRoute('app_login');
  212.     }
  213.     private function autologin(Passport $passport) {
  214.         return $passport;
  215.     }
  216.     /**
  217.      * @Route("/verify/email", name="app_verify_email")
  218.      */
  219.     public function verifyUserEmail(Request $requestUserRepository $userRepository): Response {
  220.         
  221.         $id $request->get('id');
  222.         if (null === $id) {
  223.             return $this->redirectToRoute('app_register');
  224.         }
  225.         $user $userRepository->find($id);
  226.         if (null === $user) {
  227.             return $this->redirectToRoute('app_register');
  228.         }
  229.         // validate email confirmation link, sets User::isVerified=true and persists
  230.         try {
  231.             $this->emailVerifier->handleEmailConfirmation($request$user);
  232.         } catch (VerifyEmailExceptionInterface $exception) {
  233.             $this->addFlash('verify_email_error'$exception->getReason());
  234.             return $this->redirectToRoute('app_register');
  235.         }
  236.         // @TODO Change the redirect on success and handle or remove the flash message in your templates
  237.         $this->addFlash('success''Votre adresse mail a été vérifiée.');
  238.         if($user->isProf())
  239.         return $this->redirectToRoute('enseignant');
  240.         if($user->isEleve())
  241.         return $this->redirectToRoute('eleve');
  242.         return $this->redirectToRoute('login');
  243.     }
  244. }