File: /var/www/dvpis2025/dvpis.kaunokolegija.lt/src/Controller/SecurityController.php
<?php
namespace App\Controller;
use App\Entity\Lecturer;
use App\Repository\LecturerRepository;
use App\Service\DbDataFilter;
use Doctrine\ORM\EntityManagerInterface;
use LogicException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
public function __construct(
private readonly TokenStorageInterface $tokenStorage,
private readonly DbDataFilter $dbDataFilter,
) {
}
#[Route(path: '/login', name: 'app_login')]
public function login(AuthenticationUtils $authenticationUtils): Response
{
if ($this->getUser() instanceof UserInterface) {
return $this->redirectToRoute('homepage');
}
// 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(path: '/logout', name: 'app_logout')]
public function logout(): void
{
throw new LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
#[Route(path: '/toggle', name: 'app_toggle')]
public function changeRole(TokenStorageInterface $tokenStorage, RequestStack $requestStack, Security $security): Response
{
$token = $tokenStorage->getToken();
if (!$token) {
throw $this->createAccessDeniedException('No authenticated user found.');
}
$user = $token->getUser();
if (!is_object($user)) {
throw $this->createAccessDeniedException('Invalid user.');
}
$request = $requestStack->getCurrentRequest();
if (!$request) {
throw new \RuntimeException('No current request found.');
}
$newRoles = $security->isGranted('ROLE_LECTURER') ? $user->getRoles() : ['ROLE_LECTURER'];
// Create a new token with the updated roles
$newToken = new UsernamePasswordToken($user, 'main', $newRoles);
$tokenStorage->setToken($newToken);
// Save the token in the session
$session = $request->getSession();
$session->set('_security_main', serialize($newToken));
$session->save();
return $this->redirectToRoute('homepage');
}
}