src/Controller/Front/SecurityController.php line 38

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Front;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\Routing\Annotation\Route;
  7. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  8. use Symfony\Component\Security\Core\User\UserProviderInterface;
  9. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  10. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  11. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  12. class SecurityController extends AbstractController
  13. {
  14.     const SWITCH_USER_PARAMETER 'user4preview';
  15.     const ADMIN_USERNAME 'admin';
  16.     /** @var UserProviderInterface */
  17.     protected $userProvider;
  18.     /** @var EventDispatcherInterface */
  19.     protected $eventDispatcher;
  20.     /**
  21.      * SecurityController constructor.
  22.      */
  23.     public function __construct(UserProviderInterface $userProviderEventDispatcherInterface $eventDispatcher)
  24.     {
  25.         $this->userProvider $userProvider;
  26.         $this->eventDispatcher $eventDispatcher;
  27.     }
  28.     /**
  29.      * @Route("/login", name="app_login")
  30.      */
  31.     public function login(AuthenticationUtils $authenticationUtils): Response
  32.     {
  33.         $error $authenticationUtils->getLastAuthenticationError();
  34.         $lastUsername $authenticationUtils->getLastUsername();
  35.         return $this->render('front/security/login.html.twig', ['last_username' => $lastUsername'error' => $error]);
  36.     }
  37.     /**
  38.      * @Route("/login4preview", name="app_login_4_preview")
  39.      */
  40.     public function loginAsAdmin(Request $request): Response
  41.     {
  42.         $userMail $this->get('session')->get('admin4preview');
  43.         $this->get('session')->remove('admin4preview');
  44.         $admin $this->userProvider->loadUserByUsername(self::ADMIN_USERNAME);
  45.         $token = new UsernamePasswordToken($adminnull'main'$admin->getRoles());
  46.         $this->get('security.token_storage')->setToken($token);
  47.         $this->get('session')->set('_security_main'serialize($token));
  48.         $event = new InteractiveLoginEvent($request$token);
  49.         $this->eventDispatcher->dispatch($event);
  50.         return $this->redirectToRoute('dashboard', [self::SWITCH_USER_PARAMETER => $userMail]);
  51.     }
  52. }