<?php
namespace App\Controller\Front;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class SecurityController extends AbstractController
{
const SWITCH_USER_PARAMETER = 'user4preview';
const ADMIN_USERNAME = 'admin';
/** @var UserProviderInterface */
protected $userProvider;
/** @var EventDispatcherInterface */
protected $eventDispatcher;
/**
* SecurityController constructor.
*/
public function __construct(UserProviderInterface $userProvider, EventDispatcherInterface $eventDispatcher)
{
$this->userProvider = $userProvider;
$this->eventDispatcher = $eventDispatcher;
}
/**
* @Route("/login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('front/security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
/**
* @Route("/login4preview", name="app_login_4_preview")
*/
public function loginAsAdmin(Request $request): Response
{
$userMail = $this->get('session')->get('admin4preview');
$this->get('session')->remove('admin4preview');
$admin = $this->userProvider->loadUserByUsername(self::ADMIN_USERNAME);
$token = new UsernamePasswordToken($admin, null, 'main', $admin->getRoles());
$this->get('security.token_storage')->setToken($token);
$this->get('session')->set('_security_main', serialize($token));
$event = new InteractiveLoginEvent($request, $token);
$this->eventDispatcher->dispatch($event);
return $this->redirectToRoute('dashboard', [self::SWITCH_USER_PARAMETER => $userMail]);
}
}