vendor/symfony/security-bundle/DataCollector/SecurityDataCollector.php line 179

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Bundle\SecurityBundle\DataCollector;
  11. use Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener;
  12. use Symfony\Bundle\SecurityBundle\Security\FirewallMap;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpKernel\DataCollector\DataCollector;
  16. use Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface;
  17. use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
  18. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  19. use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
  20. use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
  21. use Symfony\Component\Security\Core\Authorization\TraceableAccessDecisionManager;
  22. use Symfony\Component\Security\Core\Authorization\Voter\TraceableVoter;
  23. use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
  24. use Symfony\Component\Security\Http\Firewall\SwitchUserListener;
  25. use Symfony\Component\Security\Http\FirewallMapInterface;
  26. use Symfony\Component\Security\Http\Logout\LogoutUrlGenerator;
  27. use Symfony\Component\VarDumper\Caster\ClassStub;
  28. use Symfony\Component\VarDumper\Cloner\Data;
  29. /**
  30.  * @author Fabien Potencier <fabien@symfony.com>
  31.  *
  32.  * @final
  33.  */
  34. class SecurityDataCollector extends DataCollector implements LateDataCollectorInterface
  35. {
  36.     private $tokenStorage;
  37.     private $roleHierarchy;
  38.     private $logoutUrlGenerator;
  39.     private $accessDecisionManager;
  40.     private $firewallMap;
  41.     private $firewall;
  42.     private $hasVarDumper;
  43.     private $authenticatorManagerEnabled;
  44.     public function __construct(TokenStorageInterface $tokenStorage nullRoleHierarchyInterface $roleHierarchy nullLogoutUrlGenerator $logoutUrlGenerator nullAccessDecisionManagerInterface $accessDecisionManager nullFirewallMapInterface $firewallMap nullTraceableFirewallListener $firewall nullbool $authenticatorManagerEnabled false)
  45.     {
  46.         $this->tokenStorage $tokenStorage;
  47.         $this->roleHierarchy $roleHierarchy;
  48.         $this->logoutUrlGenerator $logoutUrlGenerator;
  49.         $this->accessDecisionManager $accessDecisionManager;
  50.         $this->firewallMap $firewallMap;
  51.         $this->firewall $firewall;
  52.         $this->hasVarDumper class_exists(ClassStub::class);
  53.         $this->authenticatorManagerEnabled $authenticatorManagerEnabled;
  54.     }
  55.     /**
  56.      * {@inheritdoc}
  57.      */
  58.     public function collect(Request $requestResponse $response\Throwable $exception null)
  59.     {
  60.         if (null === $this->tokenStorage) {
  61.             $this->data = [
  62.                 'enabled' => false,
  63.                 'authenticated' => false,
  64.                 'impersonated' => false,
  65.                 'impersonator_user' => null,
  66.                 'impersonation_exit_path' => null,
  67.                 'token' => null,
  68.                 'token_class' => null,
  69.                 'logout_url' => null,
  70.                 'user' => '',
  71.                 'roles' => [],
  72.                 'inherited_roles' => [],
  73.                 'supports_role_hierarchy' => null !== $this->roleHierarchy,
  74.             ];
  75.         } elseif (null === $token $this->tokenStorage->getToken()) {
  76.             $this->data = [
  77.                 'enabled' => true,
  78.                 'authenticated' => false,
  79.                 'impersonated' => false,
  80.                 'impersonator_user' => null,
  81.                 'impersonation_exit_path' => null,
  82.                 'token' => null,
  83.                 'token_class' => null,
  84.                 'logout_url' => null,
  85.                 'user' => '',
  86.                 'roles' => [],
  87.                 'inherited_roles' => [],
  88.                 'supports_role_hierarchy' => null !== $this->roleHierarchy,
  89.             ];
  90.         } else {
  91.             $inheritedRoles = [];
  92.             $assignedRoles $token->getRoleNames();
  93.             $impersonatorUser null;
  94.             if ($token instanceof SwitchUserToken) {
  95.                 $originalToken $token->getOriginalToken();
  96.                 // @deprecated since 5.3, change to $originalToken->getUserIdentifier() in 6.0
  97.                 $impersonatorUser method_exists($originalToken'getUserIdentifier') ? $originalToken->getUserIdentifier() : $originalToken->getUsername();
  98.             }
  99.             if (null !== $this->roleHierarchy) {
  100.                 foreach ($this->roleHierarchy->getReachableRoleNames($assignedRoles) as $role) {
  101.                     if (!\in_array($role$assignedRolestrue)) {
  102.                         $inheritedRoles[] = $role;
  103.                     }
  104.                 }
  105.             }
  106.             $logoutUrl null;
  107.             try {
  108.                 if (null !== $this->logoutUrlGenerator && !$token instanceof AnonymousToken) {
  109.                     $logoutUrl $this->logoutUrlGenerator->getLogoutPath();
  110.                 }
  111.             } catch (\Exception $e) {
  112.                 // fail silently when the logout URL cannot be generated
  113.             }
  114.             $this->data = [
  115.                 'enabled' => true,
  116.                 'authenticated' => $token->isAuthenticated(),
  117.                 'impersonated' => null !== $impersonatorUser,
  118.                 'impersonator_user' => $impersonatorUser,
  119.                 'impersonation_exit_path' => null,
  120.                 'token' => $token,
  121.                 'token_class' => $this->hasVarDumper ? new ClassStub(\get_class($token)) : \get_class($token),
  122.                 'logout_url' => $logoutUrl,
  123.                 // @deprecated since 5.3, change to $token->getUserIdentifier() in 6.0
  124.                 'user' => method_exists($token'getUserIdentifier') ? $token->getUserIdentifier() : $token->getUsername(),
  125.                 'roles' => $assignedRoles,
  126.                 'inherited_roles' => array_unique($inheritedRoles),
  127.                 'supports_role_hierarchy' => null !== $this->roleHierarchy,
  128.             ];
  129.         }
  130.         // collect voters and access decision manager information
  131.         if ($this->accessDecisionManager instanceof TraceableAccessDecisionManager) {
  132.             $this->data['voter_strategy'] = $this->accessDecisionManager->getStrategy();
  133.             foreach ($this->accessDecisionManager->getVoters() as $voter) {
  134.                 if ($voter instanceof TraceableVoter) {
  135.                     $voter $voter->getDecoratedVoter();
  136.                 }
  137.                 $this->data['voters'][] = $this->hasVarDumper ? new ClassStub(\get_class($voter)) : \get_class($voter);
  138.             }
  139.             // collect voter details
  140.             $decisionLog $this->accessDecisionManager->getDecisionLog();
  141.             foreach ($decisionLog as $key => $log) {
  142.                 $decisionLog[$key]['voter_details'] = [];
  143.                 foreach ($log['voterDetails'] as $voterDetail) {
  144.                     $voterClass \get_class($voterDetail['voter']);
  145.                     $classData $this->hasVarDumper ? new ClassStub($voterClass) : $voterClass;
  146.                     $decisionLog[$key]['voter_details'][] = [
  147.                         'class' => $classData,
  148.                         'attributes' => $voterDetail['attributes'], // Only displayed for unanimous strategy
  149.                         'vote' => $voterDetail['vote'],
  150.                     ];
  151.                 }
  152.                 unset($decisionLog[$key]['voterDetails']);
  153.             }
  154.             $this->data['access_decision_log'] = $decisionLog;
  155.         } else {
  156.             $this->data['access_decision_log'] = [];
  157.             $this->data['voter_strategy'] = 'unknown';
  158.             $this->data['voters'] = [];
  159.         }
  160.         // collect firewall context information
  161.         $this->data['firewall'] = null;
  162.         if ($this->firewallMap instanceof FirewallMap) {
  163.             $firewallConfig $this->firewallMap->getFirewallConfig($request);
  164.             if (null !== $firewallConfig) {
  165.                 $this->data['firewall'] = [
  166.                     'name' => $firewallConfig->getName(),
  167.                     'allows_anonymous' => $firewallConfig->allowsAnonymous(),
  168.                     'request_matcher' => $firewallConfig->getRequestMatcher(),
  169.                     'security_enabled' => $firewallConfig->isSecurityEnabled(),
  170.                     'stateless' => $firewallConfig->isStateless(),
  171.                     'provider' => $firewallConfig->getProvider(),
  172.                     'context' => $firewallConfig->getContext(),
  173.                     'entry_point' => $firewallConfig->getEntryPoint(),
  174.                     'access_denied_handler' => $firewallConfig->getAccessDeniedHandler(),
  175.                     'access_denied_url' => $firewallConfig->getAccessDeniedUrl(),
  176.                     'user_checker' => $firewallConfig->getUserChecker(),
  177.                     'listeners' => $firewallConfig->getListeners(),
  178.                 ];
  179.                 // generate exit impersonation path from current request
  180.                 if ($this->data['impersonated'] && null !== $switchUserConfig $firewallConfig->getSwitchUser()) {
  181.                     $exitPath $request->getRequestUri();
  182.                     $exitPath .= null === $request->getQueryString() ? '?' '&';
  183.                     $exitPath .= sprintf('%s=%s'urlencode($switchUserConfig['parameter']), SwitchUserListener::EXIT_VALUE);
  184.                     $this->data['impersonation_exit_path'] = $exitPath;
  185.                 }
  186.             }
  187.         }
  188.         // collect firewall listeners information
  189.         $this->data['listeners'] = [];
  190.         if ($this->firewall) {
  191.             $this->data['listeners'] = $this->firewall->getWrappedListeners();
  192.         }
  193.         $this->data['authenticator_manager_enabled'] = $this->authenticatorManagerEnabled;
  194.     }
  195.     /**
  196.      * {@inheritdoc}
  197.      */
  198.     public function reset()
  199.     {
  200.         $this->data = [];
  201.     }
  202.     public function lateCollect()
  203.     {
  204.         $this->data $this->cloneVar($this->data);
  205.     }
  206.     /**
  207.      * Checks if security is enabled.
  208.      *
  209.      * @return bool true if security is enabled, false otherwise
  210.      */
  211.     public function isEnabled()
  212.     {
  213.         return $this->data['enabled'];
  214.     }
  215.     /**
  216.      * Gets the user.
  217.      *
  218.      * @return string The user
  219.      */
  220.     public function getUser()
  221.     {
  222.         return $this->data['user'];
  223.     }
  224.     /**
  225.      * Gets the roles of the user.
  226.      *
  227.      * @return array|Data
  228.      */
  229.     public function getRoles()
  230.     {
  231.         return $this->data['roles'];
  232.     }
  233.     /**
  234.      * Gets the inherited roles of the user.
  235.      *
  236.      * @return array|Data
  237.      */
  238.     public function getInheritedRoles()
  239.     {
  240.         return $this->data['inherited_roles'];
  241.     }
  242.     /**
  243.      * Checks if the data contains information about inherited roles. Still the inherited
  244.      * roles can be an empty array.
  245.      *
  246.      * @return bool true if the profile was contains inherited role information
  247.      */
  248.     public function supportsRoleHierarchy()
  249.     {
  250.         return $this->data['supports_role_hierarchy'];
  251.     }
  252.     /**
  253.      * Checks if the user is authenticated or not.
  254.      *
  255.      * @return bool true if the user is authenticated, false otherwise
  256.      */
  257.     public function isAuthenticated()
  258.     {
  259.         return $this->data['authenticated'];
  260.     }
  261.     /**
  262.      * @return bool
  263.      */
  264.     public function isImpersonated()
  265.     {
  266.         return $this->data['impersonated'];
  267.     }
  268.     /**
  269.      * @return string|null
  270.      */
  271.     public function getImpersonatorUser()
  272.     {
  273.         return $this->data['impersonator_user'];
  274.     }
  275.     /**
  276.      * @return string|null
  277.      */
  278.     public function getImpersonationExitPath()
  279.     {
  280.         return $this->data['impersonation_exit_path'];
  281.     }
  282.     /**
  283.      * Get the class name of the security token.
  284.      *
  285.      * @return string|Data|null The token
  286.      */
  287.     public function getTokenClass()
  288.     {
  289.         return $this->data['token_class'];
  290.     }
  291.     /**
  292.      * Get the full security token class as Data object.
  293.      *
  294.      * @return Data|null
  295.      */
  296.     public function getToken()
  297.     {
  298.         return $this->data['token'];
  299.     }
  300.     /**
  301.      * Get the logout URL.
  302.      *
  303.      * @return string|null The logout URL
  304.      */
  305.     public function getLogoutUrl()
  306.     {
  307.         return $this->data['logout_url'];
  308.     }
  309.     /**
  310.      * Returns the FQCN of the security voters enabled in the application.
  311.      *
  312.      * @return string[]|Data
  313.      */
  314.     public function getVoters()
  315.     {
  316.         return $this->data['voters'];
  317.     }
  318.     /**
  319.      * Returns the strategy configured for the security voters.
  320.      *
  321.      * @return string
  322.      */
  323.     public function getVoterStrategy()
  324.     {
  325.         return $this->data['voter_strategy'];
  326.     }
  327.     /**
  328.      * Returns the log of the security decisions made by the access decision manager.
  329.      *
  330.      * @return array|Data
  331.      */
  332.     public function getAccessDecisionLog()
  333.     {
  334.         return $this->data['access_decision_log'];
  335.     }
  336.     /**
  337.      * Returns the configuration of the current firewall context.
  338.      *
  339.      * @return array|Data|null
  340.      */
  341.     public function getFirewall()
  342.     {
  343.         return $this->data['firewall'];
  344.     }
  345.     /**
  346.      * @return array|Data
  347.      */
  348.     public function getListeners()
  349.     {
  350.         return $this->data['listeners'];
  351.     }
  352.     /**
  353.      * {@inheritdoc}
  354.      */
  355.     public function getName()
  356.     {
  357.         return 'security';
  358.     }
  359.     public function isAuthenticatorManagerEnabled(): bool
  360.     {
  361.         return $this->data['authenticator_manager_enabled'];
  362.     }
  363. }