src/Controller/SecurityController.php line 37

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace App\Controller;
  11. use App\Entity\User;
  12. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\Security\Http\Attribute\CurrentUser;
  17. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  18. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  19. /**
  20. * Controller used to manage the application security.
  21. * See https://symfony.com/doc/current/security/form_login_setup.html.
  22. *
  23. */
  24. class SecurityController extends AbstractController
  25. {
  26. use TargetPathTrait;
  27. /*
  28. * The $user argument type (?User) must be nullable because the login page
  29. * must be accessible to anonymous visitors too.
  30. */
  31. #[Route('/login', name: 'security_login')]
  32. public function login(#[CurrentUser] ?User $user, Request $request, AuthenticationUtils $helper,): Response {
  33. // if user is already logged in, don't display the login page again
  34. if ($user) {
  35. return $this->redirectToRoute('app_dashboard');
  36. }
  37. // this statement solves an edge-case: if you change the locale in the login
  38. // page, after a successful login you are redirected to a page in the previous
  39. // locale. This code regenerates the referrer URL whenever the login page is
  40. // browsed, to ensure that its locale is always the current one.
  41. $this->saveTargetPath($request->getSession(), 'main', $this->generateUrl('app_dashboard'));
  42. return $this->render('security/login.html.twig', [
  43. // last username entered by the user (if any)
  44. 'last_username' => $helper->getLastUsername(),
  45. // last authentication error (if any)
  46. 'error' => $helper->getLastAuthenticationError(),
  47. ]);
  48. }
  49. /**
  50. * This is the route the user can use to logout.
  51. *
  52. * But, this will never be executed. Symfony will intercept this first
  53. * and handle the logout automatically. See logout in config/packages/security.yaml
  54. */
  55. #[Route('/logout', name: 'security_logout')]
  56. public function logout(): void
  57. {
  58. throw new \Exception('This should never be reached!');
  59. }
  60. }