src/Controller/RegistrationController.php line 39

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\RegistrationFormType;
  5. use App\Form\ResetFormType;
  6. use App\Form\ResetPasswordFormType;
  7. use App\Repository\UserRepository;
  8. use App\Security\EmailVerifier;
  9. use App\Security\AppFormAuthenticator;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  12. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\Mime\Address;
  16. use Symfony\Component\Routing\Annotation\Route;
  17. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  18. use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
  19. use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
  20. use SymfonyCasts\Bundle\VerifyEmail\VerifyEmailHelperInterface;
  21. class RegistrationController extends AbstractController
  22. {
  23. private $emailVerifier;
  24. public function __construct(EmailVerifier $emailVerifier)
  25. {
  26. $this->emailVerifier = $emailVerifier;
  27. }
  28. /**
  29. * @Route("/register", name="app_register")
  30. */
  31. public function register(Request $request, UserPasswordEncoderInterface $passwordEncoder, GuardAuthenticatorHandler $guardHandler, AppFormAuthenticator $authenticator): Response
  32. {
  33. $user = new User();
  34. $form = $this->createForm(RegistrationFormType::class, $user);
  35. $form->handleRequest($request);
  36. if ($form->isSubmitted() && $form->isValid()) {
  37. // encode the plain password
  38. $user->setPassword(
  39. $passwordEncoder->encodePassword(
  40. $user,
  41. $form->get('plainPassword')->getData()
  42. )
  43. );
  44. // set username equal to email for now
  45. $user->setUsername($user->getEmail());
  46. $user->setEmailCanonical(mb_strtolower($user->getEmail()));
  47. $user->setUsernameCanonical(mb_strtolower($user->getEmail()));
  48. $entityManager = $this->getDoctrine()->getManager();
  49. $entityManager->persist($user);
  50. $entityManager->flush();
  51. // generate a signed url and email it to the user
  52. $this->emailVerifier->sendEmailConfirmation('app_verify_email', $user,
  53. (new TemplatedEmail())
  54. ->from(new Address('noreply@getrealtrialtool.eu', 'GetReal Trial Tool'))
  55. ->to($user->getEmail())
  56. ->subject('Please Confirm your Email')
  57. ->htmlTemplate('registration/confirmation_email.html.twig')
  58. );
  59. // do anything else you need here, like send an email
  60. // old code: log the user in
  61. // return $guardHandler->authenticateUserAndHandleSuccess(
  62. // $user,
  63. // $request,
  64. // $authenticator,
  65. // 'main' // firewall name in security.yaml
  66. // );
  67. return $this->render('registration/check_mail.html.twig', [
  68. ]);
  69. }
  70. return $this->render('registration/register.html.twig', [
  71. 'registrationForm' => $form->createView(),
  72. ]);
  73. }
  74. /**
  75. * @Route("/resetting/request", name="app_password_reset_request")
  76. */
  77. public function resetRequest(Request $request, UserRepository $userRepository, GuardAuthenticatorHandler $guardHandler, AppFormAuthenticator $authenticator): Response
  78. {
  79. $user = new User();
  80. $form = $this->createForm(ResetFormType::class, $user);
  81. $form->handleRequest($request);
  82. if ($form->isSubmitted() && $form->isValid()) {
  83. // check if user exists
  84. $resettingUser = $userRepository->findOneBy(['emailCanonical' => mb_strtolower($user->getEmail())]);
  85. $this->emailVerifier->sendEmailConfirmation('app_password_reset', $resettingUser,
  86. (new TemplatedEmail())
  87. ->from(new Address('noreply@getrealtrialtool.eu', 'GetReal Trial Tool'))
  88. ->to($user->getEmail())
  89. ->subject('Password reset request')
  90. ->htmlTemplate('registration/reset_password_email.html.twig')
  91. );
  92. return $this->render('registration/reset_password_request_done.html.twig', [
  93. 'registrationForm' => $form->createView(),
  94. ]);
  95. }
  96. return $this->render('registration/reset_password_request.html.twig', [
  97. 'registrationForm' => $form->createView(),
  98. ]);
  99. }
  100. /**
  101. * @Route("/resetting/password", name="app_password_reset")
  102. */
  103. public function resetPassword(Request $request, UserPasswordEncoderInterface $passwordEncoder,
  104. GuardAuthenticatorHandler $guardHandler, AppFormAuthenticator $authenticator,
  105. VerifyEmailHelperInterface $verifyEmailHelper,
  106. UserRepository $userRepository, EntityManagerInterface $entityManager
  107. ): Response
  108. {
  109. $id = $request->get('id'); // retrieve the user id from the url
  110. // Verify the user id exists and is not null
  111. if (null === $id) {
  112. $this->addFlash('verify_email_error', 'id missing');
  113. return $this->redirectToRoute('app_password_reset_request');
  114. }
  115. $user = $userRepository->find($id);
  116. // Ensure the user exists in persistence
  117. if (null === $user) {
  118. $this->addFlash('verify_email_error', 'user not found');
  119. return $this->redirectToRoute('app_password_reset_request');
  120. }
  121. // validate email confirmation link, sets User::isVerified=true and persists
  122. try {
  123. $verifyEmailHelper->validateEmailConfirmation($request->getUri(), $user->getId(), $user->getEmail());
  124. // update password
  125. $userFormModel = new User();
  126. $form = $this->createForm(ResetPasswordFormType::class, $userFormModel);
  127. $form->handleRequest($request);
  128. if ($form->isSubmitted() && $form->isValid()) {
  129. $user->setPassword(
  130. $passwordEncoder->encodePassword(
  131. $user,
  132. $form->get('plainPassword')->getData()
  133. )
  134. );
  135. $entityManager->flush();
  136. $this->addFlash('success', 'Your password has been updated.');
  137. return $this->redirectToRoute('app_login');
  138. }
  139. return $this->render('registration/reset_password.html.twig', [
  140. 'registrationForm' => $form->createView(),
  141. ]);
  142. } catch (VerifyEmailExceptionInterface $exception) {
  143. $this->addFlash('verify_email_error', $exception->getReason());
  144. return $this->redirectToRoute('app_register');
  145. }
  146. }
  147. /**
  148. * @Route("/verify/email", name="app_verify_email")
  149. */
  150. public function verifyUserEmail(Request $request, UserRepository $userRepository): Response
  151. {
  152. // This is if you want to validated on a logged in session
  153. // $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  154. $id = $request->get('id'); // retrieve the user id from the url
  155. // Verify the user id exists and is not null
  156. if (null === $id) {
  157. $this->addFlash('verify_email_error', 'id missing');
  158. return $this->redirectToRoute('app_register');
  159. }
  160. $user = $userRepository->find($id);
  161. // Ensure the user exists in persistence
  162. if (null === $user) {
  163. $this->addFlash('verify_email_error', 'user not found');
  164. return $this->redirectToRoute('app_register');
  165. }
  166. // validate email confirmation link, sets User::isVerified=true and persists
  167. try {
  168. $this->emailVerifier->handleEmailConfirmation($request, $user);
  169. } catch (VerifyEmailExceptionInterface $exception) {
  170. $this->addFlash('verify_email_error', $exception->getReason());
  171. return $this->redirectToRoute('app_register');
  172. }
  173. $this->addFlash('success', 'Your email address has been verified.');
  174. return $this->redirectToRoute('app_login');
  175. }
  176. }