8000 feature #21935 [FrameworkBundle][Workflow] Add a way to register a gu… · symfony/symfony@d1e591e · GitHub
[go: up one dir, main page]

Skip to content

Commit d1e591e

Browse files
committed
feature #21935 [FrameworkBundle][Workflow] Add a way to register a guard expression in the configuration (lyrixx)
This PR was merged into the 3.3-dev branch. Discussion ---------- [FrameworkBundle][Workflow] Add a way to register a guard expression in the configuration | Q | A | ------------- | --- | Branch? | master | Bug fix? | no | New feature? | yes | BC breaks? | no | Deprecations? | no | Tests pass? | yes | Fixed tickets | - | License | MIT | Doc PR | - --- Many people already asked for this feature so ... here we go 🎉 --- Usage: ```yml transitions: journalist_approval: guard: "is_fully_authenticated() and has_role('ROLE_JOURNALIST') or is_granted('POST_EDIT', subject)" from: wait_for_journalist to: approved_by_journalist publish: guard: "subject.isPublic()" from: approved_by_journalist to: published ``` Commits ------- ab3b12d [FrameworkBundle][Workflow] Add a way to register a guard expression in the configuration
2 parents 6166260 + ab3b12d commit d1e591e

File tree

7 files changed

+251
-1
lines changed

7 files changed

+251
-1
lines changed

src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,11 @@ private function addWorkflowSection(ArrayNodeDefinition $rootNode)
336336
->isRequired()
337337
->cannotBeEmpty()
338338
->end()
339+
->scalarNode('guard')
340+
->cannotBeEmpty()
341+
->info('An expression to block the transition')
342+
->example('is_fully_authenticated() and has_role(\'ROLE_JOURNALIST\') and subject.getTitle() == \'My first article\'')
343+
->end()
339344
->arrayNode('from')
340345
->beforeNormalization()
341346
->ifString()

src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,30 @@ private function registerWorkflowConfiguration(array $workflows, ContainerBuilde
499499
$listener->addArgument(new Reference('logger'));
500500
$container->setDefinition(sprintf('%s.listener.audit_trail', $workflowId), $listener);
501501
}
502+
503+
// Add Guard Listener
504+
$guard = new Definition(Workflow\EventListener\GuardListener::class);
505+
$configuration = array();
506+
foreach ($workflow['transitions'] as $transitionName => $config) {
507+
if (!isset($config['guard'])) {
508+
continue;
509+
}
510+
$eventName = sprintf('workflow.%s.guard.%s', $name, $transitionName);
511+
$guard->addTag('kernel.event_listener', array('event' => $eventName, 'method' => 'onTransition'));
512+
$configuration[$eventName] = $config['guard'];
513+
}
514+
if ($configuration) {
515+
$guard->setArguments(array(
516+
$configuration,
517+
new Reference('workflow.security.expression_language'),
518+
new Reference('security.token_storage'),
519+
new Reference('security.authorization_checker'),
520+
new Reference('security.authentication.trust_resolver'),
521+
new Reference('security.role_hierarchy'),
522+
));
523+
524+
$container->setDefinition(sprintf('%s.listener.guard', $workflowId), $guard);
525+
}
502526
}
503527
}
504528

