1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace League\Tactician\Bundle\Middleware; |
4
|
|
|
|
5
|
|
|
use League\Tactician\Exception\InvalidMiddlewareException; |
6
|
|
|
use League\Tactician\Middleware; |
7
|
|
|
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; |
8
|
|
|
use Symfony\Component\Security\Core\Exception\AccessDeniedException; |
9
|
|
|
|
10
|
|
|
|
11
|
|
|
class SecurityMiddleware implements Middleware |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* Access denied behavior to drop the command if not allowed. |
15
|
|
|
*/ |
16
|
|
|
const DROP_COMMAND = 1; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Access denied behavior to throw an AccessDenied exception if not allowed. |
20
|
|
|
* Default behavior. |
21
|
|
|
*/ |
22
|
|
|
const THROW_ACCESS_DENIED_EXCEPTION = 2; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var int |
26
|
|
|
*/ |
27
|
|
|
private $accessDeniedBehavior; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var AuthorizationCheckerInterface |
31
|
|
|
*/ |
32
|
|
|
private $authorizationChecker; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param AuthorizationCheckerInterface $authorizationChecker |
36
|
|
|
*/ |
37
|
12 |
|
public function __construct(AuthorizationCheckerInterface $authorizationChecker, $accessDeniedBehavior = self::THROW_ACCESS_DENIED_EXCEPTION) { |
38
|
12 |
|
$this->authorizationChecker = $authorizationChecker; |
39
|
12 |
|
$this->accessDeniedBehavior = $accessDeniedBehavior; |
40
|
|
|
|
41
|
12 |
|
if ($this->accessDeniedBehavior !== static::DROP_COMMAND && $this->accessDeniedBehavior !== static::THROW_ACCESS_DENIED_EXCEPTION) { |
42
|
3 |
|
throw new InvalidMiddlewareException( |
43
|
3 |
|
sprintf('The security middleware requires a valid accessDeniedBehavior, \'%s\' is not valid.', $this->accessDeniedBehavior) |
44
|
3 |
|
); |
45
|
|
|
} |
46
|
9 |
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param object $command |
50
|
|
|
* @param callable $next |
51
|
|
|
* @return mixed |
52
|
|
|
*/ |
53
|
9 |
|
public function execute($command, callable $next) |
54
|
|
|
{ |
55
|
9 |
|
if ($this->authorizationChecker->isGranted('handle', $command)) { |
56
|
3 |
|
return $next($command); |
57
|
6 |
|
} elseif ($this->accessDeniedBehavior === static::THROW_ACCESS_DENIED_EXCEPTION) { |
58
|
3 |
|
throw new AccessDeniedException( |
59
|
3 |
|
sprintf('The current user is not allowed to handle command of type \'%s\'', get_class($command)) |
60
|
3 |
|
); |
61
|
|
|
} |
62
|
3 |
|
} |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
|