src/Controller/ResetPasswordController.php line 48

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Admin;
  4. use App\Entity\Child;
  5. use App\Entity\Guardian;
  6. use App\Entity\Teacher;
  7. use App\Form\ChangePasswordFormType;
  8. use App\Form\ResetPasswordRequestFormType;
  9. use App\Repository\ResetPasswordRequestRepository;
  10. use App\Service\CredentialsService;
  11. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  12. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  13. use Symfony\Component\HttpFoundation\RedirectResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\Mailer\MailerInterface;
  17. use Symfony\Component\Mime\Address;
  18. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  21. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  22. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  23. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  24. /**
  25. * @Route("/reset-password")
  26. */
  27. class ResetPasswordController extends AbstractController
  28. {
  29. use ResetPasswordControllerTrait;
  30. private $resetPasswordHelper;
  31. public function __construct(ResetPasswordHelperInterface $resetPasswordHelper)
  32. {
  33. $this->resetPasswordHelper = $resetPasswordHelper;
  34. }
  35. /**
  36. * Display & process form to request a password reset.
  37. *
  38. * @Route("", name="app_forgot_password_request")
  39. */
  40. public function request(Request $request, MailerInterface $mailer): Response
  41. {
  42. $form = $this->createForm(ResetPasswordRequestFormType::class);
  43. $form->handleRequest($request);
  44. if ($form->isSubmitted() && $form->isValid()) {
  45. return $this->processSendingPasswordResetEmail(
  46. $form->get('email')->getData(),
  47. $mailer
  48. );
  49. }
  50. return $this->render('reset_password/request.html.twig', [
  51. 'requestForm' => $form->createView(),
  52. ]);
  53. }
  54. /**
  55. * Confirmation page after a user has requested a password reset.
  56. *
  57. * @Route("/check-email", name="app_check_email")
  58. */
  59. public function checkEmail(): Response
  60. {
  61. // Generate a fake token if the user does not exist or someone hit this page directly.
  62. // This prevents exposing whether or not a user was found with the given email address or not
  63. if (null === ($resetToken = $this->getTokenObjectFromSession())) {
  64. $resetToken = $this->resetPasswordHelper->generateFakeResetToken();
  65. }
  66. return $this->render('reset_password/check_email.html.twig', [
  67. 'resetToken' => $resetToken,
  68. ]);
  69. }
  70. /**
  71. * Validates and process the reset URL that the user clicked in their email.
  72. *
  73. * @Route("/reset/{token}", name="app_reset_password")
  74. */
  75. public function reset(Request $request,CredentialsService $credentialsService, UserPasswordHasherInterface $userPasswordHasher, string $token = null, ResetPasswordRequestRepository $resetPasswordRequestRepository): Response
  76. {
  77. /*if ($token) {
  78. // We store the token in session and remove it from the URL, to avoid the URL being
  79. // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  80. $this->storeTokenInSession($token);
  81. return $this->redirectToRoute('app_reset_password');
  82. }
  83. $token = $this->getTokenFromSession();*/
  84. if (null === $token) {
  85. // throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  86. return $this->redirectToRoute('app_forgot_password_request');
  87. }
  88. try {
  89. $user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  90. } catch (ResetPasswordExceptionInterface $e) {
  91. $this->addFlash('reset_password_error', sprintf(
  92. 'There was a problem validating your reset request - %s',
  93. $e->getReason()
  94. ));
  95. return $this->redirectToRoute('app_forgot_password_request');
  96. }
  97. // The token is valid; allow the user to change their password.
  98. $form = $this->createForm(ChangePasswordFormType::class);
  99. $form->handleRequest($request);
  100. if ($form->isSubmitted() && $form->isValid()) {
  101. // A password reset token should be used only once, remove it.
  102. // $this->resetPasswordHelper->removeResetRequest($token);
  103. $tokenObj = $resetPasswordRequestRepository->findOneBy(['guardian' => $user]);
  104. if($tokenObj)
  105. {
  106. $this->getDoctrine()->getManager()->remove($tokenObj);
  107. $this->getDoctrine()->getManager()->flush();
  108. }
  109. $tokenObj = $resetPasswordRequestRepository->findOneBy(['admin' => $user]);
  110. if($tokenObj)
  111. {
  112. $this->getDoctrine()->getManager()->remove($tokenObj);
  113. $this->getDoctrine()->getManager()->flush();
  114. }
  115. $tokenObj = $resetPasswordRequestRepository->findOneBy(['teacher' => $user]);
  116. if($tokenObj)
  117. {
  118. $this->getDoctrine()->getManager()->remove($tokenObj);
  119. $this->getDoctrine()->getManager()->flush();
  120. }
  121. $tokenObj = $resetPasswordRequestRepository->findOneBy(['child' => $user]);
  122. if($tokenObj)
  123. {
  124. $this->getDoctrine()->getManager()->remove($tokenObj);
  125. $this->getDoctrine()->getManager()->flush();
  126. }
  127. // Encode the plain password, and set it.
  128. $encodedPassword = $userPasswordHasher->hashPassword(
  129. $user,
  130. $form->get('plainPassword')->getData()
  131. );
  132. if($user instanceof Child){
  133. $credentialsService->sendChildrenCredentialsEmail($user->getGuardian(), $user, $form->get('plainPassword')->getData());
  134. }
  135. $user->setPassword($encodedPassword);
  136. $this->getDoctrine()->getManager()->flush();
  137. // The session is cleaned up after the password has been changed.
  138. $this->cleanSessionAfterReset();
  139. return $this->redirectToRoute('app_login');
  140. }
  141. return $this->render('reset_password/reset.html.twig', [
  142. 'resetForm' => $form->createView(),
  143. ]);
  144. }
  145. private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer): RedirectResponse
  146. {
  147. $user = $this->getDoctrine()->getRepository(Guardian::class)->findOneBy([
  148. 'email' => $emailFormData,
  149. ]);
  150. if (!$user) {
  151. $user = $this->getDoctrine()->getRepository(Admin::class)->findOneBy([
  152. 'email' => $emailFormData,
  153. ]);
  154. }
  155. if (!$user) {
  156. $user = $this->getDoctrine()->getRepository(Teacher::class)->findOneBy([
  157. 'email' => $emailFormData,
  158. ]);
  159. }
  160. if (!$user) {
  161. $user = $this->getDoctrine()->getRepository(Child::class)->findOneBy([
  162. 'email' => $emailFormData,
  163. ]);
  164. }
  165. // Do not reveal whether a user account was found or not.
  166. if (!$user) {
  167. return $this->redirectToRoute('app_check_email');
  168. }
  169. try {
  170. $resetToken = $this->resetPasswordHelper->generateResetToken($user);
  171. } catch (ResetPasswordExceptionInterface $e) {
  172. // If you want to tell the user why a reset email was not sent, uncomment
  173. // the lines below and change the redirect to 'app_forgot_password_request'.
  174. // Caution: This may reveal if a user is registered or not.
  175. //
  176. // $this->addFlash('reset_password_error', sprintf(
  177. // 'There was a problem handling your password reset request - %s',
  178. // $e->getReason()
  179. // ));
  180. return $this->redirectToRoute('app_check_email');
  181. }
  182. $email = (new TemplatedEmail())
  183. ->from(new Address('info@corepetitus.lt', 'Corepetitus'))
  184. ->to($user->getEmail())
  185. ->subject('Corepetitus slaptažodžio atstatymas')
  186. ->htmlTemplate('reset_password/email.html.twig')
  187. ->context([
  188. 'resetToken' => $resetToken,
  189. ])
  190. ;
  191. $mailer->send($email);
  192. // Store the token object in session for retrieval in check-email route.
  193. $this->setTokenObjectInSession($resetToken);
  194. return $this->redirectToRoute('app_check_email');
  195. }
  196. }