src/Controller/SecurityController.php line 18

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  7. use Symfony\Component\Routing\Annotation\Route;
  8. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  9. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  10. class SecurityController extends Controller
  11. {
  12.     /**
  13.      * @Route("/", name="index")
  14.      */
  15.     public function index(): Response {
  16.         return $this->redirectToRoute('security_login');
  17.     }
  18.     /**
  19.      * @Route("/login", name="security_login")
  20.      */
  21.     public function login(AuthenticationUtils $authenticationUtils): Response
  22.     {
  23.         // get the login error if there is one
  24.         $error $authenticationUtils->getLastAuthenticationError();
  25.         // last username entered by the user
  26.         $lastUsername $authenticationUtils->getLastUsername();
  27.         $security_context $this->get('security.authorization_checker');
  28.         if($security_context->isGranted('IS_AUTHENTICATED_FULLY')) {
  29.             return $this->redirectToRoute('security_dispatch_by_role');
  30.         }
  31.         return $this->render('Security/login.html.twig', ['last_username' => $lastUsername'error' => $error]);
  32.     }
  33.     /**
  34.      * @Route("/logout", name="security_logout")
  35.      */
  36.     public function logout(): void {
  37.         throw new Exception("Nobody is supposed reaching this point");
  38.     }
  39.     /**
  40.      * Sends the user to the appropriate backend.
  41.      * In other words, it boots the right kernel mode.
  42.      *
  43.      * @Route("/dispatch", name="security_dispatch_by_role")
  44.      */
  45.     public function dispatchByRole(AuthorizationCheckerInterface $auth_checker): RedirectResponse {
  46.         // Here, we can't use routes' names because backends routes are generated dynamically
  47.         // in the kernel, according to the path the user asked for. So, at this time routes don't exist.
  48.         $mappings = [
  49.             'ROLE_SUPER_ADMIN' => '/system',
  50.             'ROLE_ADMIN' => '/admin',
  51.             'ROLE_MANAGER' => '/manager',
  52.             'ROLE_AGENT' => '/agent',
  53.             'ROLE_CUSTOMER'  => '/customer',
  54.         ];
  55.         foreach($mappings as $role => $path) {
  56.             if($auth_checker->isGranted($role)) {
  57.                 return new RedirectResponse($path);
  58.             }
  59.         }
  60.         throw new AccessDeniedHttpException();
  61.     }
  62. }