src/Controller/SecurityController.php line 91

Open in your IDE?
  1. <?php
  2. /**
  3.  * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
  4.  *
  5.  * Copyright (C) 2019 - 2020 Jan Böhmer (https://github.com/jbtronics)
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU Affero General Public License as published
  9.  * by the Free Software Foundation, either version 3 of the License, or
  10.  * (at your option) any later version.
  11.  *
  12.  * This program is distributed in the hope that it will be useful,
  13.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15.  * GNU Affero General Public License for more details.
  16.  *
  17.  * You should have received a copy of the GNU Affero General Public License
  18.  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
  19.  */
  20. declare(strict_types=1);
  21. /**
  22.  * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
  23.  *
  24.  * Copyright (C) 2019 Jan Böhmer (https://github.com/jbtronics)
  25.  *
  26.  * This program is free software; you can redistribute it and/or
  27.  * modify it under the terms of the GNU General Public License
  28.  * as published by the Free Software Foundation; either version 2
  29.  * of the License, or (at your option) any later version.
  30.  *
  31.  * This program is distributed in the hope that it will be useful,
  32.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  33.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  34.  * GNU General Public License for more details.
  35.  *
  36.  * You should have received a copy of the GNU General Public License
  37.  * along with this program; if not, write to the Free Software
  38.  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
  39.  */
  40. namespace App\Controller;
  41. use App\Entity\UserSystem\User;
  42. use App\Events\SecurityEvent;
  43. use App\Events\SecurityEvents;
  44. use App\Services\PasswordResetManager;
  45. use Doctrine\ORM\EntityManagerInterface;
  46. use Gregwar\CaptchaBundle\Type\CaptchaType;
  47. use RuntimeException;
  48. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  49. use Symfony\Component\EventDispatcher\EventDispatcher;
  50. use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  51. use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
  52. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  53. use Symfony\Component\Form\Extension\Core\Type\TextType;
  54. use Symfony\Component\HttpFoundation\Request;
  55. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  56. use Symfony\Component\Routing\Annotation\Route;
  57. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  58. use Symfony\Component\Validator\Constraints\Length;
  59. use Symfony\Component\Validator\Constraints\NotBlank;
  60. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  61. use Symfony\Contracts\Translation\TranslatorInterface;
  62. class SecurityController extends AbstractController
  63. {
  64.     protected $translator;
  65.     protected $allow_email_pw_reset;
  66.     public function __construct(TranslatorInterface $translatorbool $allow_email_pw_reset)
  67.     {
  68.         $this->translator $translator;
  69.         $this->allow_email_pw_reset $allow_email_pw_reset;
  70.     }
  71.     /**
  72.      * @Route("/login", name="login", methods={"GET", "POST"})
  73.      */
  74.     public function login(AuthenticationUtils $authenticationUtils): \Symfony\Component\HttpFoundation\Response
  75.     {
  76.         // get the login error if there is one
  77.         $error $authenticationUtils->getLastAuthenticationError();
  78.         // last username entered by the user
  79.         $lastUsername $authenticationUtils->getLastUsername();
  80.         return $this->render('security/login.html.twig', [
  81.             'last_username' => $lastUsername,
  82.             'error' => $error,
  83.         ]);
  84.     }
  85.     /**
  86.      * @Route("/pw_reset/request", name="pw_reset_request")
  87.      *
  88.      * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
  89.      */
  90.     public function requestPwReset(PasswordResetManager $passwordResetRequest $request)
  91.     {
  92.         if (!$this->allow_email_pw_reset) {
  93.             throw new AccessDeniedHttpException('The password reset via email is disabled!');
  94.         }
  95.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  96.             throw new AccessDeniedHttpException('You are already logged in, so you can not reset your password!');
  97.         }
  98.         $builder $this->createFormBuilder();
  99.         $builder->add('user'TextType::class, [
  100.             'label' => $this->translator->trans('pw_reset.user_or_email'),
  101.             'constraints' => [new NotBlank()],
  102.         ]);
  103.         $builder->add('captcha'CaptchaType::class, [
  104.             'width' => 200,
  105.             'height' => 50,
  106.             'length' => 6,
  107.         ]);
  108.         $builder->add('submit'SubmitType::class, [
  109.             'label' => 'pw_reset.submit',
  110.         ]);
  111.         $form $builder->getForm();
  112.         $form->handleRequest($request);
  113.         if ($form->isSubmitted() && $form->isValid()) {
  114.             $passwordReset->request($form->getData()['user']);
  115.             $this->addFlash('success''pw_reset.request.success');
  116.             return $this->redirectToRoute('login');
  117.         }
  118.         return $this->render('security/pw_reset_request.html.twig', [
  119.             'form' => $form->createView(),
  120.         ]);
  121.     }
  122.     /**
  123.      * @Route("/pw_reset/new_pw/{user}/{token}", name="pw_reset_new_pw")
  124.      *
  125.      * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
  126.      */
  127.     public function pwResetNewPw(PasswordResetManager $passwordResetRequest $requestEntityManagerInterface $emEventDispatcherInterface $eventDispatcher, ?string $user null, ?string $token null)
  128.     {
  129.         if (!$this->allow_email_pw_reset) {
  130.             throw new AccessDeniedHttpException('The password reset via email is disabled!');
  131.         }
  132.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  133.             throw new AccessDeniedHttpException('You are already logged in, so you can not reset your password!');
  134.         }
  135.         $data = [
  136.             'username' => $user,
  137.             'token' => $token,
  138.         ];
  139.         $builder $this->createFormBuilder($data);
  140.         $builder->add('username'TextType::class, [
  141.             'label' => $this->translator->trans('pw_reset.username'),
  142.         ]);
  143.         $builder->add('token'TextType::class, [
  144.             'label' => $this->translator->trans('pw_reset.token'),
  145.         ]);
  146.         $builder->add('new_password'RepeatedType::class, [
  147.             'type' => PasswordType::class,
  148.             'first_options' => [
  149.                 'label' => 'user.settings.pw_new.label',
  150.             ],
  151.             'second_options' => [
  152.                 'label' => 'user.settings.pw_confirm.label',
  153.             ],
  154.             'invalid_message' => 'password_must_match',
  155.             'constraints' => [new Length([
  156.                 'min' => 6,
  157.                 'max' => 128,
  158.             ])],
  159.         ]);
  160.         $builder->add('submit'SubmitType::class, [
  161.             'label' => 'pw_reset.submit',
  162.         ]);
  163.         $form $builder->getForm();
  164.         $form->handleRequest($request);
  165.         if ($form->isSubmitted() && $form->isValid()) {
  166.             $data $form->getData();
  167.             //Try to set the new password
  168.             $success $passwordReset->setNewPassword($data['username'], $data['token'], $data['new_password']);
  169.             if (!$success) {
  170.                 $this->addFlash('error''pw_reset.new_pw.error');
  171.             } else {
  172.                 $this->addFlash('success''pw_reset.new_pw.success');
  173.                 $repo $em->getRepository(User::class);
  174.                 $u $repo->findOneBy(['name' => $data['username']]);
  175.                 $event = new SecurityEvent($u);
  176.                 /** @var EventDispatcher $eventDispatcher */
  177.                 $eventDispatcher->dispatch($eventSecurityEvents::PASSWORD_RESET);
  178.                 return $this->redirectToRoute('login');
  179.             }
  180.         }
  181.         return $this->render('security/pw_reset_new_pw.html.twig', [
  182.             'form' => $form->createView(),
  183.         ]);
  184.     }
  185.     /**
  186.      * @Route("/logout", name="logout")
  187.      */
  188.     public function logout(): void
  189.     {
  190.         throw new RuntimeException('Will be intercepted before getting here');
  191.     }
  192. }