src/Controller/SecurityController.php line 21

  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\RegistrationFormType;
  5. use App\Security\LoginFormAuthenticator;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Exception;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\HttpFoundation\RedirectResponse;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  15. use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
  16. class SecurityController extends AbstractController
  17. {
  18.     public function login(AuthenticationUtils $authenticationUtils): Response
  19.     {
  20.         // if ($this->getUser()) {
  21.         //     return $this->redirectToRoute('target_path');
  22.         // }
  23.         // get the login error if there is one
  24.         $error $authenticationUtils->getLastAuthenticationError();
  25.         // last username entered by the user
  26.         $lastUsername $authenticationUtils->getLastUsername();
  27.         return $this->render('security/login.html.twig', ['last_username' => $lastUsername'error' => $error]);
  28.     }
  29.     public function logout(): void
  30.     {
  31.         throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
  32.     }
  33.     public function register(Request $requestUserPasswordHasherInterface $userPasswordHasherUserAuthenticatorInterface $userAuthenticatorLoginFormAuthenticator $authenticatorEntityManagerInterface $entityManager): Response
  34.     {
  35.         $user = new User();
  36.         $form $this->createForm(RegistrationFormType::class, $user);
  37.         $form->handleRequest($request);
  38.         if ($form->isSubmitted() && $form->isValid()) {
  39.             // encode the plain password
  40.             $user->setPassword(
  41.                 $userPasswordHasher->hashPassword(
  42.                     $user,
  43.                     $form->get('password')->getData()
  44.                 )
  45.             );
  46.             $entityManager->persist($user);
  47.             $entityManager->flush();
  48.             // do anything else you need here, like send an email
  49.             return $userAuthenticator->authenticateUser(
  50.                 $user,
  51.                 $authenticator,
  52.                 $request
  53.             );
  54.         }
  55.         return $this->render('registration/register.html.twig', [
  56.             'registrationForm' => $form->createView(),
  57.         ]);
  58.     }
  59. }