src/Controller/Auth/RegistrationController.php line 64

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Auth;
  3. use App\Entity\Auth\User;
  4. use App\Event\UserCreatedEvent;
  5. use App\Event\UserUpdatedEvent;
  6. use App\Form\Auth\RegistrationFormType;
  7. use App\Infrastructure\Social\SocialLoginService;
  8. use App\Security\AppAuthenticator;
  9. use App\Service\ProfileService;
  10. use App\Service\TokenGeneratorService;
  11. use DateTime;
  12. use Doctrine\ORM\EntityManagerInterface;
  13. use Exception;
  14. use Psr\EventDispatcher\EventDispatcherInterface;
  15. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  16. use Symfony\Component\Form\FormError;
  17. use Symfony\Component\HttpFoundation\RedirectResponse;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  21. use Symfony\Component\Routing\Annotation\Route;
  22. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  23. use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
  24. class RegistrationController extends AbstractController
  25. {
  26.     /**
  27.      * @Route("/register", name="app_register")
  28.      * @param Request $request
  29.      * @param AuthorizationCheckerInterface $checker
  30.      * @param UserPasswordHasherInterface $userPasswordHasher
  31.      * @param SocialLoginService $socialLoginService
  32.      * @param UserAuthenticatorInterface $authenticator
  33.      * @param AppAuthenticator $appAuthenticator
  34.      * @param EventDispatcherInterface $dispatcher
  35.      * @param TokenGeneratorService $tokenGeneratorService
  36.      * @param EntityManagerInterface $entityManager
  37.      * @param ProfileService $service
  38.      * @return Response
  39.      * @throws Exception
  40.      */
  41.     public function register(Request $requestAuthorizationCheckerInterface $checker,
  42.                              UserPasswordHasherInterface $userPasswordHasher,
  43.                              SocialLoginService $socialLoginService,
  44.                              UserAuthenticatorInterface $authenticator,
  45.                              AppAuthenticator $appAuthenticator,
  46.                              EventDispatcherInterface $dispatcher,
  47.                              TokenGeneratorService $tokenGeneratorService,
  48.                              EntityManagerInterface $entityManagerProfileService $service): Response
  49.     {
  50.         if ($this->getUser()) {
  51.             if ($checker->isGranted('ROLE_ADMIN')) {
  52.                 return $this->redirectToRoute('admin_dashboard');
  53.             }
  54.             return $this->redirectToRoute('homepage');
  55.         }
  56.         $user = new User();
  57.         $rootErrors = [];
  58.         // Si l'utilisateur provient de l'oauth, on préremplit ses données
  59.         $isOauthUser $request->get('oauth') ? $socialLoginService->hydrate($user) : false;
  60.         $form $this->createForm(RegistrationFormType::class, $user);
  61.         $form->handleRequest($request);
  62.         if ($form->isSubmitted() && $form->isValid()) {
  63.             // encode the plain password
  64.             $user->setPassword(
  65.                 $form->has('plainPassword') ? $userPasswordHasher->hashPassword(
  66.                     $user,
  67.                     $form->get('plainPassword')->getData()
  68.                 ) : '');
  69.             $user->setConfirmationToken($isOauthUser null $tokenGeneratorService->generate(60));
  70.             $user->setUsername($isOauthUser null $user->getEmail());
  71.             $user->setRoles([$user->getProfile()->getToken()]);
  72.             $user->setIsParent($user->getProfile()->getSlug() === 'parent');
  73.             $entityManager->persist($user);
  74.             $entityManager->flush();
  75.             $dispatcher->dispatch(new UserCreatedEvent($user$isOauthUser));
  76.             if (!$user->isIsParent() && !$user->isIsAdmin()) {
  77.                 $dispatcher->dispatch(new UserUpdatedEvent($user));
  78.             }
  79.             if ($isOauthUser) {
  80.                 $this->addFlash(
  81.                     'success',
  82.                     'Votre compte a été créé avec succès'
  83.                 );
  84.                 return $authenticator->authenticateUser($user$appAuthenticator$request) ?: $this->redirectToRoute('profile_edit');
  85.             }
  86.             $this->addFlash(
  87.                 'success',
  88.                 'Un message avec un lien de confirmation vous a été envoyé par mail. Veuillez suivre ce lien pour activer votre compte.'
  89.             );
  90.             return $this->redirectToRoute('app_login');
  91.         } elseif ($form->isSubmitted()) {
  92.             /** @var FormError $error */
  93.             foreach ($form->getErrors() as $error) {
  94.                 if (null === $error->getCause()) {
  95.                     $rootErrors[] = $error;
  96.                 }
  97.             }
  98.         }
  99.         return $this->render('registration/register.html.twig', [
  100.             'form' => $form->createView(),
  101.             'link' => 'registration',
  102.             'errors' => $rootErrors,
  103.             'oauth_registration' => $request->get('oauth'),
  104.             'oauth_type' => $socialLoginService->getOauthType(),
  105.         ]);
  106.     }
  107.     /**
  108.      * @Route("/inscription/confirmation/{id<\d+>}", name="register_confirm")
  109.      * @param User $user
  110.      * @param Request $request
  111.      * @param EventDispatcherInterface $dispatcher
  112.      * @param EntityManagerInterface $em
  113.      * @param AppAuthenticator $appAuthenticator
  114.      * @param UserAuthenticatorInterface $authenticator
  115.      * @return RedirectResponse
  116.      */
  117.     public function confirmToken(User $userRequest $requestEventDispatcherInterface $dispatcher,
  118.                                  EntityManagerInterface $emAppAuthenticator $appAuthenticator,
  119.                                  UserAuthenticatorInterface $authenticator): RedirectResponse
  120.     {
  121.         $token $request->get('token');
  122.         if (empty($token) || $token !== $user->getConfirmationToken()) {
  123.             $this->addFlash('error'"Ce token n'est pas valide");
  124.             return $this->redirectToRoute('app_register');
  125.         }
  126.         if ($user->getCreatedAt() < new DateTime('-2 hours')) {
  127.             $this->addFlash('error''Ce token a expiré');
  128.             return $this->redirectToRoute('app_register');
  129.         }
  130.         $user->setIsVerified(true);
  131.         $user->setConfirmationToken(null);
  132.         $em->flush();
  133.         $dispatcher->dispatch(new UserUpdatedEvent($user));
  134.         $this->addFlash('success''Votre compte a été validé. Vous êtes maintenant connecté');
  135.         $authenticator->authenticateUser($user$appAuthenticator$request);
  136.         return $this->redirectToRoute('homepage');
  137.     }
  138. }