<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends Controller
{
/**
* @Route("/", name="index")
*/
public function index(): Response {
return $this->redirectToRoute('security_login');
}
/**
* @Route("/login", name="security_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
$security_context = $this->get('security.authorization_checker');
if($security_context->isGranted('IS_AUTHENTICATED_FULLY')) {
return $this->redirectToRoute('security_dispatch_by_role');
}
return $this->render('Security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
/**
* @Route("/logout", name="security_logout")
*/
public function logout(): void {
throw new Exception("Nobody is supposed reaching this point");
}
/**
* Sends the user to the appropriate backend.
* In other words, it boots the right kernel mode.
*
* @Route("/dispatch", name="security_dispatch_by_role")
*/
public function dispatchByRole(AuthorizationCheckerInterface $auth_checker): RedirectResponse {
// Here, we can't use routes' names because backends routes are generated dynamically
// in the kernel, according to the path the user asked for. So, at this time routes don't exist.
$mappings = [
'ROLE_SUPER_ADMIN' => '/system',
'ROLE_ADMIN' => '/admin',
'ROLE_MANAGER' => '/manager',
'ROLE_AGENT' => '/agent',
'ROLE_CUSTOMER' => '/customer',
];
foreach($mappings as $role => $path) {
if($auth_checker->isGranted($role)) {
return new RedirectResponse($path);
}
}
throw new AccessDeniedHttpException();
}
}