src/Controller/SecurityController.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Entity\ChangePassword;
  5. use App\Form\ChangePasswordType;
  6. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  12. class SecurityController extends AbstractController
  13. {
  14. /**
  15. * @Route("/login", name="app_login")
  16. */
  17. public function login(AuthenticationUtils $authenticationUtils): Response
  18. {
  19. if ($this->getUser()) {
  20. return $this->redirectToRoute('homepage');
  21. }
  22. // get the login error if there is one
  23. $error = $authenticationUtils->getLastAuthenticationError();
  24. // last username entered by the user
  25. $lastUsername = $authenticationUtils->getLastUsername();
  26. return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
  27. }
  28. /**
  29. * @Route("/logout", name="app_logout")
  30. */
  31. public function logout(): Response
  32. {
  33. throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
  34. }
  35. /**
  36. * @Route("/user/change-password", name="change_password")
  37. */
  38. public function changePassword(Request $request, UserPasswordHasherInterface $passwordEncoder)
  39. {
  40. $changePasswordModel = new ChangePassword();
  41. $form = $this->createForm(ChangePasswordType::class, $changePasswordModel);
  42. $form->handleRequest($request);
  43. if ($form->isSubmitted() && $form->isValid()) {
  44. $entityManager = $this->getDoctrine()->getManager();
  45. $user = $entityManager->find(User::class, $this->getUser()->getId());
  46. $user->setPassword(
  47. $passwordEncoder->hashPassword(
  48. $user,
  49. $form->get('newPassword')->getData()
  50. )
  51. );
  52. $entityManager->persist($user);
  53. $entityManager->flush();
  54. return $this->redirect('/?entity=User&action=show&id='. $this->getUser()->getId());
  55. }
  56. return $this->render('reset_password/change-password.html.twig', array(
  57. 'changePasswordForm' => $form->createView(),
  58. ));
  59. }
  60. }