<?php
namespace App\Controller;
use App\Entity\User;
use App\Entity\UserLog;
use LogicException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
/**
* @Route("/login", name="app_login")
* @param AuthenticationUtils $authenticationUtils
* @return Response
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
if ($this->getUser()) {
return $this->redirectToRoute('home');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
/**
* @Route("/logout/devices", name="app_logout_devices")
*/
public function logOutOnAllDevices(): Response
{
if (!$this->getUser()) {
return $this->redirectToRoute('app_logout');
}
$entityManager = $this->getDoctrine()->getManager();
$devices = $this->getUser()->getDevices();
foreach ($devices as $device) {
$entityManager->remove($device);
}
$entityManager->flush();
$this->log($this->getUser(), UserLog::USER_LOGOUT_ALL);
return $this->redirectToRoute('app_logout');
}
/**
* @Route("/logout", name="app_logout")
*/
public function logout()
{
throw new LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
/**
* @param User $user
* @param $event
*/
private function log(User $user, $event){
$userLog = new UserLog();
$userLog->setUser($user);
$userLog->setEventType($event);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($userLog);
$entityManager->flush();
}
}