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
12namespace Symfony\Component\Security\Core\Authorization;
13
14use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
15use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
16use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
17
18/**
19 * AuthorizationChecker is the main authorization point of the Security component.
20 *
21 * It gives access to the token representing the current user authentication.
22 *
23 * @author Fabien Potencier <fabien@symfony.com>
24 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
25 */
26class AuthorizationChecker implements AuthorizationCheckerInterface
27{
28    private $tokenStorage;
29    private $accessDecisionManager;
30    private $authenticationManager;
31    private $alwaysAuthenticate;
32
33    /**
34     * Constructor.
35     *
36     * @param TokenStorageInterface          $tokenStorage
37     * @param AuthenticationManagerInterface $authenticationManager An AuthenticationManager instance
38     * @param AccessDecisionManagerInterface $accessDecisionManager An AccessDecisionManager instance
39     * @param bool                           $alwaysAuthenticate
40     */
41    public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager, AccessDecisionManagerInterface $accessDecisionManager, $alwaysAuthenticate = false)
42    {
43        $this->tokenStorage = $tokenStorage;
44        $this->authenticationManager = $authenticationManager;
45        $this->accessDecisionManager = $accessDecisionManager;
46        $this->alwaysAuthenticate = $alwaysAuthenticate;
47    }
48
49    /**
50     * {@inheritdoc}
51     *
52     * @throws AuthenticationCredentialsNotFoundException when the token storage has no authentication token.
53     */
54    final public function isGranted($attributes, $object = null)
55    {
56        if (null === ($token = $this->tokenStorage->getToken())) {
57            throw new AuthenticationCredentialsNotFoundException('The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.');
58        }
59
60        if ($this->alwaysAuthenticate || !$token->isAuthenticated()) {
61            $this->tokenStorage->setToken($token = $this->authenticationManager->authenticate($token));
62        }
63
64        if (!is_array($attributes)) {
65            $attributes = array($attributes);
66        }
67
68        return $this->accessDecisionManager->decide($token, $attributes, $object);
69    }
70}
71