src/Symfony/Bundle/FrameworkBundle/Resources/config/workflow.xml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,5 +27,7 @@
2727
<argument type="service" id="workflow.registry" />
2828
<tag name="twig.extension" />
2929
</service>
30+
31+
<service id="workflow.security.expression_language" class="Symfony\Component\Workflow\EventListener\ExpressionLanguage" public="false" />
3032
</services>
3133
</container>
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Workflow\EventListener;
13+
14+
use Symfony\Component\Security\Core\Authorization\ExpressionLanguage as BaseExpressionLanguage;
15+
16+
/**
17+
* Adds some function to the default Symfony Security ExpressionLanguage.
18+
*
19+
* @author Fabien Potencier <fabien@symfony.com>
20+
*/
21+
class ExpressionLanguage extends BaseExpressionLanguage
22+
{
23+
protected function registerFunctions()
24+
{
25+
parent::registerFunctions();
26+
27+
$this->register('is_granted', function ($attributes, $object = 'null') {
28+
return sprintf('$auth_checker->isGranted(%s, %s)', $attributes, $object);
29+
}, function (array $variables, $attributes, $object = null) {
30+
return $variables['auth_checker']->isGranted($attributes, $object);
31+
});
32+
}
33+
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Workflow\EventListener;
13+
14+
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
15+
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
16+
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
17+
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
18+
use Symfony\Component\Workflow\Event\GuardEvent;
19+
20+
/**
21+
* @author Grégoire Pineau <lyrixx@lyrixx.info>
22+
*/
23+
class GuardListener
24+
{
25+
private $configuration;
26+
private $expressionLanguage;
27+
private $tokenStorage;
28+
private $authenticationChecker;
29+
private $trustResolver;
30+
private $roleHierarchy;
31+
32+
public function __construct($configuration, ExpressionLanguage $expressionLanguage, TokenStorageInterface $tokenStorage, AuthorizationCheckerInterface $authenticationChecker, AuthenticationTrustResolverInterface $trustResolver, RoleHierarchyInterface $roleHierarchy = null)
33+
{
34+
$this->configuration = $configuration;
35+
$this->expressionLanguage = $expressionLanguage;
36+
$this->tokenStorage = $tokenStorage;
37+
$this->authenticationChecker = $authenticationChecker;
38+
$this->trustResolver = $trustResolver;
39+
$this->roleHierarchy = $roleHierarchy;
40+
}
41+
42+
public function onTransition(GuardEvent $event, $eventName)
43+
{
44+
if (!isset($this->configuration[$eventName])) {
45+
return;
46+
}
47+
48+
if (!$this->expressionLanguage->evaluate($this->configuration[$eventName], $this->getVariables($event))) {
49+
$event->setBlocked(true);
50+
}
51+
}
52+
53+
// code should be sync with Symfony\Component\Security\Core\Authorization\Voter\ExpressionVoter
54+
private function getVariables(GuardEvent $event)
55+
{
56+
$token = $this->tokenStorage->getToken();
57+
58+
if (null !== $this->roleHierarchy) {
59+
$roles = $this->roleHierarchy->getReachableRoles($token->getRoles());
60+
} else {
61+
$roles = $token->getRoles();
62+
}
63+
64+
$variables = array(
65+
'token' => $token,
66+
'user' => $token->getUser(),
67+
'subject' => $event->getSubject(),
68+
'roles' => array_map(function ($role) {
69+
return $role->getRole();
70+
}, $roles),
71+
// needed for the is_granted expression function
72+
'auth_checker' => $this->authenticationChecker,
73+
// needed for the is_* expression function
74+
'trust_resolver' => $this->trustResolver,
75+
);
76+
77+
return $variables;
78+
}
79+
}
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
<?php
2+
3+
namespace Symfony\Component\Workflow\Tests\EventListener;
4+
5+
use PHPUnit\Framework\TestCase;
6+
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
7+
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
8+
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
9+
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
10+
use Symfony\Component\Security\Core\Role\Role;
11+
use Symfony\Component\Workflow\EventListener\ExpressionLanguage;
12+
use Symfony\Component\Workflow\EventListener\GuardListener;
13+
use Symfony\Component\Workflow\Event\GuardEvent;
14+
use Symfony\Component\Workflow\Marking;
15+
use Symfony\Component\Workflow\Transition;
16+
17+
class GuardListenerTest extends TestCase
18+
{
19+
private $tokenStorage;
20+
private $listener;
21+
22+
protected function setUp()
23+
{
24+
$configuration = array(
25+
'event_name_a' => 'true',
26+
'event_name_b' => 'false',
27+
);
28+
29+
$expressionLanguage = new ExpressionLanguage();
30+
$this->tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock();
31+
$authenticationChecker = $this->getMockBuilder(AuthorizationCheckerInterface::class)->getMock();
32+
$trustResolver = $this->getMockBuilder(AuthenticationTrustResolverInterface::class)->getMock();
33+
34+
$this->listener = new GuardListener($configuration, $expressionLanguage, $this->tokenStorage, $authenticationChecker, $trustResolver);
35+
}
36+
37+
protected function tearDown()
38+
{
39+
$this->listener = null;
40+
}
41+
42+
public function testWithNotSupportedEvent()
43+
{
44+
$event = $this->createEvent();
45+
$this->configureTokenStorage(false);
46+
47+
$this->listener->onTransition($event, 'not supported');
48+
49+
$this->assertFalse($event->isBlocked());
50+
}
51+
52+
public function testWithSupportedEventAndReject()
53+
{
54+
$event = $this->createEvent();
55+
$this->configureTokenStorage(true);
56+
57+
$this->listener->onTransition($event, 'event_name_a');
58+
59+
$this->assertFalse($event->isBlocked());
60+
}
61+
62+
public function testWithSupportedEventAndAccept()
63+
{
64+
$event = $this->createEvent();
65+
$this->configureTokenStorage(true);
66+
67+
$this->listener->onTransition($event, 'event_name_b');
68+
69+
$this->assertTrue($event->isBlocked());
70+
}
71+
72+
private function createEvent()
73+
{
74+
$subject = new \stdClass();
75+
$subject->marking = new Marking();
76+
$transition = new Transition('name', 'from', 'to');
77+
78+
return new GuardEvent($subject, $subject->marking, $transition);
79+
}
80+
81+
private function configureTokenStorage($hasUser)
82+
{
83+
if (!$hasUser) {
84+
$this->tokenStorage
85+
->expects($this->never())
86+
->method('getToken')
87+
;
88+
89+
return;
90+
}
91+
92+
$token = $this->getMockBuilder(TokenInterface::class)->getMock();
93+
$token
94+
->expects($this->once())
95+
->method('getRoles')
96+
->willReturn(array(new Role('ROLE_ADMIN')))
97+
;
98+
99+
$this->tokenStorage
100+
->expects($this->once())
101+
->method('getToken')
102+
->willReturn($token)
103+
;
104+
}
105+
}

src/Symfony/Component/Workflow/composer.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,9 @@
2525
},
2626
"require-dev": {
2727
"psr/log": "~1.0",
28-
"symfony/event-dispatcher": "~2.1|~3.0"
28+
"symfony/event-dispatcher": "~2.1|~3.0",
29+
"symfony/expression-language": "~2.8|~3.0",
30+
"symfony/security-core": "~2.8|~3.0"
2931
},
3032
"autoload": {
3133
"psr-4": { "Symfony\\Component\\Workflow\\": "" }

0 commit comments

Comments
 (0)
0