Skip to content

[TwigBridge] Create impersonation_exit_path() and *_url() functions #24737

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/Symfony/Bridge/Twig/Extension/SecurityExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,25 @@
use Symfony\Component\Security\Acl\Voter\FieldVote;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
use Symfony\Component\Security\Http\Logout\ImpersonateUrlGenerator;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

/**
* SecurityExtension exposes security context features.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Amrouche Hamza <hamza.simperfit@gmail.com>
*/
class SecurityExtension extends AbstractExtension
{
private $securityChecker;
private $impersonateUrlGenerator;

public function __construct(AuthorizationCheckerInterface $securityChecker = null)
public function __construct(AuthorizationCheckerInterface $securityChecker = null, ImpersonateUrlGenerator $impersonateUrlGenerator)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think PHP strongly discourages non-optional arguments after optional

http://php.net/manual/en/functions.arguments.php

Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.

{
$this->securityChecker = $securityChecker;
$this->impersonateUrlGenerator = $impersonateUrlGenerator;
}

public function isGranted($role, $object = null, $field = null)
Expand All @@ -48,13 +52,25 @@ public function isGranted($role, $object = null, $field = null)
}
}

public function getImpersonateExitPath()
{
return $this->impersonateUrlGenerator->getImpersonateExitPath();
}

public function getImpersonateExitUrl()
{
return $this->impersonateUrlGenerator->getImpersonateExitUrl();
}

/**
* {@inheritdoc}
*/
public function getFunctions()
{
return array(
new TwigFunction('is_granted', array($this, 'isGranted')),
new TwigFunction('impersonation_exit_path', array($this, 'getImpersonateExitPath')),
new TwigFunction('impersonation_exit_url', array($this, 'getImpersonateExitUrl')),
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ public function load(array $configs, ContainerBuilder $container)
$container->removeDefinition('security.access.expression_voter');
}

if (!class_exists('Symfony\Component\HttpFoundation\RequestStack') || !class_exists('Symfony\Component\Routing\Generator\UrlGeneratorInterface')) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why would RequestStack not exist? It's required by dependencies

$container->removeDefinition('security.impersonate_url_generator');
}

// set some global scalars
$container->setParameter('security.access.denied_url', $config['access_denied_url']);
$container->setParameter('security.authentication.manager.erase_credentials', $config['erase_credentials']);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,12 @@
<argument /> <!-- switch_user -->
</service>

<service id="security.impersonate_url_generator" class="Symfony\Component\Security\Http\Logout\ImpersonateUrlGenerator">
<argument type="service" id="request_stack" />
<argument type="service" id="router" />
<argument type="service" id="security.token_storage" on-invalid="null" />
</service>

<service id="security.logout_url_generator" class="Symfony\Component\Security\Http\Logout\LogoutUrlGenerator">
<argument type="service" id="request_stack" on-invalid="null" />
<argument type="service" id="router" on-invalid="null" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<service id="twig.extension.security" class="Symfony\Bridge\Twig\Extension\SecurityExtension">
<tag name="twig.extension" />
<argument type="service" id="security.authorization_checker" on-invalid="ignore" />
<argument type="service" id="security.impersonate_url_generator" on-invalid="ignore" />
</service>
</services>
</container>
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Security\Http\Logout;

use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Http\Firewall\SwitchUserListener;
use Symfony\Component\Security\Http\FirewallMapInterface;
use Symfony\Bundle\SecurityBundle\Security\FirewallMap;

/**
* Provides generator functions for the impersonate url exit.
*
* @author Amrouche Hamza <hamza.simperfit@gmail.com>
*/
class ImpersonateUrlGenerator
{
private $requestStack;
private $router;
private $tokenStorage;
private $firewallMap;

public function __construct(RequestStack $requestStack, UrlGeneratorInterface $router, TokenStorageInterface $tokenStorage = null, FirewallMapInterface $firewallMap)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This class does not work with other implementation than FirewallMap, so you can as well just require it, instead of interface and get rid of an instanceof check. Also not sure why is non-optional argument last.

{
$this->requestStack = $requestStack;
$this->router = $router;
$this->tokenStorage = $tokenStorage;
$this->firewallMap = $firewallMap;
}

public function getImpersonateExitPath(): string
{
return $this->generateImpersonateExitUrl(UrlGeneratorInterface::ABSOLUTE_PATH);
}

public function getImpersonateExitUrl(): string
{
return $this->generateImpersonateExitUrl(UrlGeneratorInterface::ABSOLUTE_URL);
}

private function generateImpersonateExitUrl($referenceType): string
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be more flexible if this was public and twig functions would call this with correct parameters. We then wouldn't need two public methods. Also, missing typehint.

{
$request = $this->requestStack->getCurrentRequest();
$parameters = $request->query;
$exitPath = null;
if ($this->firewallMap instanceof FirewallMap) {
$firewallConfig = $this->firewallMap->getFirewallConfig($request);

// generate exit impersonation path from current request
if ($this->isImpersonatedUser() && null !== $switchUserConfig = $firewallConfig->getSwitchUser()) {
$exitPath = $request->getRequestUri();
$exitPath .= null === $request->getQueryString() ? '?' : '&';
$exitPath .= sprintf('%s=%s', urlencode($switchUserConfig['parameter']), SwitchUserListener::EXIT_VALUE);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

using http_build_query would be better

}
}
if (null === $exitPath) {
throw new \LogicException('Unable to generate the impersonate exit URL without a path.');
}

if ('/' === $exitPath[0]) {
if (!$this->requestStack) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a dead code. RequestStack is required so will never be null

throw new \LogicException('Unable to generate the impersonate exit URL without a RequestStack.');
}

$url = UrlGeneratorInterface::ABSOLUTE_URL === $referenceType ? $request->getUriForPath($exitPath) : $request->getBaseUrl().$exitPath;

if (!empty($parameters)) {
$url .= '?'.http_build_query($parameters);
}
} else {
if (!$this->router) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

another dead path

throw new \LogicException('Unable to generate the impersonate exit URL without a Router.');
}

$url = $this->router->generate($exitPath, array(), $referenceType);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is wrong, first parameter of route path is name of the route, query string is given instead

}

return $url;
}

private function isImpersonatedUser(): bool
{
if (null === $token = $this->tokenStorage->getToken()) {
return false;
}

$assignedRoles = $token->getRoles();

foreach ($assignedRoles as $role) {
if ($role instanceof SwitchUserRole) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than this mechanism to check if user is currently impersonating, shouldn't it be done the way docs recommend? That means checking if user has ROLE_PREVIOUS_ADMIN via AuthorizationChecker.

https://symfony.com/doc/current/security/impersonating_user.html

return true;
}
}
}
}