src/Controller/SecurityController.php line 111

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Event\AppEvents;
  4. use App\Event\UserResetPasswordEvent;
  5. use App\Model\Form\ChangePasswordForm;
  6. use App\Model\Form\ResetPasswordForm;
  7. use App\Repository\UserRepository;
  8. use DateTime;
  9. use App\Entity\User;
  10. use App\ValueObject\SearchCriteria\UserSearchCriteria;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. use Ecommerce121\UtilBundle\Controller\ControllerBase;
  13. use Ecommerce121\UtilBundle\Controller\ControllerUtil;
  14. use Exception;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Session\Session;
  19. use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface;
  20. use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
  21. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  22. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  23. /**
  24.  * Class with version related actions.
  25.  */
  26. class SecurityController extends ControllerBase
  27. {
  28.     /**
  29.      * @var AuthenticationUtils
  30.      */
  31.     private $authenticationUtils;
  32.     /**
  33.      * @var PasswordHasherFactoryInterface
  34.      */
  35.     private $encoderFactory;
  36.     private EntityManagerInterface $entityManager;
  37.     private UserRepository $userRepository;
  38.     /**
  39.      * Constructor.
  40.      *
  41.      * @param ControllerUtil          $controllerUtil
  42.      * @param AuthenticationUtils     $authenticationUtils
  43.      * @param PasswordHasherFactoryInterface $encoderFactory
  44.      */
  45.     public function __construct(
  46.         ControllerUtil $controllerUtil,
  47.         AuthenticationUtils $authenticationUtils,
  48.         PasswordHasherFactoryInterface $encoderFactory,
  49.         EntityManagerInterface $entityManager,
  50.         UserRepository $userRepository
  51.     ) {
  52.         parent::__construct($controllerUtil);
  53.         $this->authenticationUtils $authenticationUtils;
  54.         $this->encoderFactory $encoderFactory;
  55.         $this->entityManager $entityManager;
  56.         $this->userRepository $userRepository;
  57.     }
  58.     /**
  59.      * @Route("/login", name="app_login")
  60.      * @Template("Security/login.html.twig")
  61.      */
  62.     public function loginAction()
  63.     {
  64.         if ($this->getUser() instanceof User) {
  65.             $dashboardPath $this->generateUrl('app_home');
  66.             return $this->redirect($dashboardPath);
  67.         }
  68.         return [
  69.             // last username entered by the user (if any)
  70.             'last_username' => $this->authenticationUtils->getLastUsername(),
  71.             // last authentication error (if any)
  72.             'error' => $this->authenticationUtils->getLastAuthenticationError(),
  73.         ];
  74.     }
  75.     /**
  76.      * @Route("/loginCheck", name="app_login_check")
  77.      *
  78.      * @throws \Exception
  79.      */
  80.     public function loginCheckAction()
  81.     {
  82.         throw new \RuntimeException('This should never be reached!');
  83.     }
  84.     /**
  85.      * @Route("/logout", name="app_logout")
  86.      *
  87.      * @throws \Exception
  88.      */
  89.     public function logoutAction()
  90.     {
  91.         throw new \RuntimeException('This should never be reached!');
  92.     }
  93.     /**
  94.      * @Route("/resetPassword", name="app_reset_password")
  95.      * @Template("Security/resetPassword.html.twig")
  96.      *
  97.      * @param Request $request
  98.      *
  99.      * @return array
  100.      */
  101.     public function resetPasswordAction(Request $request)
  102.     {
  103.         $form $this->createForm(ResetPasswordForm::class);
  104.         $form->handleRequest($request);
  105.         if ($form->isSubmitted() && $form->isValid()) {
  106.             $email $form->get('email')->getData();
  107.             /** @var User $user */
  108.             $user $this->getEntityManager()->getRepository(User::class)->findOneBy(['email' => $email]);
  109.             if ($user instanceof User) {
  110.                 $user->setForgetPasswordValidUntil(new DateTime('+7 days'));
  111.                 $user->setForgetPasswordCode(uniqid());
  112.                 $this->getEntityManager()->persist($user);
  113.                 $this->getEntityManager()->flush();
  114.                 $this->dispatchEvent(AppEvents::USER_RESET_PASSWORD, new UserResetPasswordEvent($user));
  115.             }
  116.         }
  117.         return [
  118.             'form' => $form->createView(),
  119.             'formIsValid' => $form->isSubmitted() && $form->isValid(),
  120.         ];
  121.     }
  122.     /** use common method */
  123.     /**
  124.      * @Route("/changePassword/{code}", name="app_change_password")
  125.      * @Template("Security/changePassword.html.twig")
  126.      */
  127.     public function changePasswordAction($codeRequest $request)
  128.     {
  129.         return $this->handlePasswordChange($code$request'resetPassword');
  130.     }
  131.     /**
  132.      * @Route("/update-password/{code}", name="app_update_user_password")
  133.      * @Template("Security/changePassword.html.twig")
  134.      */
  135.     public function updateUserPassword($codeRequest $request)
  136.     {
  137.         return $this->handlePasswordChange($code$request'updatePassword');
  138.     }
  139.     private function handlePasswordChange($codeRequest $requeststring $passwordAction) {
  140.         $this->forward404Unless($code);
  141.         /** @var User $user */
  142.         $user $this->userRepository->findOneBy(['forgetPasswordCode' => $code]);
  143.         $oldPassword $user->getPassword();
  144.         $homeUrl $this->generateUrl('app_home');
  145.         $updatePassUrl $this->generateUrl('app_update_user_password', ['code' => $code]);
  146.         if (!$user instanceof User) {
  147.             /** @var Session $session */
  148.             $session $request->getSession();
  149.             $session->getFlashBag()->add(
  150.                 'message_password',
  151.                 'You code have been already used or have expired.'
  152.             );
  153.             return $this->redirect($homeUrl);
  154.         }
  155.         $form $this->createForm(ChangePasswordForm::class);
  156.         $form->handleRequest($request);
  157.         if ($form->isSubmitted() && $form->isValid()) {
  158.             $encoder $this->encoderFactory->getPasswordHasher(User::class);
  159.             $encodedPassword $encoder->hash($form['newPassword']->getData(), $user->getSalt());
  160.             $user->changePassword($encodedPassword);
  161.             $user->setForgetPasswordCode(null);
  162.             $user->setForgetPasswordValidUntil(null);
  163.             $user->setPasswordValidUntil(new \DateTime('+90 days'));
  164.             $session $request->getSession();
  165.             $newPassword $form['newPassword']->getData();
  166.             $sameAsOldPassword $encoder->verify($oldPassword$newPassword);
  167.             if ($sameAsOldPassword) {
  168.                 $session->getFlashBag()->add('message_password''Please use different password. Old password and new password are same.');
  169.                 return $this->redirect($updatePassUrl);
  170.             }
  171.             $this->entityManager->persist($user);
  172.             $this->entityManager->flush();
  173.             $session $request->getSession();
  174.             $session->getFlashBag()->add('message_password''Your password has been updated.');
  175.             return $this->redirect($homeUrl);
  176.         }
  177.         return [
  178.             'form' => $form->createView(),
  179.             'code' => $code,
  180.             'user' => $user,
  181.             'updatePassword' => ($passwordAction === 'updatePassword')
  182.         ];
  183.     }
  184. }