src/Controller/SecurityController.php line 24

  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\Routing\Annotation\Route;
  8. use Symfony\Component\Security\Http\Attribute\CurrentUser;
  9. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  10. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  11. #[Route('/admin')]
  12. final class SecurityController extends AbstractController
  13. {
  14.     use TargetPathTrait;
  15.     /*
  16.      * The $user argument type (?User) must be nullable because the login page
  17.      * must be accessible to anonymous visitors too.
  18.      */
  19.     #[Route('/login'name'security_login')]
  20.     public function login(
  21.         #[CurrentUser] ?User $user,
  22.         Request $request,
  23.         AuthenticationUtils $helper,
  24.     ): Response {
  25.         // if user is already logged in, don't display the login page again
  26.         if ($user) {
  27.             return $this->redirectToRoute('admin');
  28.         }
  29.         $this->saveTargetPath($request->getSession(), 'main'$this->generateUrl('admin'));
  30.         return $this->render('security/login.html.twig', [
  31.             // last username entered by the user (if any)
  32.             'last_username' => $helper->getLastUsername(),
  33.             // last authentication error (if any)
  34.             'error' => $helper->getLastAuthenticationError(),
  35.         ]);
  36.     }
  37.     /**
  38.      * This is the route the user can use to logout.
  39.      *
  40.      * But, this will never be executed. Symfony will intercept this first
  41.      * and handle the logout automatically. See logout in config/packages/security.yaml
  42.      */
  43.     #[Route('/logout'name'security_logout')]
  44.     public function logout(): void
  45.     {
  46.         throw new \Exception('This should never be reached!');
  47.     }
  48. }