diff --git a/src/Symfony/Bundle/DoctrineMongoDBBundle/Security/DocumentUserProvider.php b/src/Symfony/Bundle/DoctrineMongoDBBundle/Security/DocumentUserProvider.php index 583933d466887..651c21c5546f5 100644 --- a/src/Symfony/Bundle/DoctrineMongoDBBundle/Security/DocumentUserProvider.php +++ b/src/Symfony/Bundle/DoctrineMongoDBBundle/Security/DocumentUserProvider.php @@ -11,9 +11,9 @@ namespace Symfony\Bundle\DoctrineMongoDBBundle\Security; -use Symfony\Component\Security\Core\User\AccountInterface; +use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\UserProviderInterface; -use Symfony\Component\Security\Core\Exception\UnsupportedAccountException; +use Symfony\Component\Security\Core\Exception\UnsupportedUserException; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; class DocumentUserProvider implements UserProviderInterface @@ -59,13 +59,13 @@ public function loadUserByUsername($username) /** * {@inheritDoc} */ - public function loadUserByAccount(AccountInterface $account) + public function loadUser(UserInterface $user) { - if (!$account instanceof $this->class) { - throw new UnsupportedAccountException(sprintf('Instances of "%s" are not supported.', get_class($account))); + if (!$user instanceof $this->class) { + throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user))); } - return $this->loadUserByUsername($account->getUsername()); + return $this->loadUserByUsername($user->getUsername()); } /** diff --git a/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php b/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php index 7da23c76c7fce..609f8db31a712 100644 --- a/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php +++ b/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php @@ -23,7 +23,7 @@ */ class SecurityDataCollector extends DataCollector { - protected $context; + private $context; public function __construct(SecurityContextInterface $context = null) { @@ -53,7 +53,7 @@ public function collect(Request $request, Response $response, \Exception $except $this->data = array( 'enabled' => true, 'authenticated' => $token->isAuthenticated(), - 'user' => (string) $token, + 'user' => $token->getUsername(), 'roles' => array_map(function ($role){ return $role->getRole();}, $token->getRoles()), ); } diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Configuration.php index c101e8319ba9e..c9e554164f9d4 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Configuration.php @@ -58,7 +58,7 @@ public function getMainConfigTree(array $factories) return $tb->buildTree(); } - protected function addAclSection($rootNode) + private function addAclSection($rootNode) { $rootNode ->arrayNode('acl') @@ -68,7 +68,7 @@ protected function addAclSection($rootNode) ; } - protected function addRoleHierarchySection($rootNode) + private function addRoleHierarchySection($rootNode) { $rootNode ->fixXmlConfig('role', 'role_hierarchy') @@ -87,7 +87,7 @@ protected function addRoleHierarchySection($rootNode) ; } - protected function addAccessControlSection($rootNode) + private function addAccessControlSection($rootNode) { $rootNode ->fixXmlConfig('rule', 'access_control') @@ -122,7 +122,7 @@ protected function addAccessControlSection($rootNode) ; } - protected function addFirewallsSection($rootNode, array $factories) + private function addFirewallsSection($rootNode, array $factories) { $firewallNodeBuilder = $rootNode @@ -186,7 +186,7 @@ protected function addFirewallsSection($rootNode, array $factories) } } - protected function addProvidersSection($rootNode) + private function addProvidersSection($rootNode) { $rootNode ->fixXmlConfig('provider') @@ -225,7 +225,7 @@ protected function addProvidersSection($rootNode) ; } - protected function addEncodersSection($rootNode) + private function addEncodersSection($rootNode) { $rootNode ->fixXmlConfig('encoder') diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php index 372f80ea0b782..05996c6cdbc9b 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php @@ -34,11 +34,11 @@ */ class SecurityExtension extends Extension { - protected $requestMatchers = array(); - protected $contextListeners = array(); - protected $listenerPositions = array('pre_auth', 'form', 'http', 'remember_me'); - protected $configuration; - protected $factories; + private $requestMatchers = array(); + private $contextListeners = array(); + private $listenerPositions = array('pre_auth', 'form', 'http', 'remember_me'); + private $configuration; + private $factories; public function __construct() { @@ -107,7 +107,7 @@ public function load(array $configs, ContainerBuilder $container) )); } - protected function aclLoad($config, ContainerBuilder $container) + private function aclLoad($config, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(array(__DIR__.'/../Resources/config', __DIR__.'/Resources/config'))); $loader->load('security_acl.xml'); @@ -128,7 +128,7 @@ protected function aclLoad($config, ContainerBuilder $container) * @param ContainerBuilder $container A ContainerBuilder instance */ - protected function createRoleHierarchy($config, ContainerBuilder $container) + private function createRoleHierarchy($config, ContainerBuilder $container) { if (!isset($config['role_hierarchy'])) { $container->remove('security.access.role_hierarchy_voter'); @@ -140,7 +140,7 @@ protected function createRoleHierarchy($config, ContainerBuilder $container) $container->remove('security.access.simple_role_voter'); } - protected function createAuthorization($config, ContainerBuilder $container) + private function createAuthorization($config, ContainerBuilder $container) { if (!$config['access_control']) { return; @@ -165,7 +165,7 @@ protected function createAuthorization($config, ContainerBuilder $container) } } - protected function createFirewalls($config, ContainerBuilder $container) + private function createFirewalls($config, ContainerBuilder $container) { if (!isset($config['firewalls'])) { return; @@ -213,7 +213,7 @@ protected function createFirewalls($config, ContainerBuilder $container) ; } - protected function createFirewall(ContainerBuilder $container, $id, $firewall, &$authenticationProviders, $providerIds, array $factories) + private function createFirewall(ContainerBuilder $container, $id, $firewall, &$authenticationProviders, $providerIds, array $factories) { // Matcher $i = 0; @@ -310,7 +310,7 @@ protected function createFirewall(ContainerBuilder $container, $id, $firewall, & return array($matcher, $listeners, $exceptionListener); } - protected function createContextListener($container, $contextKey) + private function createContextListener($container, $contextKey) { if (isset($this->contextListeners[$contextKey])) { return $this->contextListeners[$contextKey]; @@ -323,7 +323,7 @@ protected function createContextListener($container, $contextKey) return $this->contextListeners[$contextKey] = $listenerId; } - protected function createAuthenticationListeners($container, $id, $firewall, &$authenticationProviders, $defaultProvider, array $factories) + private function createAuthenticationListeners($container, $id, $firewall, &$authenticationProviders, $defaultProvider, array $factories) { $listeners = array(); $hasListeners = false; @@ -359,11 +359,11 @@ protected function createAuthenticationListeners($container, $id, $firewall, &$a return array($listeners, $defaultEntryPoint); } - protected function createEncoders($encoders, ContainerBuilder $container) + private function createEncoders($encoders, ContainerBuilder $container) { $encoderMap = array(); foreach ($encoders as $class => $encoder) { - $encoderMap[$class] = $this->createEncoder($class, $encoder, $container); + $encoderMap[$class] = $this->createEncoder($encoder, $container); } $container @@ -372,7 +372,7 @@ protected function createEncoders($encoders, ContainerBuilder $container) ; } - protected function createEncoder($accountClass, $config, ContainerBuilder $container) + private function createEncoder($config, ContainerBuilder $container) { // a custom encoder service if (isset($config['id'])) { @@ -403,7 +403,7 @@ protected function createEncoder($accountClass, $config, ContainerBuilder $conta } // Parses user providers and returns an array of their ids - protected function createUserProviders($config, ContainerBuilder $container) + private function createUserProviders($config, ContainerBuilder $container) { $providerIds = array(); foreach ($config['providers'] as $name => $provider) { @@ -415,7 +415,7 @@ protected function createUserProviders($config, ContainerBuilder $container) } // Parses a tag and returns the id for the related user provider service - protected function createUserDaoProvider($name, $provider, ContainerBuilder $container, $master = true) + private function createUserDaoProvider($name, $provider, ContainerBuilder $container, $master = true) { $name = $this->getUserProviderId(strtolower($name)); @@ -468,12 +468,12 @@ protected function createUserDaoProvider($name, $provider, ContainerBuilder $con return $name; } - protected function getUserProviderId($name) + private function getUserProviderId($name) { return 'security.user.provider.concrete.'.$name; } - protected function createExceptionListener($container, $config, $id, $defaultEntryPoint) + private function createExceptionListener($container, $config, $id, $defaultEntryPoint) { $exceptionListenerId = 'security.exception_listener.'.$id; $listener = $container->setDefinition($exceptionListenerId, new DefinitionDecorator('security.exception_listener')); @@ -489,7 +489,7 @@ protected function createExceptionListener($container, $config, $id, $defaultEnt return $exceptionListenerId; } - protected function createSwitchUserListener($container, $id, $config, $defaultProvider) + private function createSwitchUserListener($container, $id, $config, $defaultProvider) { $userProvider = isset($config['provider']) ? $this->getUserProviderId($config['provider']) : $defaultProvider; @@ -503,7 +503,7 @@ protected function createSwitchUserListener($container, $id, $config, $defaultPr return $switchUserListenerId; } - protected function createRequestMatcher($container, $path = null, $host = null, $methods = null, $ip = null, array $attributes = array()) + private function createRequestMatcher($container, $path = null, $host = null, $methods = null, $ip = null, array $attributes = array()) { $serialized = serialize(array($path, $host, $methods, $ip, $attributes)); $id = 'security.request_matcher.'.md5($serialized).sha1($serialized); @@ -527,7 +527,7 @@ protected function createRequestMatcher($container, $path = null, $host = null, return $this->requestMatchers[$id] = new Reference($id); } - protected function createListenerFactories(ContainerBuilder $container, $config) + private function createListenerFactories(ContainerBuilder $container, $config) { if (null !== $this->factories) { return $this->factories; diff --git a/src/Symfony/Bundle/SecurityBundle/Resources/config/security.xml b/src/Symfony/Bundle/SecurityBundle/Resources/config/security.xml index 56f5780984fdb..b43d9d722d496 100644 --- a/src/Symfony/Bundle/SecurityBundle/Resources/config/security.xml +++ b/src/Symfony/Bundle/SecurityBundle/Resources/config/security.xml @@ -8,7 +8,7 @@ Symfony\Component\Security\Core\SecurityContext false - Symfony\Component\Security\Core\User\AccountChecker + Symfony\Component\Security\Core\User\UserChecker Symfony\Component\Security\Core\Encoder\EncoderFactory Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder @@ -72,7 +72,7 @@ - + diff --git a/src/Symfony/Bundle/SecurityBundle/Resources/config/security_listeners.xml b/src/Symfony/Bundle/SecurityBundle/Resources/config/security_listeners.xml index 216d3cf19d4a6..0fdc4aa685655 100644 --- a/src/Symfony/Bundle/SecurityBundle/Resources/config/security_listeners.xml +++ b/src/Symfony/Bundle/SecurityBundle/Resources/config/security_listeners.xml @@ -137,14 +137,14 @@ - + - + @@ -159,7 +159,7 @@ - + diff --git a/src/Symfony/Bundle/SecurityBundle/Resources/config/security_rememberme.xml b/src/Symfony/Bundle/SecurityBundle/Resources/config/security_rememberme.xml index bca250ed05ae5..55c87df404411 100644 --- a/src/Symfony/Bundle/SecurityBundle/Resources/config/security_rememberme.xml +++ b/src/Symfony/Bundle/SecurityBundle/Resources/config/security_rememberme.xml @@ -23,7 +23,7 @@ - + diff --git a/src/Symfony/Bundle/SecurityBundle/Security/FirewallContext.php b/src/Symfony/Bundle/SecurityBundle/Security/FirewallContext.php index 69289175b6a41..05a8fe558c9ec 100644 --- a/src/Symfony/Bundle/SecurityBundle/Security/FirewallContext.php +++ b/src/Symfony/Bundle/SecurityBundle/Security/FirewallContext.php @@ -12,8 +12,8 @@ */ class FirewallContext { - protected $listeners; - protected $exceptionListener; + private $listeners; + private $exceptionListener; public function __construct(array $listeners, ExceptionListener $exceptionListener = null) { diff --git a/src/Symfony/Bundle/SecurityBundle/Templating/Helper/SecurityHelper.php b/src/Symfony/Bundle/SecurityBundle/Templating/Helper/SecurityHelper.php index 1ba7a04f1579a..1ccc37c568e18 100644 --- a/src/Symfony/Bundle/SecurityBundle/Templating/Helper/SecurityHelper.php +++ b/src/Symfony/Bundle/SecurityBundle/Templating/Helper/SecurityHelper.php @@ -18,11 +18,11 @@ /** * SecurityHelper provides read-only access to the security context. * - * @author Fabien Potencier + * @author Fabien Potencier */ class SecurityHelper extends Helper { - protected $context; + private $context; /** * Constructor. @@ -34,7 +34,7 @@ public function __construct(SecurityContextInterface $context = null) $this->context = $context; } - public function vote($role, $object = null, $field = null) + public function isGranted($role, $object = null, $field = null) { if (null === $this->context) { return false; @@ -44,7 +44,7 @@ public function vote($role, $object = null, $field = null) $object = new FieldVote($object, $field); } - return $this->context->vote($role, $object); + return $this->context->isGranted($role, $object); } /** diff --git a/src/Symfony/Bundle/SecurityBundle/Twig/Extension/SecurityExtension.php b/src/Symfony/Bundle/SecurityBundle/Twig/Extension/SecurityExtension.php index a3148e5fb3e5c..b42576142691a 100644 --- a/src/Symfony/Bundle/SecurityBundle/Twig/Extension/SecurityExtension.php +++ b/src/Symfony/Bundle/SecurityBundle/Twig/Extension/SecurityExtension.php @@ -21,14 +21,14 @@ */ class SecurityExtension extends \Twig_Extension { - protected $context; + private $context; public function __construct(SecurityContextInterface $context = null) { $this->context = $context; } - public function vote($role, $object = null, $field = null) + public function isGranted($role, $object = null, $field = null) { if (null === $this->context) { return false; @@ -38,7 +38,7 @@ public function vote($role, $object = null, $field = null) $object = new FieldVote($object, $field); } - return $this->context->vote($role, $object); + return $this->context->isGranted($role, $object); } /** @@ -47,7 +47,7 @@ public function vote($role, $object = null, $field = null) public function getFunctions() { return array( - 'has_role' => new \Twig_Function_Method($this, 'vote'), + 'is_granted' => new \Twig_Function_Method($this, 'isGranted'), ); } diff --git a/src/Symfony/Component/Security/Acl/Dbal/AclProvider.php b/src/Symfony/Component/Security/Acl/Dbal/AclProvider.php index 2335f6908fc4c..2ef711dc8b5f6 100644 --- a/src/Symfony/Component/Security/Acl/Dbal/AclProvider.php +++ b/src/Symfony/Component/Security/Acl/Dbal/AclProvider.php @@ -38,12 +38,12 @@ class AclProvider implements AclProviderInterface { const MAX_BATCH_SIZE = 30; - protected $aclCache; + protected $cache; protected $connection; protected $loadedAces; protected $loadedAcls; protected $options; - protected $permissionGrantingStrategy; + private $permissionGrantingStrategy; /** * Constructor @@ -51,11 +51,11 @@ class AclProvider implements AclProviderInterface * @param Connection $connection * @param PermissionGrantingStrategyInterface $permissionGrantingStrategy * @param array $options - * @param AclCacheInterface $aclCache + * @param AclCacheInterface $cache */ - public function __construct(Connection $connection, PermissionGrantingStrategyInterface $permissionGrantingStrategy, array $options, AclCacheInterface $aclCache = null) + public function __construct(Connection $connection, PermissionGrantingStrategyInterface $permissionGrantingStrategy, array $options, AclCacheInterface $cache = null) { - $this->aclCache = $aclCache; + $this->cache = $cache; $this->connection = $connection; $this->loadedAces = array(); $this->loadedAcls = array(); @@ -122,8 +122,8 @@ public function findAcls(array $oids, array $sids = array()) } // check if we can locate the ACL in the cache - if (!$aclFound && null !== $this->aclCache) { - $acl = $this->aclCache->getFromCacheByIdentity($oid); + if (!$aclFound && null !== $this->cache) { + $acl = $this->cache->getFromCacheByIdentity($oid); if (null !== $acl) { if ($acl->isSidLoaded($sids)) { @@ -149,10 +149,10 @@ public function findAcls(array $oids, array $sids = array()) $result->attach($oid, $acl); $aclFound = true; } else { - $this->aclCache->evictFromCacheByIdentity($oid); + $this->cache->evictFromCacheByIdentity($oid); foreach ($this->findChildren($oid) as $childOid) { - $this->aclCache->evictFromCacheByIdentity($childOid); + $this->cache->evictFromCacheByIdentity($childOid); } } } @@ -170,8 +170,8 @@ public function findAcls(array $oids, array $sids = array()) foreach ($loadedBatch as $loadedOid) { $loadedAcl = $loadedBatch->offsetGet($loadedOid); - if (null !== $this->aclCache) { - $this->aclCache->putInCache($loadedAcl); + if (null !== $this->cache) { + $this->cache->putInCache($loadedAcl); } if (isset($oidLookup[$loadedOid->getIdentifier().$loadedOid->getType()])) { @@ -200,13 +200,157 @@ public function findAcls(array $oids, array $sids = array()) return $result; } + /** + * Constructs the query used for looking up object identities and associated + * ACEs, and security identities. + * + * @param array $ancestorIds + * @return string + */ + protected function getLookupSql(array $ancestorIds) + { + // FIXME: add support for filtering by sids (right now we select all sids) + + $sql = <<options['oid_table_name']} o + INNER JOIN {$this->options['class_table_name']} c ON c.id = o.class_id + LEFT JOIN {$this->options['entry_table_name']} e ON ( + e.class_id = o.class_id AND (e.object_identity_id = o.id OR {$this->connection->getDatabasePlatform()->getIsNullExpression('e.object_identity_id')}) + ) + LEFT JOIN {$this->options['sid_table_name']} s ON ( + s.id = e.security_identity_id + ) + + WHERE (o.id = +SELECTCLAUSE; + + $sql .= implode(' OR o.id = ', $ancestorIds).')'; + + return $sql; + } + + protected function getAncestorLookupSql(array $batch) + { + $sql = <<connection->quote($batch[$i]->getIdentifier()), + $this->connection->quote($batch[$i]->getType()) + ); + + if ($i+1 < $c) { + $sql .= ' OR '; + } + } + + $sql .= ')'; + + return $sql; + } + + /** + * Constructs the SQL for retrieving child object identities for the given + * object identities. + * + * @param ObjectIdentityInterface $oid + * @param Boolean $directChildrenOnly + * @return string + */ + protected function getFindChildrenSql(ObjectIdentityInterface $oid, $directChildrenOnly) + { + if (false === $directChildrenOnly) { + $query = <<options['oid_table_name']} as o + INNER JOIN {$this->options['class_table_name']} as c ON c.id = o.class_id + INNER JOIN {$this->options['oid_ancestors_table_name']} as a ON a.object_identity_id = o.id + WHERE + a.ancestor_id = %d AND a.object_identity_id != a.ancestor_id +FINDCHILDREN; + } else { + $query = <<options['oid_table_name']} as o + INNER JOIN {$this->options['class_table_name']} as c ON c.id = o.class_id + WHERE o.parent_object_identity_id = %d +FINDCHILDREN; + } + + return sprintf($query, $this->retrieveObjectIdentityPrimaryKey($oid)); + } + + /** + * Constructs the SQL for retrieving the primary key of the given object + * identity. + * + * @param ObjectIdentityInterface $oid + * @return string + */ + protected function getSelectObjectIdentityIdSql(ObjectIdentityInterface $oid) + { + $query = <<options['oid_table_name'], + $this->options['class_table_name'], + $this->connection->quote($oid->getIdentifier()), + $this->connection->quote($oid->getType()) + ); + } + + /** + * Returns the primary key of the passed object identity. + * + * @param ObjectIdentityInterface $oid + * @return integer + */ + protected final function retrieveObjectIdentityPrimaryKey(ObjectIdentityInterface $oid) + { + return $this->connection->executeQuery($this->getSelectObjectIdentityIdSql($oid))->fetchColumn(); + } + /** * This method is called when an ACL instance is retrieved from the cache. * * @param AclInterface $acl * @return void */ - protected function updateAceIdentityMap(AclInterface $acl) + private function updateAceIdentityMap(AclInterface $acl) { foreach (array('classAces', 'classFieldAces', 'objectAces', 'objectFieldAces') as $property) { $reflection = new \ReflectionProperty($acl, $property); @@ -226,6 +370,27 @@ protected function updateAceIdentityMap(AclInterface $acl) } } + /** + * Retrieves all the ids which need to be queried from the database + * including the ids of parent ACLs. + * + * @param array $batch + * @return array + */ + private function getAncestorIds(array $batch) + { + $sql = $this->getAncestorLookupSql($batch); + + $ancestorIds = array(); + foreach ($this->connection->executeQuery($sql)->fetchAll() as $data) { + // FIXME: skip ancestors which are cached + + $ancestorIds[] = $data['ancestor_id']; + } + + return $ancestorIds; + } + /** * Does either overwrite the passed ACE, or saves it in the global identity * map to ensure every ACE only gets instantiated once. @@ -233,7 +398,7 @@ protected function updateAceIdentityMap(AclInterface $acl) * @param array $aces * @return void */ - protected function doUpdateAceIdentityMap(array &$aces) + private function doUpdateAceIdentityMap(array &$aces) { foreach ($aces as $index => $ace) { if (isset($this->loadedAces[$ace->getId()])) { @@ -254,9 +419,14 @@ protected function doUpdateAceIdentityMap(array &$aces) * * @return \SplObjectStorage mapping object identities to ACL instances */ - protected function lookupObjectIdentities(array $batch, array $sids, array $oidLookup) + private function lookupObjectIdentities(array $batch, array $sids, array $oidLookup) { - $sql = $this->getLookupSql($batch, $sids); + $ancestorIds = $this->getAncestorIds($batch); + if (!$ancestorIds) { + throw new AclNotFoundException('There is no ACL for the given object identity.'); + } + + $sql = $this->getLookupSql($ancestorIds); $stmt = $this->connection->executeQuery($sql); return $this->hydrateObjectIdentities($stmt, $oidLookup, $sids); @@ -277,7 +447,7 @@ protected function lookupObjectIdentities(array $batch, array $sids, array $oidL * @throws \RuntimeException * @return \SplObjectStorage */ - protected function hydrateObjectIdentities(Statement $stmt, array $oidLookup, array $sids) { + private function hydrateObjectIdentities(Statement $stmt, array $oidLookup, array $sids) { $parentIdToFill = new \SplObjectStorage(); $acls = $aces = $emptyArray = array(); $oidCache = $oidLookup; @@ -464,169 +634,4 @@ protected function hydrateObjectIdentities(Statement $stmt, array $oidLookup, ar return $result; } - - /** - * Constructs the query used for looking up object identities and associated - * ACEs, and security identities. - * - * @param array $batch - * @param array $sids - * @throws AclNotFoundException - * @return string - */ - protected function getLookupSql(array $batch, array $sids) - { - // FIXME: add support for filtering by sids (right now we select all sids) - - $ancestorIds = $this->getAncestorIds($batch); - if (0 === count($ancestorIds)) { - throw new AclNotFoundException('There is no ACL for the given object identity.'); - } - - $sql = <<options['oid_table_name']} o - INNER JOIN {$this->options['class_table_name']} c ON c.id = o.class_id - LEFT JOIN {$this->options['entry_table_name']} e ON ( - e.class_id = o.class_id AND (e.object_identity_id = o.id OR {$this->connection->getDatabasePlatform()->getIsNullExpression('e.object_identity_id')}) - ) - LEFT JOIN {$this->options['sid_table_name']} s ON ( - s.id = e.security_identity_id - ) - - WHERE (o.id = -SELECTCLAUSE; - - $sql .= implode(' OR o.id = ', $ancestorIds).')'; - - return $sql; - } - - /** - * Retrieves all the ids which need to be queried from the database - * including the ids of parent ACLs. - * - * @param array $batch - * @return array - */ - protected function getAncestorIds(array &$batch) - { - $sql = <<connection->quote($batch[$i]->getIdentifier()), - $this->connection->quote($batch[$i]->getType()) - ); - - if ($i+1 < $c) { - $sql .= ' OR '; - } - } - - $sql .= ')'; - - $ancestorIds = array(); - foreach ($this->connection->executeQuery($sql)->fetchAll() as $data) { - // FIXME: skip ancestors which are cached - - $ancestorIds[] = $data['ancestor_id']; - } - - return $ancestorIds; - } - - /** - * Constructs the SQL for retrieving child object identities for the given - * object identities. - * - * @param ObjectIdentityInterface $oid - * @param Boolean $directChildrenOnly - * @return string - */ - protected function getFindChildrenSql(ObjectIdentityInterface $oid, $directChildrenOnly) - { - if (false === $directChildrenOnly) { - $query = <<options['oid_table_name']} as o - INNER JOIN {$this->options['class_table_name']} as c ON c.id = o.class_id - INNER JOIN {$this->options['oid_ancestors_table_name']} as a ON a.object_identity_id = o.id - WHERE - a.ancestor_id = %d AND a.object_identity_id != a.ancestor_id -FINDCHILDREN; - } else { - $query = <<options['oid_table_name']} as o - INNER JOIN {$this->options['class_table_name']} as c ON c.id = o.class_id - WHERE o.parent_object_identity_id = %d -FINDCHILDREN; - } - - return sprintf($query, $this->retrieveObjectIdentityPrimaryKey($oid)); - } - - /** - * Constructs the SQL for retrieving the primary key of the given object - * identity. - * - * @param ObjectIdentityInterface $oid - * @return string - */ - protected function getSelectObjectIdentityIdSql(ObjectIdentityInterface $oid) - { - $query = <<options['oid_table_name'], - $this->options['class_table_name'], - $this->connection->quote($oid->getIdentifier()), - $this->connection->quote($oid->getType()) - ); - } - - /** - * Returns the primary key of the passed object identity. - * - * @param ObjectIdentityInterface $oid - * @return integer - */ - protected function retrieveObjectIdentityPrimaryKey(ObjectIdentityInterface $oid) - { - return $this->connection->executeQuery($this->getSelectObjectIdentityIdSql($oid))->fetchColumn(); - } } diff --git a/src/Symfony/Component/Security/Acl/Dbal/MutableAclProvider.php b/src/Symfony/Component/Security/Acl/Dbal/MutableAclProvider.php index 9b36d6a2505f8..52d1a9b8f0ffb 100644 --- a/src/Symfony/Component/Security/Acl/Dbal/MutableAclProvider.php +++ b/src/Symfony/Component/Security/Acl/Dbal/MutableAclProvider.php @@ -34,14 +34,14 @@ */ class MutableAclProvider extends AclProvider implements MutableAclProviderInterface, PropertyChangedListener { - protected $propertyChanges; + private $propertyChanges; /** * {@inheritDoc} */ - public function __construct(Connection $connection, PermissionGrantingStrategyInterface $permissionGrantingStrategy, array $options, AclCacheInterface $aclCache = null) + public function __construct(Connection $connection, PermissionGrantingStrategyInterface $permissionGrantingStrategy, array $options, AclCacheInterface $cache = null) { - parent::__construct($connection, $permissionGrantingStrategy, $options, $aclCache); + parent::__construct($connection, $permissionGrantingStrategy, $options, $cache); $this->propertyChanges = new \SplObjectStorage(); } @@ -104,8 +104,8 @@ public function deleteAcl(ObjectIdentityInterface $oid) } // evict the ACL from any caches - if (null !== $this->aclCache) { - $this->aclCache->evictFromCacheByIdentity($oid); + if (null !== $this->cache) { + $this->cache->evictFromCacheByIdentity($oid); } } @@ -312,110 +312,25 @@ public function updateAcl(MutableAclInterface $acl) $this->propertyChanges->offsetSet($acl, array()); - if (null !== $this->aclCache) { + if (null !== $this->cache) { if (count($sharedPropertyChanges) > 0) { // FIXME: Currently, there is no easy way to clear the cache for ACLs // of a certain type. The problem here is that we need to make // sure to clear the cache of all child ACLs as well, and these // child ACLs might be of a different class type. - $this->aclCache->clearCache(); + $this->cache->clearCache(); } else { // if there are no shared property changes, it's sufficient to just delete // the cache for this ACL - $this->aclCache->evictFromCacheByIdentity($acl->getObjectIdentity()); + $this->cache->evictFromCacheByIdentity($acl->getObjectIdentity()); foreach ($this->findChildren($acl->getObjectIdentity()) as $childOid) { - $this->aclCache->evictFromCacheByIdentity($childOid); + $this->cache->evictFromCacheByIdentity($childOid); } } } } - /** - * Creates the ACL for the passed object identity - * - * @param ObjectIdentityInterface $oid - * @return void - */ - protected function createObjectIdentity(ObjectIdentityInterface $oid) - { - $classId = $this->createOrRetrieveClassId($oid->getType()); - - $this->connection->executeQuery($this->getInsertObjectIdentitySql($oid->getIdentifier(), $classId, true)); - } - - /** - * Returns the primary key for the passed class type. - * - * If the type does not yet exist in the database, it will be created. - * - * @param string $classType - * @return integer - */ - protected function createOrRetrieveClassId($classType) - { - if (false !== $id = $this->connection->executeQuery($this->getSelectClassIdSql($classType))->fetchColumn()) { - return $id; - } - - $this->connection->executeQuery($this->getInsertClassSql($classType)); - - return $this->connection->executeQuery($this->getSelectClassIdSql($classType))->fetchColumn(); - } - - /** - * Returns the primary key for the passed security identity. - * - * If the security identity does not yet exist in the database, it will be - * created. - * - * @param SecurityIdentityInterface $sid - * @return integer - */ - protected function createOrRetrieveSecurityIdentityId(SecurityIdentityInterface $sid) - { - if (false !== $id = $this->connection->executeQuery($this->getSelectSecurityIdentityIdSql($sid))->fetchColumn()) { - return $id; - } - - $this->connection->executeQuery($this->getInsertSecurityIdentitySql($sid)); - - return $this->connection->executeQuery($this->getSelectSecurityIdentityIdSql($sid))->fetchColumn(); - } - - /** - * Deletes all ACEs for the given object identity primary key. - * - * @param integer $oidPK - * @return void - */ - protected function deleteAccessControlEntries($oidPK) - { - $this->connection->executeQuery($this->getDeleteAccessControlEntriesSql($oidPK)); - } - - /** - * Deletes the object identity from the database. - * - * @param integer $pk - * @return void - */ - protected function deleteObjectIdentity($pk) - { - $this->connection->executeQuery($this->getDeleteObjectIdentitySql($pk)); - } - - /** - * Deletes all entries from the relations table from the database. - * - * @param integer $pk - * @return void - */ - protected function deleteObjectIdentityRelations($pk) - { - $this->connection->executeQuery($this->getDeleteObjectIdentityRelationsSql($pk)); - } - /** * Constructs the SQL for deleting access control entries. * @@ -720,13 +635,98 @@ protected function getUpdateAccessControlEntrySql($pk, array $sets) ); } + /** + * Creates the ACL for the passed object identity + * + * @param ObjectIdentityInterface $oid + * @return void + */ + private function createObjectIdentity(ObjectIdentityInterface $oid) + { + $classId = $this->createOrRetrieveClassId($oid->getType()); + + $this->connection->executeQuery($this->getInsertObjectIdentitySql($oid->getIdentifier(), $classId, true)); + } + + /** + * Returns the primary key for the passed class type. + * + * If the type does not yet exist in the database, it will be created. + * + * @param string $classType + * @return integer + */ + private function createOrRetrieveClassId($classType) + { + if (false !== $id = $this->connection->executeQuery($this->getSelectClassIdSql($classType))->fetchColumn()) { + return $id; + } + + $this->connection->executeQuery($this->getInsertClassSql($classType)); + + return $this->connection->executeQuery($this->getSelectClassIdSql($classType))->fetchColumn(); + } + + /** + * Returns the primary key for the passed security identity. + * + * If the security identity does not yet exist in the database, it will be + * created. + * + * @param SecurityIdentityInterface $sid + * @return integer + */ + private function createOrRetrieveSecurityIdentityId(SecurityIdentityInterface $sid) + { + if (false !== $id = $this->connection->executeQuery($this->getSelectSecurityIdentityIdSql($sid))->fetchColumn()) { + return $id; + } + + $this->connection->executeQuery($this->getInsertSecurityIdentitySql($sid)); + + return $this->connection->executeQuery($this->getSelectSecurityIdentityIdSql($sid))->fetchColumn(); + } + + /** + * Deletes all ACEs for the given object identity primary key. + * + * @param integer $oidPK + * @return void + */ + private function deleteAccessControlEntries($oidPK) + { + $this->connection->executeQuery($this->getDeleteAccessControlEntriesSql($oidPK)); + } + + /** + * Deletes the object identity from the database. + * + * @param integer $pk + * @return void + */ + private function deleteObjectIdentity($pk) + { + $this->connection->executeQuery($this->getDeleteObjectIdentitySql($pk)); + } + + /** + * Deletes all entries from the relations table from the database. + * + * @param integer $pk + * @return void + */ + private function deleteObjectIdentityRelations($pk) + { + $this->connection->executeQuery($this->getDeleteObjectIdentityRelationsSql($pk)); + } + /** * This regenerates the ancestor table which is used for fast read access. * * @param AclInterface $acl * @return void */ - protected function regenerateAncestorRelations(AclInterface $acl) + private function regenerateAncestorRelations(AclInterface $acl) { $pk = $acl->getId(); $this->connection->executeQuery($this->getDeleteObjectIdentityRelationsSql($pk)); @@ -747,7 +747,7 @@ protected function regenerateAncestorRelations(AclInterface $acl) * @param array $changes * @return void */ - protected function updateFieldAceProperty($name, array $changes) + private function updateFieldAceProperty($name, array $changes) { $sids = new \SplObjectStorage(); $classIds = new \SplObjectStorage(); @@ -804,7 +804,7 @@ protected function updateFieldAceProperty($name, array $changes) * @param array $changes * @return void */ - protected function updateAceProperty($name, array $changes) + private function updateAceProperty($name, array $changes) { list($old, $new) = $changes; @@ -858,7 +858,7 @@ protected function updateAceProperty($name, array $changes) * @param \SplObjectStorage $aces * @return void */ - protected function updateAces(\SplObjectStorage $aces) + private function updateAces(\SplObjectStorage $aces) { foreach ($aces as $ace) { $propertyChanges = $aces->offsetGet($ace); diff --git a/src/Symfony/Component/Security/Acl/Dbal/Schema.php b/src/Symfony/Component/Security/Acl/Dbal/Schema.php index 29907b44ccc8c..09d60aa931292 100644 --- a/src/Symfony/Component/Security/Acl/Dbal/Schema.php +++ b/src/Symfony/Component/Security/Acl/Dbal/Schema.php @@ -18,7 +18,7 @@ * * @author Johannes M. Schmitt */ -class Schema extends BaseSchema +final class Schema extends BaseSchema { protected $options; diff --git a/src/Symfony/Component/Security/Acl/Domain/Acl.php b/src/Symfony/Component/Security/Acl/Domain/Acl.php index 6769617d0e65c..20f300b53980b 100644 --- a/src/Symfony/Component/Security/Acl/Domain/Acl.php +++ b/src/Symfony/Component/Security/Acl/Domain/Acl.php @@ -35,17 +35,17 @@ */ class Acl implements AuditableAclInterface { - protected $parentAcl; - protected $permissionGrantingStrategy; - protected $objectIdentity; - protected $classAces; - protected $classFieldAces; - protected $objectAces; - protected $objectFieldAces; - protected $id; - protected $loadedSids; - protected $entriesInheriting; - protected $listeners; + private $parentAcl; + private $permissionGrantingStrategy; + private $objectIdentity; + private $classAces; + private $classFieldAces; + private $objectAces; + private $objectFieldAces; + private $id; + private $loadedSids; + private $entriesInheriting; + private $listeners; /** * Constructor @@ -406,7 +406,7 @@ public function updateObjectFieldAuditing($index, $field, $auditSuccess, $auditF * @throws \OutOfBoundsException * @return void */ - protected function deleteAce($property, $index) + private function deleteAce($property, $index) { $aces =& $this->$property; if (!isset($aces[$index])) { @@ -432,7 +432,7 @@ protected function deleteAce($property, $index) * @throws \OutOfBoundsException * @return void */ - protected function deleteFieldAce($property, $index, $field) + private function deleteFieldAce($property, $index, $field) { $aces =& $this->$property; if (!isset($aces[$field][$index])) { @@ -462,7 +462,7 @@ protected function deleteFieldAce($property, $index, $field) * @throws \InvalidArgumentException * @return void */ - protected function insertAce($property, $index, $mask, SecurityIdentityInterface $sid, $granting, $strategy = null) + private function insertAce($property, $index, $mask, SecurityIdentityInterface $sid, $granting, $strategy = null) { if ($index < 0 || $index > count($this->$property)) { throw new \OutOfBoundsException(sprintf('The index must be in the interval [0, %d].', count($this->$property))); @@ -512,7 +512,7 @@ protected function insertAce($property, $index, $mask, SecurityIdentityInterface * @throws \OutOfBoundsException * @return void */ - protected function insertFieldAce($property, $index, $field, $mask, SecurityIdentityInterface $sid, $granting, $strategy = null) + private function insertFieldAce($property, $index, $field, $mask, SecurityIdentityInterface $sid, $granting, $strategy = null) { if (0 === strlen($field)) { throw new \InvalidArgumentException('$field cannot be empty.'); @@ -556,37 +556,6 @@ protected function insertFieldAce($property, $index, $field, $mask, SecurityIden $this->onPropertyChanged($property, $oldValue, $this->$property); } - /** - * Called when a property of the ACL changes - * - * @param string $name - * @param mixed $oldValue - * @param mixed $newValue - * @return void - */ - protected function onPropertyChanged($name, $oldValue, $newValue) - { - foreach ($this->listeners as $listener) { - $listener->propertyChanged($this, $name, $oldValue, $newValue); - } - } - - /** - * Called when a property of an ACE associated with this ACL changes - * - * @param EntryInterface $entry - * @param string $name - * @param mixed $oldValue - * @param mixed $newValue - * @return void - */ - protected function onEntryPropertyChanged(EntryInterface $entry, $name, $oldValue, $newValue) - { - foreach ($this->listeners as $listener) { - $listener->propertyChanged($entry, $name, $oldValue, $newValue); - } - } - /** * Updates an ACE * @@ -597,7 +566,7 @@ protected function onEntryPropertyChanged(EntryInterface $entry, $name, $oldValu * @throws \OutOfBoundsException * @return void */ - protected function updateAce($property, $index, $mask, $strategy = null) + private function updateAce($property, $index, $mask, $strategy = null) { $aces =& $this->$property; if (!isset($aces[$index])) { @@ -625,7 +594,7 @@ protected function updateAce($property, $index, $mask, $strategy = null) * @throws \OutOfBoundsException * @return void */ - protected function updateAuditing(array &$aces, $index, $auditSuccess, $auditFailure) + private function updateAuditing(array &$aces, $index, $auditSuccess, $auditFailure) { if (!isset($aces[$index])) { throw new \OutOfBoundsException(sprintf('The index "%d" does not exist.', $index)); @@ -654,7 +623,7 @@ protected function updateAuditing(array &$aces, $index, $auditSuccess, $auditFai * @throws \OutOfBoundsException * @return void */ - protected function updateFieldAce($property, $index, $field, $mask, $strategy = null) + private function updateFieldAce($property, $index, $field, $mask, $strategy = null) { if (0 === strlen($field)) { throw new \InvalidArgumentException('$field cannot be empty.'); @@ -675,4 +644,35 @@ protected function updateFieldAce($property, $index, $field, $mask, $strategy = $ace->setStrategy($strategy); } } + + /** + * Called when a property of the ACL changes + * + * @param string $name + * @param mixed $oldValue + * @param mixed $newValue + * @return void + */ + private function onPropertyChanged($name, $oldValue, $newValue) + { + foreach ($this->listeners as $listener) { + $listener->propertyChanged($this, $name, $oldValue, $newValue); + } + } + + /** + * Called when a property of an ACE associated with this ACL changes + * + * @param EntryInterface $entry + * @param string $name + * @param mixed $oldValue + * @param mixed $newValue + * @return void + */ + private function onEntryPropertyChanged(EntryInterface $entry, $name, $oldValue, $newValue) + { + foreach ($this->listeners as $listener) { + $listener->propertyChanged($entry, $name, $oldValue, $newValue); + } + } } diff --git a/src/Symfony/Component/Security/Acl/Domain/AclCollectionCache.php b/src/Symfony/Component/Security/Acl/Domain/AclCollectionCache.php index 81c88fe6d14a9..f3fe6f0b09eec 100644 --- a/src/Symfony/Component/Security/Acl/Domain/AclCollectionCache.php +++ b/src/Symfony/Component/Security/Acl/Domain/AclCollectionCache.php @@ -22,9 +22,9 @@ */ class AclCollectionCache { - protected $aclProvider; - protected $objectIdentityRetrievalStrategy; - protected $securityIdentityRetrievalStrategy; + private $aclProvider; + private $objectIdentityRetrievalStrategy; + private $securityIdentityRetrievalStrategy; /** * Constructor diff --git a/src/Symfony/Component/Security/Acl/Domain/DoctrineAclCache.php b/src/Symfony/Component/Security/Acl/Domain/DoctrineAclCache.php index 3aae00fd296b5..eb18986a8cee7 100644 --- a/src/Symfony/Component/Security/Acl/Domain/DoctrineAclCache.php +++ b/src/Symfony/Component/Security/Acl/Domain/DoctrineAclCache.php @@ -26,9 +26,9 @@ class DoctrineAclCache implements AclCacheInterface { const PREFIX = 'sf2_acl_'; - protected $cache; - protected $prefix; - protected $permissionGrantingStrategy; + private $cache; + private $prefix; + private $permissionGrantingStrategy; /** * Constructor @@ -145,7 +145,7 @@ public function putInCache(AclInterface $acl) * @param string $serialized * @return AclInterface */ - protected function unserializeAcl($serialized) + private function unserializeAcl($serialized) { $acl = unserialize($serialized); @@ -203,7 +203,7 @@ protected function unserializeAcl($serialized) * @param ObjectIdentityInterface $oid * @return string */ - protected function getDataKeyByIdentity(ObjectIdentityInterface $oid) + private function getDataKeyByIdentity(ObjectIdentityInterface $oid) { return $this->prefix.md5($oid->getType()).sha1($oid->getType()) .'_'.md5($oid->getIdentifier()).sha1($oid->getIdentifier()); @@ -215,7 +215,7 @@ protected function getDataKeyByIdentity(ObjectIdentityInterface $oid) * @param string $aclId * @return string */ - protected function getAliasKeyForIdentity($aclId) + private function getAliasKeyForIdentity($aclId) { return $this->prefix.$aclId; } diff --git a/src/Symfony/Component/Security/Acl/Domain/Entry.php b/src/Symfony/Component/Security/Acl/Domain/Entry.php index 67e76ad9511d4..7498b035d6c05 100644 --- a/src/Symfony/Component/Security/Acl/Domain/Entry.php +++ b/src/Symfony/Component/Security/Acl/Domain/Entry.php @@ -23,14 +23,14 @@ */ class Entry implements AuditableEntryInterface { - protected $acl; - protected $mask; - protected $id; - protected $securityIdentity; - protected $strategy; - protected $auditFailure; - protected $auditSuccess; - protected $granting; + private $acl; + private $mask; + private $id; + private $securityIdentity; + private $strategy; + private $auditFailure; + private $auditSuccess; + private $granting; /** * Constructor @@ -122,10 +122,10 @@ public function isGranting() /** * Turns on/off auditing on permissions denials. - * + * * Do never call this method directly. Use the respective methods on the * AclInterface instead. - * + * * @param Boolean $boolean * @return void */ @@ -136,10 +136,10 @@ public function setAuditFailure($boolean) /** * Turns on/off auditing on permission grants. - * + * * Do never call this method directly. Use the respective methods on the * AclInterface instead. - * + * * @param Boolean $boolean * @return void */ @@ -153,7 +153,7 @@ public function setAuditSuccess($boolean) * * Do never call this method directly. Use the respective methods on the * AclInterface instead. - * + * * @param integer $mask * @return void */ @@ -167,7 +167,7 @@ public function setMask($mask) * * Do never call this method directly. Use the respective methods on the * AclInterface instead. - * + * * @param string $strategy * @return void */ diff --git a/src/Symfony/Component/Security/Acl/Domain/FieldEntry.php b/src/Symfony/Component/Security/Acl/Domain/FieldEntry.php index 430f013dffbfd..0f7123783179b 100644 --- a/src/Symfony/Component/Security/Acl/Domain/FieldEntry.php +++ b/src/Symfony/Component/Security/Acl/Domain/FieldEntry.php @@ -22,7 +22,7 @@ */ class FieldEntry extends Entry implements FieldAwareEntryInterface { - protected $field; + private $field; /** * Constructor @@ -60,13 +60,7 @@ public function serialize() { return serialize(array( $this->field, - $this->mask, - $this->id, - $this->securityIdentity, - $this->strategy, - $this->auditFailure, - $this->auditSuccess, - $this->granting, + parent::serialize(), )); } @@ -75,14 +69,7 @@ public function serialize() */ public function unserialize($serialized) { - list($this->field, - $this->mask, - $this->id, - $this->securityIdentity, - $this->strategy, - $this->auditFailure, - $this->auditSuccess, - $this->granting - ) = unserialize($serialized); + list($this->field, $parentStr) = unserialize($serialized); + parent::unserialize($parentStr); } } \ No newline at end of file diff --git a/src/Symfony/Component/Security/Acl/Domain/ObjectIdentity.php b/src/Symfony/Component/Security/Acl/Domain/ObjectIdentity.php index 8fc099bc29816..2cb1352bf73a2 100644 --- a/src/Symfony/Component/Security/Acl/Domain/ObjectIdentity.php +++ b/src/Symfony/Component/Security/Acl/Domain/ObjectIdentity.php @@ -22,8 +22,8 @@ */ class ObjectIdentity implements ObjectIdentityInterface { - protected $identifier; - protected $type; + private $identifier; + private $type; /** * Constructor diff --git a/src/Symfony/Component/Security/Acl/Domain/PermissionGrantingStrategy.php b/src/Symfony/Component/Security/Acl/Domain/PermissionGrantingStrategy.php index 9b44177413c15..8bee157ae4f35 100644 --- a/src/Symfony/Component/Security/Acl/Domain/PermissionGrantingStrategy.php +++ b/src/Symfony/Component/Security/Acl/Domain/PermissionGrantingStrategy.php @@ -30,8 +30,8 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface const ALL = 'all'; const ANY = 'any'; - protected static $noAceException; - protected $auditLogger; + private static $noAceException; + private $auditLogger; public function __construct() { @@ -51,16 +51,6 @@ public function setAuditLogger(AuditLoggerInterface $auditLogger) $this->auditLogger = $auditLogger; } - /** - * Returns the audit logger - * - * @return AuditLoggerInterface - */ - public function getAuditLogger() - { - return $this->auditLogger; - } - /** * {@inheritDoc} */ @@ -153,7 +143,7 @@ public function isFieldGranted(AclInterface $acl, $field, array $masks, array $s * @param Boolean $administrativeMode true turns off audit logging * @return Boolean true, or false; either granting, or denying access respectively. */ - protected function hasSufficientPermissions(AclInterface $acl, array $aces, array $masks, array $sids, $administrativeMode) + private function hasSufficientPermissions(AclInterface $acl, array $aces, array $masks, array $sids, $administrativeMode) { $firstRejectedAce = null; @@ -211,7 +201,7 @@ protected function hasSufficientPermissions(AclInterface $acl, array $aces, arra * @param EntryInterface $ace * @return Boolean */ - protected function isAceApplicable($requiredMask, EntryInterface $ace) + private function isAceApplicable($requiredMask, EntryInterface $ace) { $strategy = $ace->getStrategy(); if (self::ALL === $strategy) { diff --git a/src/Symfony/Component/Security/Acl/Domain/RoleSecurityIdentity.php b/src/Symfony/Component/Security/Acl/Domain/RoleSecurityIdentity.php index a824032040601..d3694e662477d 100644 --- a/src/Symfony/Component/Security/Acl/Domain/RoleSecurityIdentity.php +++ b/src/Symfony/Component/Security/Acl/Domain/RoleSecurityIdentity.php @@ -21,7 +21,7 @@ */ class RoleSecurityIdentity implements SecurityIdentityInterface { - protected $role; + private $role; /** * Constructor diff --git a/src/Symfony/Component/Security/Acl/Domain/SecurityIdentityRetrievalStrategy.php b/src/Symfony/Component/Security/Acl/Domain/SecurityIdentityRetrievalStrategy.php index c810e38e3f179..1252a0f7e9d55 100644 --- a/src/Symfony/Component/Security/Acl/Domain/SecurityIdentityRetrievalStrategy.php +++ b/src/Symfony/Component/Security/Acl/Domain/SecurityIdentityRetrievalStrategy.php @@ -13,7 +13,7 @@ use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken; -use Symfony\Component\Security\Core\User\AccountInterface; +use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Acl\Model\SecurityIdentityRetrievalStrategyInterface; use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver; @@ -27,8 +27,8 @@ */ class SecurityIdentityRetrievalStrategy implements SecurityIdentityRetrievalStrategyInterface { - protected $roleHierarchy; - protected $authenticationTrustResolver; + private $roleHierarchy; + private $authenticationTrustResolver; /** * Constructor diff --git a/src/Symfony/Component/Security/Acl/Domain/UserSecurityIdentity.php b/src/Symfony/Component/Security/Acl/Domain/UserSecurityIdentity.php index 4073bb43873cf..ac63080b44b11 100644 --- a/src/Symfony/Component/Security/Acl/Domain/UserSecurityIdentity.php +++ b/src/Symfony/Component/Security/Acl/Domain/UserSecurityIdentity.php @@ -12,7 +12,7 @@ namespace Symfony\Component\Security\Acl\Domain; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; -use Symfony\Component\Security\Core\User\AccountInterface; +use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Acl\Model\SecurityIdentityInterface; /** @@ -22,8 +22,8 @@ */ class UserSecurityIdentity implements SecurityIdentityInterface { - protected $username; - protected $class; + private $username; + private $class; /** * Constructor @@ -45,12 +45,12 @@ public function __construct($username, $class) } /** - * Creates a user security identity from an AccountInterface + * Creates a user security identity from an UserInterface * - * @param AccountInterface $user + * @param UserInterface $user * @return UserSecurityIdentity */ - public static function fromAccount(AccountInterface $user) + public static function fromAccount(UserInterface $user) { return new self($user->getUsername(), get_class($user)); } @@ -65,7 +65,7 @@ public static function fromToken(TokenInterface $token) { $user = $token->getUser(); - if ($user instanceof AccountInterface) { + if ($user instanceof UserInterface) { return self::fromAccount($user); } diff --git a/src/Symfony/Component/Security/Acl/Exception/NotAllAclsFoundException.php b/src/Symfony/Component/Security/Acl/Exception/NotAllAclsFoundException.php index 7db9b21841606..820d933f1b5e7 100644 --- a/src/Symfony/Component/Security/Acl/Exception/NotAllAclsFoundException.php +++ b/src/Symfony/Component/Security/Acl/Exception/NotAllAclsFoundException.php @@ -22,7 +22,7 @@ */ class NotAllAclsFoundException extends AclNotFoundException { - protected $partialResult; + private $partialResult; /** * Sets the partial result diff --git a/src/Symfony/Component/Security/Acl/Permission/BasicPermissionMap.php b/src/Symfony/Component/Security/Acl/Permission/BasicPermissionMap.php index 4818e0ce351f0..18006ff9b7174 100644 --- a/src/Symfony/Component/Security/Acl/Permission/BasicPermissionMap.php +++ b/src/Symfony/Component/Security/Acl/Permission/BasicPermissionMap.php @@ -28,7 +28,7 @@ class BasicPermissionMap implements PermissionMapInterface const PERMISSION_MASTER = 'MASTER'; const PERMISSION_OWNER = 'OWNER'; - protected $map = array( + private $map = array( self::PERMISSION_VIEW => array( MaskBuilder::MASK_VIEW, MaskBuilder::MASK_EDIT, diff --git a/src/Symfony/Component/Security/Acl/Permission/MaskBuilder.php b/src/Symfony/Component/Security/Acl/Permission/MaskBuilder.php index b1c283abe27e0..99652286ef82a 100644 --- a/src/Symfony/Component/Security/Acl/Permission/MaskBuilder.php +++ b/src/Symfony/Component/Security/Acl/Permission/MaskBuilder.php @@ -67,7 +67,7 @@ class MaskBuilder const OFF = '.'; const ON = '*'; - protected $mask; + private $mask; /** * Constructor diff --git a/src/Symfony/Component/Security/Acl/Voter/AclVoter.php b/src/Symfony/Component/Security/Acl/Voter/AclVoter.php index bc70c59c38887..e7811edb3a849 100644 --- a/src/Symfony/Component/Security/Acl/Voter/AclVoter.php +++ b/src/Symfony/Component/Security/Acl/Voter/AclVoter.php @@ -32,12 +32,12 @@ */ class AclVoter implements VoterInterface { - protected $aclProvider; - protected $permissionMap; - protected $objectIdentityRetrievalStrategy; - protected $securityIdentityRetrievalStrategy; - protected $allowIfObjectIdentityUnavailable; - protected $logger; + private $aclProvider; + private $permissionMap; + private $objectIdentityRetrievalStrategy; + private $securityIdentityRetrievalStrategy; + private $allowIfObjectIdentityUnavailable; + private $logger; public function __construct(AclProviderInterface $aclProvider, ObjectIdentityRetrievalStrategyInterface $oidRetrievalStrategy, SecurityIdentityRetrievalStrategyInterface $sidRetrievalStrategy, PermissionMapInterface $permissionMap, LoggerInterface $logger = null, $allowIfObjectIdentityUnavailable = true) { diff --git a/src/Symfony/Component/Security/Acl/Voter/FieldVote.php b/src/Symfony/Component/Security/Acl/Voter/FieldVote.php index 7b7f39a0eb78f..01f0c20faf39d 100644 --- a/src/Symfony/Component/Security/Acl/Voter/FieldVote.php +++ b/src/Symfony/Component/Security/Acl/Voter/FieldVote.php @@ -19,8 +19,8 @@ */ class FieldVote { - protected $domainObject; - protected $field; + private $domainObject; + private $field; public function __construct($domainObject, $field) { diff --git a/src/Symfony/Component/Security/Core/Authentication/AuthenticationProviderManager.php b/src/Symfony/Component/Security/Core/Authentication/AuthenticationProviderManager.php index ac1e36d73a361..1d85e87c6798d 100644 --- a/src/Symfony/Component/Security/Core/Authentication/AuthenticationProviderManager.php +++ b/src/Symfony/Component/Security/Core/Authentication/AuthenticationProviderManager.php @@ -25,8 +25,8 @@ */ class AuthenticationProviderManager implements AuthenticationManagerInterface { - protected $providers; - protected $eraseCredentials; + private $providers; + private $eraseCredentials; /** * Constructor. @@ -34,9 +34,13 @@ class AuthenticationProviderManager implements AuthenticationManagerInterface * @param AuthenticationProviderInterface[] $providers An array of AuthenticationProviderInterface instances * @param Boolean $eraseCredentials Whether to erase credentials after authentication or not */ - public function __construct(array $providers = array(), $eraseCredentials = true) + public function __construct(array $providers, $eraseCredentials = true) { - $this->setProviders($providers); + if (!$providers) { + throw new \InvalidArgumentException('You must at least add one authentication provider.'); + } + + $this->providers = $providers; $this->eraseCredentials = (Boolean) $eraseCredentials; } @@ -45,10 +49,6 @@ public function __construct(array $providers = array(), $eraseCredentials = true */ public function authenticate(TokenInterface $token) { - if (!count($this->providers)) { - throw new \LogicException('You must add at least one provider.'); - } - $lastException = null; $result = null; @@ -84,37 +84,4 @@ public function authenticate(TokenInterface $token) throw $lastException; } - - /** - * Returns the list of current providers. - * - * @return AuthenticationProviderInterface[] An array of AuthenticationProviderInterface instances - */ - public function all() - { - return $this->providers; - } - - /** - * Sets the providers instances. - * - * @param AuthenticationProviderInterface[] $providers An array of AuthenticationProviderInterface instances - */ - public function setProviders(array $providers) - { - $this->providers = array(); - foreach ($providers as $provider) { - $this->add($provider); - } - } - - /** - * Adds a provider. - * - * @param AuthenticationProviderInterface $provider A AuthenticationProviderInterface instance - */ - public function add(AuthenticationProviderInterface $provider) - { - $this->providers[] = $provider; - } } diff --git a/src/Symfony/Component/Security/Core/Authentication/AuthenticationTrustResolver.php b/src/Symfony/Component/Security/Core/Authentication/AuthenticationTrustResolver.php index f2e00cc1f3f1c..8ca28fbd18b8d 100644 --- a/src/Symfony/Component/Security/Core/Authentication/AuthenticationTrustResolver.php +++ b/src/Symfony/Component/Security/Core/Authentication/AuthenticationTrustResolver.php @@ -20,8 +20,8 @@ */ class AuthenticationTrustResolver implements AuthenticationTrustResolverInterface { - protected $anonymousClass; - protected $rememberMeClass; + private $anonymousClass; + private $rememberMeClass; /** * Constructor diff --git a/src/Symfony/Component/Security/Core/Authentication/Provider/AnonymousAuthenticationProvider.php b/src/Symfony/Component/Security/Core/Authentication/Provider/AnonymousAuthenticationProvider.php index ad1ad60106cab..c48a27efcd280 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Provider/AnonymousAuthenticationProvider.php +++ b/src/Symfony/Component/Security/Core/Authentication/Provider/AnonymousAuthenticationProvider.php @@ -22,7 +22,7 @@ */ class AnonymousAuthenticationProvider implements AuthenticationProviderInterface { - protected $key; + private $key; /** * Constructor. diff --git a/src/Symfony/Component/Security/Core/Authentication/Provider/DaoAuthenticationProvider.php b/src/Symfony/Component/Security/Core/Authentication/Provider/DaoAuthenticationProvider.php index ce0d220db1481..21bec8292a9c0 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Provider/DaoAuthenticationProvider.php +++ b/src/Symfony/Component/Security/Core/Authentication/Provider/DaoAuthenticationProvider.php @@ -14,8 +14,8 @@ use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface; use Symfony\Component\Security\Core\User\UserProviderInterface; -use Symfony\Component\Security\Core\User\AccountCheckerInterface; -use Symfony\Component\Security\Core\User\AccountInterface; +use Symfony\Component\Security\Core\User\UserCheckerInterface; +use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\Exception\AuthenticationServiceException; use Symfony\Component\Security\Core\Exception\BadCredentialsException; @@ -29,19 +29,19 @@ */ class DaoAuthenticationProvider extends UserAuthenticationProvider { - protected $encoderFactory; - protected $userProvider; + private $encoderFactory; + private $userProvider; /** * Constructor. * * @param UserProviderInterface $userProvider A UserProviderInterface instance - * @param AccountCheckerInterface $accountChecker An AccountCheckerInterface instance + * @param UserCheckerInterface $userChecker An UserCheckerInterface instance * @param EncoderFactoryInterface $encoderFactory A EncoderFactoryInterface instance */ - public function __construct(UserProviderInterface $userProvider, AccountCheckerInterface $accountChecker, $providerKey, EncoderFactoryInterface $encoderFactory, $hideUserNotFoundExceptions = true) + public function __construct(UserProviderInterface $userProvider, UserCheckerInterface $userChecker, $providerKey, EncoderFactoryInterface $encoderFactory, $hideUserNotFoundExceptions = true) { - parent::__construct($accountChecker, $providerKey, $hideUserNotFoundExceptions); + parent::__construct($userChecker, $providerKey, $hideUserNotFoundExceptions); $this->encoderFactory = $encoderFactory; $this->userProvider = $userProvider; @@ -50,19 +50,19 @@ public function __construct(UserProviderInterface $userProvider, AccountCheckerI /** * {@inheritdoc} */ - protected function checkAuthentication(AccountInterface $account, UsernamePasswordToken $token) + protected function checkAuthentication(UserInterface $user, UsernamePasswordToken $token) { - $user = $token->getUser(); - if ($user instanceof AccountInterface) { - if ($account->getPassword() !== $user->getPassword()) { + $currentUser = $token->getUser(); + if ($currentUser instanceof UserInterface) { + if ($currentUser->getPassword() !== $user->getPassword()) { throw new BadCredentialsException('The credentials were changed from another session.'); } } else { - if (!$presentedPassword = (string) $token->getCredentials()) { + if (!$presentedPassword = $token->getCredentials()) { throw new BadCredentialsException('Bad credentials'); } - if (!$this->encoderFactory->getEncoder($account)->isPasswordValid($account->getPassword(), $presentedPassword, $account->getSalt())) { + if (!$this->encoderFactory->getEncoder($user)->isPasswordValid($user->getPassword(), $presentedPassword, $user->getSalt())) { throw new BadCredentialsException('Bad credentials'); } } @@ -74,15 +74,15 @@ protected function checkAuthentication(AccountInterface $account, UsernamePasswo protected function retrieveUser($username, UsernamePasswordToken $token) { $user = $token->getUser(); - if ($user instanceof AccountInterface) { + if ($user instanceof UserInterface) { return $user; } try { $user = $this->userProvider->loadUserByUsername($username); - if (!$user instanceof AccountInterface) { - throw new AuthenticationServiceException('The user provider must return an AccountInterface object.'); + if (!$user instanceof UserInterface) { + throw new AuthenticationServiceException('The user provider must return an UserInterface object.'); } return $user; diff --git a/src/Symfony/Component/Security/Core/Authentication/Provider/PreAuthenticatedAuthenticationProvider.php b/src/Symfony/Component/Security/Core/Authentication/Provider/PreAuthenticatedAuthenticationProvider.php index cca52fca562d8..bf2df864aee2a 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Provider/PreAuthenticatedAuthenticationProvider.php +++ b/src/Symfony/Component/Security/Core/Authentication/Provider/PreAuthenticatedAuthenticationProvider.php @@ -11,9 +11,9 @@ namespace Symfony\Component\Security\Core\Authentication\Provider; -use Symfony\Component\Security\Core\User\AccountInterface; +use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\UserProviderInterface; -use Symfony\Component\Security\Core\User\AccountCheckerInterface; +use Symfony\Component\Security\Core\User\UserCheckerInterface; use Symfony\Component\Security\Core\Exception\BadCredentialsException; use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; @@ -30,20 +30,20 @@ */ class PreAuthenticatedAuthenticationProvider implements AuthenticationProviderInterface { - protected $userProvider; - protected $accountChecker; - protected $providerKey; + private $userProvider; + private $userChecker; + private $providerKey; /** * Constructor. * * @param UserProviderInterface $userProvider A UserProviderInterface instance - * @param AccountCheckerInterface $accountChecker An AccountCheckerInterface instance + * @param UserCheckerInterface $userChecker An UserCheckerInterface instance */ - public function __construct(UserProviderInterface $userProvider, AccountCheckerInterface $accountChecker, $providerKey) + public function __construct(UserProviderInterface $userProvider, UserCheckerInterface $userChecker, $providerKey) { $this->userProvider = $userProvider; - $this->accountChecker = $accountChecker; + $this->userChecker = $userChecker; $this->providerKey = $providerKey; } @@ -66,7 +66,7 @@ public function authenticate(TokenInterface $token) */ $user = $this->userProvider->loadUserByUsername($user); - $this->accountChecker->checkPostAuth($user); + $this->userChecker->checkPostAuth($user); $authenticatedToken = new PreAuthenticatedToken($user, $token->getCredentials(), $this->providerKey, $user->getRoles()); $authenticatedToken->setAttributes($token->getAttributes()); diff --git a/src/Symfony/Component/Security/Core/Authentication/Provider/RememberMeAuthenticationProvider.php b/src/Symfony/Component/Security/Core/Authentication/Provider/RememberMeAuthenticationProvider.php index 95ee58822c1ad..940288be5fee0 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Provider/RememberMeAuthenticationProvider.php +++ b/src/Symfony/Component/Security/Core/Authentication/Provider/RememberMeAuthenticationProvider.php @@ -1,21 +1,21 @@ accountChecker = $accountChecker; + $this->userChecker = $userChecker; $this->key = $key; $this->providerKey = $providerKey; } @@ -31,11 +31,12 @@ public function authenticate(TokenInterface $token) } $user = $token->getUser(); - $this->accountChecker->checkPreAuth($user); - $this->accountChecker->checkPostAuth($user); - $token->setAuthenticated(true); + $this->userChecker->checkPostAuth($user); - return $token; + $authenticatedToken = new RememberMeToken($user, $this->providerKey, $this->key); + $authenticatedToken->setAttributes($token->getAttributes()); + + return $authenticatedToken; } public function supports(TokenInterface $token) diff --git a/src/Symfony/Component/Security/Core/Authentication/Provider/UserAuthenticationProvider.php b/src/Symfony/Component/Security/Core/Authentication/Provider/UserAuthenticationProvider.php index 14a6fdfb17609..7b6079d83dc20 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Provider/UserAuthenticationProvider.php +++ b/src/Symfony/Component/Security/Core/Authentication/Provider/UserAuthenticationProvider.php @@ -11,8 +11,8 @@ namespace Symfony\Component\Security\Core\Authentication\Provider; -use Symfony\Component\Security\Core\User\AccountInterface; -use Symfony\Component\Security\Core\User\AccountCheckerInterface; +use Symfony\Component\Security\Core\User\UserInterface; +use Symfony\Component\Security\Core\User\UserCheckerInterface; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Core\Exception\BadCredentialsException; @@ -27,23 +27,23 @@ */ abstract class UserAuthenticationProvider implements AuthenticationProviderInterface { - protected $hideUserNotFoundExceptions; - protected $accountChecker; - protected $providerKey; + private $hideUserNotFoundExceptions; + private $userChecker; + private $providerKey; /** * Constructor. * - * @param AccountCheckerInterface $accountChecker An AccountCheckerInterface interface + * @param UserCheckerInterface $userChecker An UserCheckerInterface interface * @param Boolean $hideUserNotFoundExceptions Whether to hide user not found exception or not */ - public function __construct(AccountCheckerInterface $accountChecker, $providerKey, $hideUserNotFoundExceptions = true) + public function __construct(UserCheckerInterface $userChecker, $providerKey, $hideUserNotFoundExceptions = true) { if (empty($providerKey)) { throw new \InvalidArgumentException('$providerKey must not be empty.'); } - $this->accountChecker = $accountChecker; + $this->userChecker = $userChecker; $this->providerKey = $providerKey; $this->hideUserNotFoundExceptions = $hideUserNotFoundExceptions; } @@ -57,18 +57,21 @@ public function authenticate(TokenInterface $token) return null; } - $username = null === $token->getUser() ? 'NONE_PROVIDED' : (string) $token; + $username = $token->getUsername(); + if (empty($username)) { + $username = 'NONE_PROVIDED'; + } try { $user = $this->retrieveUser($username, $token); - if (!$user instanceof AccountInterface) { - throw new AuthenticationServiceException('retrieveUser() must return an AccountInterface.'); + if (!$user instanceof UserInterface) { + throw new AuthenticationServiceException('retrieveUser() must return an UserInterface.'); } - $this->accountChecker->checkPreAuth($user); + $this->userChecker->checkPreAuth($user); $this->checkAuthentication($user, $token); - $this->accountChecker->checkPostAuth($user); + $this->userChecker->checkPostAuth($user); $authenticatedToken = new UsernamePasswordToken($user, $token->getCredentials(), $this->providerKey, $user->getRoles()); $authenticatedToken->setAttributes($token->getAttributes()); @@ -107,10 +110,10 @@ abstract protected function retrieveUser($username, UsernamePasswordToken $token * Does additional checks on the user and token (like validating the * credentials). * - * @param AccountInterface $account The retrieved AccountInterface instance + * @param UserInterface $user The retrieved UserInterface instance * @param UsernamePasswordToken $token The UsernamePasswordToken token to be authenticated * * @throws AuthenticationException if the credentials could not be validated */ - abstract protected function checkAuthentication(AccountInterface $account, UsernamePasswordToken $token); + abstract protected function checkAuthentication(UserInterface $user, UsernamePasswordToken $token); } diff --git a/src/Symfony/Component/Security/Core/Authentication/RememberMe/InMemoryTokenProvider.php b/src/Symfony/Component/Security/Core/Authentication/RememberMe/InMemoryTokenProvider.php index 80c10d1fa3480..c432b0eced800 100644 --- a/src/Symfony/Component/Security/Core/Authentication/RememberMe/InMemoryTokenProvider.php +++ b/src/Symfony/Component/Security/Core/Authentication/RememberMe/InMemoryTokenProvider.php @@ -11,7 +11,7 @@ */ class InMemoryTokenProvider implements TokenProviderInterface { - protected $tokens = array(); + private $tokens = array(); public function loadTokenBySeries($series) { diff --git a/src/Symfony/Component/Security/Core/Authentication/Token/Token.php b/src/Symfony/Component/Security/Core/Authentication/Token/AbstractToken.php similarity index 57% rename from src/Symfony/Component/Security/Core/Authentication/Token/Token.php rename to src/Symfony/Component/Security/Core/Authentication/Token/AbstractToken.php index ac0879f3dd91f..210e46d06cbe1 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Token/Token.php +++ b/src/Symfony/Component/Security/Core/Authentication/Token/AbstractToken.php @@ -13,7 +13,7 @@ use Symfony\Component\Security\Core\Role\RoleInterface; use Symfony\Component\Security\Core\Role\Role; -use Symfony\Component\Security\Core\User\AccountInterface; +use Symfony\Component\Security\Core\User\UserInterface; /** * Base class for Token instances. @@ -21,15 +21,12 @@ * @author Fabien Potencier * @author Johannes M. Schmitt */ -abstract class Token implements TokenInterface +abstract class AbstractToken implements TokenInterface { - protected $roles; - protected $authenticated; - protected $user; - protected $credentials; - protected $immutable; - protected $providerKey; - protected $attributes; + private $user; + private $roles; + private $authenticated; + private $attributes; /** * Constructor. @@ -38,156 +35,97 @@ abstract class Token implements TokenInterface */ public function __construct(array $roles = array()) { - $this->setRoles($roles); $this->authenticated = false; - $this->immutable = false; $this->attributes = array(); - } - - /** - * Adds a Role to the token. - * - * @param RoleInterface $role A RoleInterface instance - */ - public function addRole(RoleInterface $role) - { - if ($this->immutable) { - throw new \LogicException('This token is considered immutable.'); - } - - $this->roles[] = $role; - } - /** - * {@inheritdoc} - */ - public function getRoles() - { - return $this->roles; - } - - /** - * {@inheritDoc} - */ - public function setRoles(array $roles) - { $this->roles = array(); - foreach ($roles as $role) { if (is_string($role)) { $role = new Role($role); + } else if (!$role instanceof RoleInterface) { + throw new \InvalidArgumentException(sprintf('$roles must be an array of strings, or RoleInterface instances, but got %s.', gettype($role))); } - $this->addRole($role); - } - } - - /** - * {@inheritdoc} - */ - public function __toString() - { - if ($this->user instanceof AccountInterface) { - return $this->user->getUsername(); + $this->roles[] = $role; } - - return (string) $this->user; } /** * {@inheritdoc} */ - public function isAuthenticated() + public function getRoles() { - return $this->authenticated; + return $this->roles; } /** * {@inheritdoc} */ - public function setAuthenticated($authenticated) + public function getUsername() { - if ($this->immutable) { - throw new \LogicException('This token is considered immutable.'); + if ($this->user instanceof UserInterface) { + return $this->user->getUsername(); } - $this->authenticated = (Boolean) $authenticated; - } - - /** - * {@inheritdoc} - */ - public function getCredentials() - { - return $this->credentials; + return (string) $this->user; } - /** - * {@inheritdoc} - */ public function getUser() { return $this->user; } - /** - * {@inheritDoc} - */ public function setUser($user) { - if ($this->immutable) { - throw new \LogicException('This token is considered immutable.'); + if (!($user instanceof UserInterface || (is_object($user) && method_exists($user, '__toString')) || is_string($user))) { + throw new \InvalidArgumentException('$user must be an instanceof of UserInterface, an object implementing a __toString method, or a primitive string.'); } - if (!is_string($user) && !is_object($user)) { - throw new \InvalidArgumentException('$user must be an object, or a primitive string.'); - } else if (is_object($user) && !$user instanceof AccountInterface && !method_exists($user, '__toString')) { - throw new \InvalidArgumentException('If $user is an object, it must implement __toString().'); - } - - $this->user = $user; - } - - /** - * {@inheritdoc} - */ - public function eraseCredentials() - { - if ($this->immutable) { - throw new \LogicException('This token is considered immutable.'); + if (null === $this->user) { + $changed = false; + } else if ($this->user instanceof UserInterface) { + if (!$user instanceof UserInterface) { + $changed = true; + } else { + $changed = !$this->user->equals($user); + } + } else if ($user instanceof UserInterface) { + $changed = true; + } else { + $changed = (string) $this->user !== (string) $user; } - if ($this->getCredentials() instanceof AccountInterface) { - $this->getCredentials()->eraseCredentials(); + if ($changed) { + $this->setAuthenticated(false); } - if ($this->getUser() instanceof AccountInterface) { - $this->getUser()->eraseCredentials(); - } + $this->user = $user; } /** * {@inheritdoc} */ - public function isImmutable() + public function isAuthenticated() { - return $this->immutable; + return $this->authenticated; } /** * {@inheritdoc} */ - public function setImmutable() + public function setAuthenticated($authenticated) { - $this->immutable = true; + $this->authenticated = (Boolean) $authenticated; } /** * {@inheritdoc} */ - public function getProviderKey() + public function eraseCredentials() { - return $this->providerKey; + if ($this->getUser() instanceof UserInterface) { + $this->getUser()->eraseCredentials(); + } } /** @@ -195,7 +133,7 @@ public function getProviderKey() */ public function serialize() { - return serialize(array($this->user, $this->credentials, $this->authenticated, $this->roles, $this->immutable, $this->providerKey, $this->attributes)); + return serialize(array($this->user, $this->authenticated, $this->roles, $this->attributes)); } /** @@ -203,7 +141,7 @@ public function serialize() */ public function unserialize($serialized) { - list($this->user, $this->credentials, $this->authenticated, $this->roles, $this->immutable, $this->providerKey, $this->attributes) = unserialize($serialized); + list($this->user, $this->authenticated, $this->roles, $this->attributes) = unserialize($serialized); } /** diff --git a/src/Symfony/Component/Security/Core/Authentication/Token/AnonymousToken.php b/src/Symfony/Component/Security/Core/Authentication/Token/AnonymousToken.php index a22460fdbf20f..92d95de554037 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Token/AnonymousToken.php +++ b/src/Symfony/Component/Security/Core/Authentication/Token/AnonymousToken.php @@ -16,10 +16,11 @@ * * @author Fabien Potencier */ -class AnonymousToken extends Token +use Symfony\Component\Security\Core\User\UserInterface; + +class AnonymousToken extends AbstractToken { - protected $user; - protected $key; + private $key; /** * Constructor. @@ -33,9 +34,8 @@ public function __construct($key, $user, array $roles = array()) parent::__construct($roles); $this->key = $key; - $this->user = $user; - - parent::setAuthenticated(true); + $this->setUser($user); + $this->setAuthenticated(true); } /** @@ -55,4 +55,21 @@ public function getKey() { return $this->key; } + + /** + * {@inheritDoc} + */ + public function serialize() + { + return serialize(array($this->key, parent::serialize())); + } + + /** + * {@inheritDoc} + */ + public function unserialize($str) + { + list($this->key, $parentStr) = unserialize($str); + parent::unserialize($parentStr); + } } diff --git a/src/Symfony/Component/Security/Core/Authentication/Token/PreAuthenticatedToken.php b/src/Symfony/Component/Security/Core/Authentication/Token/PreAuthenticatedToken.php index 0db56bde4042f..ff0572fbf60cd 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Token/PreAuthenticatedToken.php +++ b/src/Symfony/Component/Security/Core/Authentication/Token/PreAuthenticatedToken.php @@ -16,21 +16,39 @@ * * @author Fabien Potencier */ -class PreAuthenticatedToken extends Token +class PreAuthenticatedToken extends AbstractToken { + private $credentials; + private $providerKey; + /** * Constructor. */ - public function __construct($user, $credentials, $providerKey, array $roles = null) + public function __construct($user, $credentials, $providerKey, array $roles = array()) { - parent::__construct(null === $roles ? array() : $roles); - if (null !== $roles) { - $this->setAuthenticated(true); + parent::__construct($roles); + + if (empty($providerKey)) { + throw new \InvalidArgumentException('$providerKey must not be empty.'); } - $this->user = $user; + $this->setUser($user); $this->credentials = $credentials; $this->providerKey = $providerKey; + + if ($roles) { + $this->setAuthenticated(true); + } + } + + public function getProviderKey() + { + return $this->providerKey; + } + + public function getCredentials() + { + return $this->credentials; } /** @@ -42,4 +60,15 @@ public function eraseCredentials() $this->credentials = null; } + + public function serialize() + { + return serialize(array($this->credentials, $this->providerKey, parent::serialize())); + } + + public function unserialize($str) + { + list($this->credentials, $this->providerKey, $parentStr) = unserialize($str); + parent::unserialize($parentStr); + } } diff --git a/src/Symfony/Component/Security/Core/Authentication/Token/RememberMeToken.php b/src/Symfony/Component/Security/Core/Authentication/Token/RememberMeToken.php index ce1ed5df01c94..038198a4a5a79 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Token/RememberMeToken.php +++ b/src/Symfony/Component/Security/Core/Authentication/Token/RememberMeToken.php @@ -12,44 +12,57 @@ namespace Symfony\Component\Security\Core\Authentication\Token; use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentTokenInterface; -use Symfony\Component\Security\Core\User\AccountInterface; +use Symfony\Component\Security\Core\User\UserInterface; /** - * Base class for "Remember Me" tokens + * Authentication Token for "Remember-Me". * * @author Johannes M. Schmitt */ -class RememberMeToken extends Token +class RememberMeToken extends AbstractToken { - protected $key; - - /** - * The persistent token which resulted in this authentication token. - * - * @var PersistentTokenInterface - */ - protected $persistentToken; + private $key; + private $providerKey; + private $persistentToken; /** * Constructor. * - * @param string $username + * @param UserInterface $user + * @param string $providerKey * @param string $key */ - public function __construct(AccountInterface $user, $providerKey, $key) { + public function __construct(UserInterface $user, $providerKey, $key, PersistentTokenInterface $persistentToken = null) { parent::__construct($user->getRoles()); if (empty($key)) { throw new \InvalidArgumentException('$key must not be empty.'); } + if (empty($providerKey)) { throw new \InvalidArgumentException('$providerKey must not be empty.'); } - $this->setUser($user); $this->providerKey = $providerKey; $this->key = $key; - $this->setAuthenticated(true); + $this->persistentToken = $persistentToken; + + $this->setUser($user); + parent::setAuthenticated(true); + } + + public function setAuthenticated($authenticated) + { + if ($authenticated) { + throw new \RuntimeException('You cannot set this token to authenticated after creation.'); + } + + parent::setAuthenticated(false); + } + + public function getProviderKey() + { + return $this->providerKey; } public function getKey() @@ -62,18 +75,21 @@ public function getPersistentToken() return $this->persistentToken; } - public function setPersistentToken(PersistentTokenInterface $persistentToken) + public function getCredentials() { - $this->persistentToken = $persistentToken; + return ''; } - /** * {@inheritdoc} */ public function serialize() { - return serialize(array($this->user, $this->credentials, $this->authenticated, $this->roles, $this->immutable, $this->providerKey, $this->attributes, $this->key)); + return serialize(array( + $this->key, + $this->providerKey, + parent::serialize(), + )); } /** @@ -81,6 +97,7 @@ public function serialize() */ public function unserialize($serialized) { - list($this->user, $this->credentials, $this->authenticated, $this->roles, $this->immutable, $this->providerKey, $this->attributes, $this->key) = unserialize($serialized); + list($this->key, $this->providerKey, $parentStr) = unserialize($serialized); + parent::unserialize($parentStr); } } \ No newline at end of file diff --git a/src/Symfony/Component/Security/Core/Authentication/Token/TokenInterface.php b/src/Symfony/Component/Security/Core/Authentication/Token/TokenInterface.php index f3947dd98371e..add550fadef53 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Token/TokenInterface.php +++ b/src/Symfony/Component/Security/Core/Authentication/Token/TokenInterface.php @@ -11,22 +11,16 @@ namespace Symfony\Component\Security\Core\Authentication\Token; -use Symfony\Component\Security\Core\User\AccountInterface; +use Symfony\Component\Security\Core\User\UserInterface; /** * TokenInterface is the interface for the user authentication information. * * @author Fabien Potencier + * @author Johannes M. Schmitt */ interface TokenInterface extends \Serializable { - /** - * Returns a string representation of the token. - * - * @return string A string representation - */ - function __toString(); - /** * Returns the user roles. * @@ -34,14 +28,6 @@ function __toString(); */ function getRoles(); - /** - * Sets the user's roles - * - * @param array $roles - * @return void - */ - function setRoles(array $roles); - /** * Returns the user credentials. * @@ -58,13 +44,19 @@ function getCredentials(); function getUser(); /** - * Sets the user. + * Sets a user. * - * @param mixed $user can either be an object which implements __toString(), or - * only a primitive string + * @param mixed $user */ function setUser($user); + /** + * Returns the username. + * + * @return string + */ + function getUsername(); + /** * Checks if the user is authenticated or not. * @@ -79,22 +71,6 @@ function isAuthenticated(); */ function setAuthenticated($isAuthenticated); - /** - * Whether this token is considered immutable - * - * @return Boolean - */ - function isImmutable(); - - /** - * Marks this token as immutable. This change cannot be reversed. - * - * You'll need to create a new token if you want a mutable token again. - * - * @return void - */ - function setImmutable(); - /** * Removes sensitive information from the token. */ diff --git a/src/Symfony/Component/Security/Core/Authentication/Token/UsernamePasswordToken.php b/src/Symfony/Component/Security/Core/Authentication/Token/UsernamePasswordToken.php index 58b2b5bff5c36..67311db3e40af 100644 --- a/src/Symfony/Component/Security/Core/Authentication/Token/UsernamePasswordToken.php +++ b/src/Symfony/Component/Security/Core/Authentication/Token/UsernamePasswordToken.php @@ -16,8 +16,11 @@ * * @author Fabien Potencier */ -class UsernamePasswordToken extends Token +class UsernamePasswordToken extends AbstractToken { + private $credentials; + private $providerKey; + /** * Constructor. * @@ -28,11 +31,15 @@ public function __construct($user, $credentials, $providerKey, array $roles = ar { parent::__construct($roles); + if (empty($providerKey)) { + throw new \InvalidArgumentException('$providerKey must not be empty.'); + } + $this->setUser($user); $this->credentials = $credentials; $this->providerKey = $providerKey; - parent::setAuthenticated((Boolean) count($roles)); + parent::setAuthenticated(count($roles) > 0); } /** @@ -47,6 +54,16 @@ public function setAuthenticated($isAuthenticated) parent::setAuthenticated(false); } + public function getCredentials() + { + return $this->credentials; + } + + public function getProviderKey() + { + return $this->providerKey; + } + /** * {@inheritdoc} */ @@ -56,4 +73,15 @@ public function eraseCredentials() $this->credentials = null; } + + public function serialize() + { + return serialize(array($this->credentials, $this->providerKey, parent::serialize())); + } + + public function unserialize($str) + { + list($this->credentials, $this->providerKey, $parentStr) = unserialize($str); + parent::unserialize($parentStr); + } } diff --git a/src/Symfony/Component/Security/Core/Authorization/AccessDecisionManager.php b/src/Symfony/Component/Security/Core/Authorization/AccessDecisionManager.php index 7ae53781262d2..c1b643e64392f 100644 --- a/src/Symfony/Component/Security/Core/Authorization/AccessDecisionManager.php +++ b/src/Symfony/Component/Security/Core/Authorization/AccessDecisionManager.php @@ -22,10 +22,10 @@ */ class AccessDecisionManager implements AccessDecisionManagerInterface { - protected $voters; - protected $strategy; - protected $allowIfAllAbstainDecisions; - protected $allowIfEqualGrantedDeniedDecisions; + private $voters; + private $strategy; + private $allowIfAllAbstainDecisions; + private $allowIfEqualGrantedDeniedDecisions; /** * Constructor. @@ -34,8 +34,12 @@ class AccessDecisionManager implements AccessDecisionManagerInterface * @param string $strategy The vote strategy * @param Boolean $allowIfAllAbstainDecisions Whether to grant access if all voters abstained or not */ - public function __construct(array $voters = array(), $strategy = 'affirmative', $allowIfAllAbstainDecisions = false, $allowIfEqualGrantedDeniedDecisions = true) + public function __construct(array $voters, $strategy = 'affirmative', $allowIfAllAbstainDecisions = false, $allowIfEqualGrantedDeniedDecisions = true) { + if (!$voters) { + throw new \InvalidArgumentException('You must at least add one voter.'); + } + $this->voters = $voters; $this->strategy = 'decide'.ucfirst($strategy); $this->allowIfAllAbstainDecisions = (Boolean) $allowIfAllAbstainDecisions; @@ -50,43 +54,6 @@ public function decide(TokenInterface $token, array $attributes, $object = null) return $this->{$this->strategy}($token, $attributes, $object); } - /** - * Returns all voters. - * - * @return VoterInterface[] $voters An array of VoterInterface instances - */ - public function getVoters() - { - return $this->voters; - } - - /** - * Sets voters. - * - * @param VoterInterface[] $voters An array of VoterInterface instances - */ - public function setVoters(array $voters) - { - if (!count($voters)) { - throw new \LogicException('You must have at least one voter.'); - } - - $this->voters = array(); - foreach ($voters as $voter) { - $this->addVoter($voter); - } - } - - /** - * Adds a voter. - * - * @param VoterInterface $voter A VoterInterface instance - */ - public function addVoter(VoterInterface $voter) - { - $this->voters[] = $voter; - } - /** * {@inheritdoc} */ @@ -121,7 +88,7 @@ public function supportsClass($class) * If all voters abstained from voting, the decision will be based on the * allowIfAllAbstainDecisions property value (defaults to false). */ - protected function decideAffirmative(TokenInterface $token, array $attributes, $object = null) + private function decideAffirmative(TokenInterface $token, array $attributes, $object = null) { $deny = 0; foreach ($this->voters as $voter) { @@ -161,7 +128,7 @@ protected function decideAffirmative(TokenInterface $token, array $attributes, $ * If all voters abstained from voting, the decision will be based on the * allowIfAllAbstainDecisions property value (defaults to false). */ - protected function decideConsensus(TokenInterface $token, array $attributes, $object = null) + private function decideConsensus(TokenInterface $token, array $attributes, $object = null) { $grant = 0; $deny = 0; @@ -208,7 +175,7 @@ protected function decideConsensus(TokenInterface $token, array $attributes, $ob * If all voters abstained from voting, the decision will be based on the * allowIfAllAbstainDecisions property value (defaults to false). */ - protected function decideUnanimous(TokenInterface $token, array $attributes, $object = null) + private function decideUnanimous(TokenInterface $token, array $attributes, $object = null) { $grant = 0; foreach ($attributes as $attribute) { diff --git a/src/Symfony/Component/Security/Core/Authorization/Voter/AuthenticatedVoter.php b/src/Symfony/Component/Security/Core/Authorization/Voter/AuthenticatedVoter.php index 3b5ca97aba9b6..d750e3387817d 100644 --- a/src/Symfony/Component/Security/Core/Authorization/Voter/AuthenticatedVoter.php +++ b/src/Symfony/Component/Security/Core/Authorization/Voter/AuthenticatedVoter.php @@ -29,7 +29,7 @@ class AuthenticatedVoter implements VoterInterface const IS_AUTHENTICATED_REMEMBERED = 'IS_AUTHENTICATED_REMEMBERED'; const IS_AUTHENTICATED_ANONYMOUSLY = 'IS_AUTHENTICATED_ANONYMOUSLY'; - protected $authenticationTrustResolver; + private $authenticationTrustResolver; /** * Constructor. diff --git a/src/Symfony/Component/Security/Core/Authorization/Voter/RoleHierarchyVoter.php b/src/Symfony/Component/Security/Core/Authorization/Voter/RoleHierarchyVoter.php index 5c1e11eaea35d..c8f9b7ec8e8a9 100644 --- a/src/Symfony/Component/Security/Core/Authorization/Voter/RoleHierarchyVoter.php +++ b/src/Symfony/Component/Security/Core/Authorization/Voter/RoleHierarchyVoter.php @@ -22,7 +22,7 @@ */ class RoleHierarchyVoter extends RoleVoter { - protected $roleHierarchy; + private $roleHierarchy; public function __construct(RoleHierarchyInterface $roleHierarchy, $prefix = 'ROLE_') { diff --git a/src/Symfony/Component/Security/Core/Authorization/Voter/RoleVoter.php b/src/Symfony/Component/Security/Core/Authorization/Voter/RoleVoter.php index 3a1aa2de1f1ba..722675d29be0c 100644 --- a/src/Symfony/Component/Security/Core/Authorization/Voter/RoleVoter.php +++ b/src/Symfony/Component/Security/Core/Authorization/Voter/RoleVoter.php @@ -20,7 +20,7 @@ */ class RoleVoter implements VoterInterface { - protected $prefix; + private $prefix; /** * Constructor. diff --git a/src/Symfony/Component/Security/Core/Encoder/EncoderFactory.php b/src/Symfony/Component/Security/Core/Encoder/EncoderFactory.php index 80a7a611a7afe..d6441d98fc436 100644 --- a/src/Symfony/Component/Security/Core/Encoder/EncoderFactory.php +++ b/src/Symfony/Component/Security/Core/Encoder/EncoderFactory.php @@ -11,7 +11,7 @@ namespace Symfony\Component\Security\Core\Encoder; -use Symfony\Component\Security\Core\User\AccountInterface; +use Symfony\Component\Security\Core\User\UserInterface; /** * A generic encoder factory implementation @@ -20,7 +20,7 @@ */ class EncoderFactory implements EncoderFactoryInterface { - protected $encoders; + private $encoders; public function __construct(array $encoders) { @@ -30,10 +30,10 @@ public function __construct(array $encoders) /** * {@inheritDoc} */ - public function getEncoder(AccountInterface $account) + public function getEncoder(UserInterface $user) { foreach ($this->encoders as $class => $encoder) { - if (!$account instanceof $class) { + if (!$user instanceof $class) { continue; } @@ -44,7 +44,7 @@ public function getEncoder(AccountInterface $account) return $this->encoders[$class]; } - throw new \RuntimeException(sprintf('No encoder has been configured for account "%s".', get_class($account))); + throw new \RuntimeException(sprintf('No encoder has been configured for account "%s".', get_class($user))); } /** @@ -53,7 +53,7 @@ public function getEncoder(AccountInterface $account) * @param array $config * @return PasswordEncoderInterface */ - protected function createEncoder(array $config) + private function createEncoder(array $config) { if (!isset($config['class'])) { throw new \InvalidArgumentException(sprintf('"class" must be set in %s.', json_encode($config))); diff --git a/src/Symfony/Component/Security/Core/Encoder/EncoderFactoryInterface.php b/src/Symfony/Component/Security/Core/Encoder/EncoderFactoryInterface.php index a4b7d3bcb7197..62cc9aa657577 100644 --- a/src/Symfony/Component/Security/Core/Encoder/EncoderFactoryInterface.php +++ b/src/Symfony/Component/Security/Core/Encoder/EncoderFactoryInterface.php @@ -11,7 +11,7 @@ namespace Symfony\Component\Security\Core\Encoder; -use Symfony\Component\Security\Core\User\AccountInterface; +use Symfony\Component\Security\Core\User\UserInterface; /** * EncoderFactoryInterface to support different encoders for different accounts. @@ -23,8 +23,8 @@ interface EncoderFactoryInterface /** * Returns the password encoder to use for the given account * - * @param AccountInterface $account + * @param UserInterface $user * @return PasswordEncoderInterface never null */ - function getEncoder(AccountInterface $account); + function getEncoder(UserInterface $user); } \ No newline at end of file diff --git a/src/Symfony/Component/Security/Core/Encoder/MessageDigestPasswordEncoder.php b/src/Symfony/Component/Security/Core/Encoder/MessageDigestPasswordEncoder.php index b69cf6e22be86..a5b2c811ff708 100644 --- a/src/Symfony/Component/Security/Core/Encoder/MessageDigestPasswordEncoder.php +++ b/src/Symfony/Component/Security/Core/Encoder/MessageDigestPasswordEncoder.php @@ -18,8 +18,8 @@ */ class MessageDigestPasswordEncoder extends BasePasswordEncoder { - protected $algorithm; - protected $encodeHashAsBase64; + private $algorithm; + private $encodeHashAsBase64; /** * Constructor. diff --git a/src/Symfony/Component/Security/Core/Encoder/PlaintextPasswordEncoder.php b/src/Symfony/Component/Security/Core/Encoder/PlaintextPasswordEncoder.php index 48c19fbf25cc2..21a9a975e7f56 100644 --- a/src/Symfony/Component/Security/Core/Encoder/PlaintextPasswordEncoder.php +++ b/src/Symfony/Component/Security/Core/Encoder/PlaintextPasswordEncoder.php @@ -18,7 +18,7 @@ */ class PlaintextPasswordEncoder extends BasePasswordEncoder { - protected $ignorePasswordCase; + private $ignorePasswordCase; public function __construct($ignorePasswordCase = false) { diff --git a/src/Symfony/Component/Security/Core/Exception/AuthenticationException.php b/src/Symfony/Component/Security/Core/Exception/AuthenticationException.php index a01d6b8657e19..074dad094b74e 100644 --- a/src/Symfony/Component/Security/Core/Exception/AuthenticationException.php +++ b/src/Symfony/Component/Security/Core/Exception/AuthenticationException.php @@ -18,7 +18,7 @@ */ class AuthenticationException extends \RuntimeException implements \Serializable { - protected $extraInformation; + private $extraInformation; public function __construct($message, $extraInformation = null, $code = 0, \Exception $previous = null) { diff --git a/src/Symfony/Component/Security/Core/Exception/UnsupportedAccountException.php b/src/Symfony/Component/Security/Core/Exception/UnsupportedUserException.php similarity index 75% rename from src/Symfony/Component/Security/Core/Exception/UnsupportedAccountException.php rename to src/Symfony/Component/Security/Core/Exception/UnsupportedUserException.php index 9859c1dcecda1..5be9bc4432b33 100644 --- a/src/Symfony/Component/Security/Core/Exception/UnsupportedAccountException.php +++ b/src/Symfony/Component/Security/Core/Exception/UnsupportedUserException.php @@ -13,10 +13,10 @@ /** * This exception is thrown when an account is reloaded from a provider which - * doesn't support the passed implementation of AccountInterface. + * doesn't support the passed implementation of UserInterface. * * @author Johannes M. Schmitt */ -class UnsupportedAccountException extends AuthenticationServiceException +class UnsupportedUserException extends AuthenticationServiceException { } \ No newline at end of file diff --git a/src/Symfony/Component/Security/Core/Role/Role.php b/src/Symfony/Component/Security/Core/Role/Role.php index 4e2234054d847..5b50981fe1a78 100644 --- a/src/Symfony/Component/Security/Core/Role/Role.php +++ b/src/Symfony/Component/Security/Core/Role/Role.php @@ -19,7 +19,7 @@ */ class Role implements RoleInterface { - protected $role; + private $role; /** * Constructor. diff --git a/src/Symfony/Component/Security/Core/Role/RoleHierarchy.php b/src/Symfony/Component/Security/Core/Role/RoleHierarchy.php index 5217b5380b3a0..a368a447b0e7e 100644 --- a/src/Symfony/Component/Security/Core/Role/RoleHierarchy.php +++ b/src/Symfony/Component/Security/Core/Role/RoleHierarchy.php @@ -18,8 +18,8 @@ */ class RoleHierarchy implements RoleHierarchyInterface { - protected $hierarchy; - protected $map; + private $hierarchy; + private $map; /** * Constructor. @@ -56,7 +56,7 @@ public function getReachableRoles(array $roles) return $reachableRoles; } - protected function buildRoleMap() + private function buildRoleMap() { $this->map = array(); foreach ($this->hierarchy as $main => $roles) { diff --git a/src/Symfony/Component/Security/Core/Role/SwitchUserRole.php b/src/Symfony/Component/Security/Core/Role/SwitchUserRole.php index 13058410949e9..c6795841beaba 100644 --- a/src/Symfony/Component/Security/Core/Role/SwitchUserRole.php +++ b/src/Symfony/Component/Security/Core/Role/SwitchUserRole.php @@ -21,7 +21,7 @@ */ class SwitchUserRole extends Role { - protected $source; + private $source; /** * Constructor. diff --git a/src/Symfony/Component/Security/Core/SecurityContext.php b/src/Symfony/Component/Security/Core/SecurityContext.php index 68ee2e027adad..76ec4c10922f5 100644 --- a/src/Symfony/Component/Security/Core/SecurityContext.php +++ b/src/Symfony/Component/Security/Core/SecurityContext.php @@ -11,7 +11,7 @@ namespace Symfony\Component\Security\Core; -use Symfony\Component\Security\Core\User\AccountInterface; +use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException; use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface; use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; @@ -28,10 +28,10 @@ */ class SecurityContext implements SecurityContextInterface { - protected $token; - protected $accessDecisionManager; - protected $authenticationManager; - protected $alwaysAuthenticate; + private $token; + private $accessDecisionManager; + private $authenticationManager; + private $alwaysAuthenticate; /** * Constructor. @@ -45,7 +45,7 @@ public function __construct(AuthenticationManagerInterface $authenticationManage $this->alwaysAuthenticate = $alwaysAuthenticate; } - public final function vote($attributes, $object = null) + public final function isGranted($attributes, $object = null) { if (null === $this->token) { throw new AuthenticationCredentialsNotFoundException('The security context contains no authentication token.'); diff --git a/src/Symfony/Component/Security/Core/SecurityContextInterface.php b/src/Symfony/Component/Security/Core/SecurityContextInterface.php index fd205d6dbd7b9..a811557727b07 100644 --- a/src/Symfony/Component/Security/Core/SecurityContextInterface.php +++ b/src/Symfony/Component/Security/Core/SecurityContextInterface.php @@ -16,6 +16,6 @@ interface SecurityContextInterface const LAST_USERNAME = '_security.last_username'; function getToken(); - function setToken(TokenInterface $account); - function vote($attributes, $object = null); + function setToken(TokenInterface $token); + function isGranted($attributes, $object = null); } \ No newline at end of file diff --git a/src/Symfony/Component/Security/Core/User/AdvancedAccountInterface.php b/src/Symfony/Component/Security/Core/User/AdvancedUserInterface.php similarity index 89% rename from src/Symfony/Component/Security/Core/User/AdvancedAccountInterface.php rename to src/Symfony/Component/Security/Core/User/AdvancedUserInterface.php index 2c615b21456c0..ba528a10501f0 100644 --- a/src/Symfony/Component/Security/Core/User/AdvancedAccountInterface.php +++ b/src/Symfony/Component/Security/Core/User/AdvancedUserInterface.php @@ -12,11 +12,11 @@ namespace Symfony\Component\Security\Core\User; /** - * AdvancedAccountInterface adds status flags to a regular account. + * AdvancedUserInterface adds status flags to a regular account. * * @author Fabien Potencier */ -interface AdvancedAccountInterface extends AccountInterface +interface AdvancedUserInterface extends UserInterface { /** * Checks whether the user's account has expired. diff --git a/src/Symfony/Component/Security/Core/User/ChainUserProvider.php b/src/Symfony/Component/Security/Core/User/ChainUserProvider.php index 296d099c9b191..6417f994ea730 100644 --- a/src/Symfony/Component/Security/Core/User/ChainUserProvider.php +++ b/src/Symfony/Component/Security/Core/User/ChainUserProvider.php @@ -2,7 +2,7 @@ namespace Symfony\Component\Security\Core\User; -use Symfony\Component\Security\Core\Exception\UnsupportedAccountException; +use Symfony\Component\Security\Core\Exception\UnsupportedUserException; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; /** @@ -15,7 +15,7 @@ */ class ChainUserProvider implements UserProviderInterface { - protected $providers; + private $providers; public function __construct(array $providers) { @@ -41,17 +41,17 @@ public function loadUserByUsername($username) /** * {@inheritDoc} */ - public function loadUserByAccount(AccountInterface $account) + public function loadUser(UserInterface $user) { foreach ($this->providers as $provider) { try { - return $provider->loadUserByAccount($account); - } catch (UnsupportedAccountException $unsupported) { + return $provider->loadUser($user); + } catch (UnsupportedUserException $unsupported) { // try next one } } - throw new UnsupportedAccountException(sprintf('The account "%s" is not supported.', get_class($account))); + throw new UnsupportedUserException(sprintf('The account "%s" is not supported.', get_class($user))); } /** diff --git a/src/Symfony/Component/Security/Core/User/EntityUserProvider.php b/src/Symfony/Component/Security/Core/User/EntityUserProvider.php index 58bcc457f2363..61dd708269fc3 100644 --- a/src/Symfony/Component/Security/Core/User/EntityUserProvider.php +++ b/src/Symfony/Component/Security/Core/User/EntityUserProvider.php @@ -12,7 +12,7 @@ namespace Symfony\Component\Security\Core\User; use Doctrine\ORM\EntityManager; -use Symfony\Component\Security\Core\Exception\UnsupportedAccountException; +use Symfony\Component\Security\Core\Exception\UnsupportedUserException; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; /** @@ -25,9 +25,9 @@ */ class EntityUserProvider implements UserProviderInterface { - protected $class; - protected $repository; - protected $property; + private $class; + private $repository; + private $property; public function __construct(EntityManager $em, $class, $property = null) { @@ -66,13 +66,13 @@ public function loadUserByUsername($username) /** * {@inheritDoc} */ - public function loadUserByAccount(AccountInterface $account) + public function loadUser(UserInterface $user) { - if (!$account instanceof $this->class) { - throw new UnsupportedAccountException(sprintf('Instances of "%s" are not supported.', get_class($account))); + if (!$user instanceof $this->class) { + throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user))); } - return $this->loadUserByUsername($account->getUsername()); + return $this->loadUserByUsername($user->getUsername()); } /** diff --git a/src/Symfony/Component/Security/Core/User/InMemoryUserProvider.php b/src/Symfony/Component/Security/Core/User/InMemoryUserProvider.php index 7d4d1cc190e0a..26b4080700fd2 100644 --- a/src/Symfony/Component/Security/Core/User/InMemoryUserProvider.php +++ b/src/Symfony/Component/Security/Core/User/InMemoryUserProvider.php @@ -12,7 +12,7 @@ namespace Symfony\Component\Security\Core\User; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; -use Symfony\Component\Security\Core\Exception\UnsupportedAccountException; +use Symfony\Component\Security\Core\Exception\UnsupportedUserException; /** * InMemoryUserProvider is a simple non persistent user provider. @@ -24,7 +24,7 @@ */ class InMemoryUserProvider implements UserProviderInterface { - protected $users; + private $users; /** * Constructor. @@ -50,9 +50,9 @@ public function __construct(array $users = array()) /** * Adds a new User to the provider. * - * @param AccountInterface $user A AccountInterface instance + * @param UserInterface $user A UserInterface instance */ - public function createUser(AccountInterface $user) + public function createUser(UserInterface $user) { if (isset($this->users[strtolower($user->getUsername())])) { throw new \LogicException('Another user with the same username already exist.'); @@ -79,13 +79,13 @@ public function loadUserByUsername($username) /** * {@inheritDoc} */ - public function loadUserByAccount(AccountInterface $account) + public function loadUser(UserInterface $user) { - if (!$account instanceof User) { - throw new UnsupportedAccountException(sprintf('Instances of "%s" are not supported.', get_class($account))); + if (!$user instanceof User) { + throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user))); } - return $this->loadUserByUsername((string) $account); + return $this->loadUserByUsername($user->getUsername()); } /** diff --git a/src/Symfony/Component/Security/Core/User/User.php b/src/Symfony/Component/Security/Core/User/User.php index 02a2c06afb183..7dcdee348becb 100644 --- a/src/Symfony/Component/Security/Core/User/User.php +++ b/src/Symfony/Component/Security/Core/User/User.php @@ -18,16 +18,16 @@ * * @author Fabien Potencier */ -class User implements AdvancedAccountInterface +final class User implements AdvancedUserInterface { - protected $username; - protected $password; - protected $accountNonExpired; - protected $credentialsNonExpired; - protected $accountNonLocked; - protected $roles; - - public function __construct($username, $password, array $roles = array(), $enabled = true, $accountNonExpired = true, $credentialsNonExpired = true, $accountNonLocked = true) + private $username; + private $password; + private $userNonExpired; + private $credentialsNonExpired; + private $userNonLocked; + private $roles; + + public function __construct($username, $password, array $roles = array(), $enabled = true, $userNonExpired = true, $credentialsNonExpired = true, $userNonLocked = true) { if (empty($username)) { throw new \InvalidArgumentException('The username cannot be empty.'); @@ -36,20 +36,12 @@ public function __construct($username, $password, array $roles = array(), $enabl $this->username = $username; $this->password = $password; $this->enabled = $enabled; - $this->accountNonExpired = $accountNonExpired; + $this->accountNonExpired = $userNonExpired; $this->credentialsNonExpired = $credentialsNonExpired; - $this->accountNonLocked = $accountNonLocked; + $this->accountNonLocked = $userNonLocked; $this->roles = $roles; } - /** - * {@inheritdoc} - */ - public function __toString() - { - return $this->username; - } - /** * {@inheritdoc} */ @@ -124,37 +116,37 @@ public function eraseCredentials() /** * {@inheritDoc} */ - public function equals(AccountInterface $account) + public function equals(UserInterface $user) { - if (!$account instanceof User) { + if (!$user instanceof User) { return false; } - if ($this->password !== $account->getPassword()) { + if ($this->password !== $user->getPassword()) { return false; } - if ($this->getSalt() !== $account->getSalt()) { + if ($this->getSalt() !== $user->getSalt()) { return false; } - if ($this->username !== $account->getUsername()) { + if ($this->username !== $user->getUsername()) { return false; } - if ($this->accountNonExpired !== $account->isAccountNonExpired()) { + if ($this->accountNonExpired !== $user->isAccountNonExpired()) { return false; } - if ($this->accountNonLocked !== $account->isAccountNonLocked()) { + if ($this->accountNonLocked !== $user->isAccountNonLocked()) { return false; } - if ($this->credentialsNonExpired !== $account->isCredentialsNonExpired()) { + if ($this->credentialsNonExpired !== $user->isCredentialsNonExpired()) { return false; } - if ($this->enabled !== $account->isEnabled()) { + if ($this->enabled !== $user->isEnabled()) { return false; } diff --git a/src/Symfony/Component/Security/Core/User/AccountChecker.php b/src/Symfony/Component/Security/Core/User/UserChecker.php similarity index 63% rename from src/Symfony/Component/Security/Core/User/AccountChecker.php rename to src/Symfony/Component/Security/Core/User/UserChecker.php index cf66f935e43f2..93897a1010a41 100644 --- a/src/Symfony/Component/Security/Core/User/AccountChecker.php +++ b/src/Symfony/Component/Security/Core/User/UserChecker.php @@ -17,45 +17,45 @@ use Symfony\Component\Security\Core\Exception\AccountExpiredException; /** - * AccountChecker checks the user account flags. + * UserChecker checks the user account flags. * * @author Fabien Potencier */ -class AccountChecker implements AccountCheckerInterface +class UserChecker implements UserCheckerInterface { /** * {@inheritdoc} */ - public function checkPreAuth(AccountInterface $account) + public function checkPreAuth(UserInterface $user) { - if (!$account instanceof AdvancedAccountInterface) { + if (!$user instanceof AdvancedUserInterface) { return; } - if (!$account->isCredentialsNonExpired()) { - throw new CredentialsExpiredException('User credentials have expired.', $account); + if (!$user->isCredentialsNonExpired()) { + throw new CredentialsExpiredException('User credentials have expired.', $user); } } /** * {@inheritdoc} */ - public function checkPostAuth(AccountInterface $account) + public function checkPostAuth(UserInterface $user) { - if (!$account instanceof AdvancedAccountInterface) { + if (!$user instanceof AdvancedUserInterface) { return; } - if (!$account->isAccountNonLocked()) { - throw new LockedException('User account is locked.', $account); + if (!$user->isAccountNonLocked()) { + throw new LockedException('User account is locked.', $user); } - if (!$account->isEnabled()) { - throw new DisabledException('User account is disabled.', $account); + if (!$user->isEnabled()) { + throw new DisabledException('User account is disabled.', $user); } - if (!$account->isAccountNonExpired()) { - throw new AccountExpiredException('User account has expired.', $account); + if (!$user->isAccountNonExpired()) { + throw new AccountExpiredException('User account has expired.', $user); } } } diff --git a/src/Symfony/Component/Security/Core/User/AccountCheckerInterface.php b/src/Symfony/Component/Security/Core/User/UserCheckerInterface.php similarity index 61% rename from src/Symfony/Component/Security/Core/User/AccountCheckerInterface.php rename to src/Symfony/Component/Security/Core/User/UserCheckerInterface.php index 1e9abaae5e3f5..25de94a8dfec5 100644 --- a/src/Symfony/Component/Security/Core/User/AccountCheckerInterface.php +++ b/src/Symfony/Component/Security/Core/User/UserCheckerInterface.php @@ -12,25 +12,25 @@ namespace Symfony\Component\Security\Core\User; /** - * AccountCheckerInterface checks user account when authentication occurs. + * UserCheckerInterface checks user account when authentication occurs. * * This should not be used to make authentication decisions. * * @author Fabien Potencier */ -interface AccountCheckerInterface +interface UserCheckerInterface { /** * Checks the user account before authentication. * - * @param AccountInterface $account An AccountInterface instance + * @param UserInterface $user An UserInterface instance */ - function checkPreAuth(AccountInterface $account); + function checkPreAuth(UserInterface $user); /** * Checks the user account after authentication. * - * @param AccountInterface $account An AccountInterface instance + * @param UserInterface $user An UserInterface instance */ - function checkPostAuth(AccountInterface $account); + function checkPostAuth(UserInterface $user); } diff --git a/src/Symfony/Component/Security/Core/User/AccountInterface.php b/src/Symfony/Component/Security/Core/User/UserInterface.php similarity index 87% rename from src/Symfony/Component/Security/Core/User/AccountInterface.php rename to src/Symfony/Component/Security/Core/User/UserInterface.php index 46ea6aea86e3f..9091bfc2384e0 100644 --- a/src/Symfony/Component/Security/Core/User/AccountInterface.php +++ b/src/Symfony/Component/Security/Core/User/UserInterface.php @@ -12,11 +12,11 @@ namespace Symfony\Component\Security\Core\User; /** - * AccountInterface is the interface that user classes must implement. + * UserInterface is the interface that user classes must implement. * * @author Fabien Potencier */ -interface AccountInterface +interface UserInterface { /** * Returns the roles granted to the user. @@ -60,8 +60,8 @@ function eraseCredentials(); * However, you do not need to compare every attribute, but only those that * are relevant for assessing whether re-authentication is required. * - * @param AccountInterface $account + * @param UserInterface $user * @return Boolean */ - function equals(AccountInterface $account); + function equals(UserInterface $user); } diff --git a/src/Symfony/Component/Security/Core/User/UserProviderInterface.php b/src/Symfony/Component/Security/Core/User/UserProviderInterface.php index 6c5666fbfcea0..79be191390266 100644 --- a/src/Symfony/Component/Security/Core/User/UserProviderInterface.php +++ b/src/Symfony/Component/Security/Core/User/UserProviderInterface.php @@ -28,7 +28,7 @@ interface UserProviderInterface * @throws UsernameNotFoundException if the user is not found * @param string $username The username * - * @return AccountInterface + * @return UserInterface */ function loadUserByUsername($username); @@ -39,12 +39,12 @@ function loadUserByUsername($username); * from the database, or if it simply merges the passed User into the * identity map of an entity manager. * - * @throws UnsupportedAccountException if the account is not supported - * @param AccountInterface $account + * @throws UnsupportedUserException if the account is not supported + * @param UserInterface $user * - * @return AccountInterface + * @return UserInterface */ - function loadUserByAccount(AccountInterface $account); + function loadUser(UserInterface $user); /** * Whether this provider supports the given user class diff --git a/src/Symfony/Component/Security/Http/AccessMap.php b/src/Symfony/Component/Security/Http/AccessMap.php index ef7a4f08a3098..6d12b4227021c 100644 --- a/src/Symfony/Component/Security/Http/AccessMap.php +++ b/src/Symfony/Component/Security/Http/AccessMap.php @@ -22,7 +22,7 @@ */ class AccessMap { - protected $map = array(); + private $map = array(); /** * Constructor. diff --git a/src/Symfony/Component/Security/Http/EntryPoint/BasicAuthenticationEntryPoint.php b/src/Symfony/Component/Security/Http/EntryPoint/BasicAuthenticationEntryPoint.php index 4fcfe6ff7c98b..8f824265b2ef0 100644 --- a/src/Symfony/Component/Security/Http/EntryPoint/BasicAuthenticationEntryPoint.php +++ b/src/Symfony/Component/Security/Http/EntryPoint/BasicAuthenticationEntryPoint.php @@ -24,7 +24,7 @@ */ class BasicAuthenticationEntryPoint implements AuthenticationEntryPointInterface { - protected $realmName; + private $realmName; public function __construct($realmName) { diff --git a/src/Symfony/Component/Security/Http/EntryPoint/DigestAuthenticationEntryPoint.php b/src/Symfony/Component/Security/Http/EntryPoint/DigestAuthenticationEntryPoint.php index a1dcf4beccc3b..a4488abf0748c 100644 --- a/src/Symfony/Component/Security/Http/EntryPoint/DigestAuthenticationEntryPoint.php +++ b/src/Symfony/Component/Security/Http/EntryPoint/DigestAuthenticationEntryPoint.php @@ -26,10 +26,10 @@ */ class DigestAuthenticationEntryPoint implements AuthenticationEntryPointInterface { - protected $key; - protected $realmName; - protected $nonceValiditySeconds; - protected $logger; + private $key; + private $realmName; + private $nonceValiditySeconds; + private $logger; public function __construct($realmName, $key, $nonceValiditySeconds = 300, LoggerInterface $logger = null) { @@ -62,14 +62,4 @@ public function start(EventInterface $event, Request $request, AuthenticationExc return $response; } - - public function getKey() - { - return $this->key; - } - - public function getRealmName() - { - return $this->realmName; - } } diff --git a/src/Symfony/Component/Security/Http/EntryPoint/FormAuthenticationEntryPoint.php b/src/Symfony/Component/Security/Http/EntryPoint/FormAuthenticationEntryPoint.php index 55a32db6eed5e..e43eca4dedcd2 100644 --- a/src/Symfony/Component/Security/Http/EntryPoint/FormAuthenticationEntryPoint.php +++ b/src/Symfony/Component/Security/Http/EntryPoint/FormAuthenticationEntryPoint.php @@ -26,8 +26,8 @@ */ class FormAuthenticationEntryPoint implements AuthenticationEntryPointInterface { - protected $loginPath; - protected $useForward; + private $loginPath; + private $useForward; /** * Constructor diff --git a/src/Symfony/Component/Security/Http/EntryPoint/RetryAuthenticationEntryPoint.php b/src/Symfony/Component/Security/Http/EntryPoint/RetryAuthenticationEntryPoint.php index 328617e86fc18..48959bf908c16 100644 --- a/src/Symfony/Component/Security/Http/EntryPoint/RetryAuthenticationEntryPoint.php +++ b/src/Symfony/Component/Security/Http/EntryPoint/RetryAuthenticationEntryPoint.php @@ -27,8 +27,8 @@ */ class RetryAuthenticationEntryPoint implements AuthenticationEntryPointInterface { - protected $httpPort; - protected $httpsPort; + private $httpPort; + private $httpsPort; public function __construct($httpPort = 80, $httpsPort = 443) { diff --git a/src/Symfony/Component/Security/Http/Firewall.php b/src/Symfony/Component/Security/Http/Firewall.php index 76889babe3b9c..66b3ce6f45acf 100644 --- a/src/Symfony/Component/Security/Http/Firewall.php +++ b/src/Symfony/Component/Security/Http/Firewall.php @@ -31,9 +31,9 @@ */ class Firewall { - protected $map; - protected $dispatcher; - protected $currentListeners; + private $map; + private $dispatcher; + private $currentListeners; /** * Constructor. diff --git a/src/Symfony/Component/Security/Http/Firewall/AbstractAuthenticationListener.php b/src/Symfony/Component/Security/Http/Firewall/AbstractAuthenticationListener.php index 501dcd90499a0..eefe2f4ddc31f 100644 --- a/src/Symfony/Component/Security/Http/Firewall/AbstractAuthenticationListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/AbstractAuthenticationListener.php @@ -35,8 +35,8 @@ * Subclasses likely have to implement the following: * - an TokenInterface to hold authentication related data * - an AuthenticationProvider to perform the actual authentication of the - * token, retrieve the AccountInterface implementation from a database, and - * perform the specific account checks using the AccountChecker + * token, retrieve the UserInterface implementation from a database, and + * perform the specific account checks using the UserChecker * * By default, this listener only is active for a specific path, e.g. * /login_check. If you want to change this behavior, you can overwrite the @@ -47,16 +47,16 @@ */ abstract class AbstractAuthenticationListener implements ListenerInterface { - protected $securityContext; - protected $authenticationManager; - protected $sessionStrategy; - protected $providerKey; - protected $eventDispatcher; protected $options; - protected $successHandler; - protected $failureHandler; protected $logger; - protected $rememberMeServices; + protected $authenticationManager; + protected $providerKey; + private $securityContext; + private $sessionStrategy; + private $eventDispatcher; + private $successHandler; + private $failureHandler; + private $rememberMeServices; /** * Constructor. @@ -173,7 +173,18 @@ protected function requiresAuthentication(Request $request) return $this->options['check_path'] === $request->getPathInfo(); } - protected function onFailure($event, Request $request, AuthenticationException $failed) + /** + * Performs authentication. + * + * @param Request $request A Request instance + * + * @return TokenInterface The authenticated token, or null if full authentication is not possible + * + * @throws AuthenticationException if the authentication fails + */ + abstract protected function attemptAuthentication(Request $request); + + private function onFailure($event, Request $request, AuthenticationException $failed) { if (null !== $this->logger) { $this->logger->debug(sprintf('Authentication request failed: %s', $failed->getMessage())); @@ -209,7 +220,7 @@ protected function onFailure($event, Request $request, AuthenticationException $ return new RedirectResponse(0 !== strpos($this->options['failure_path'], 'http') ? $request->getUriForPath($this->options['failure_path']) : $this->options['failure_path'], 302); } - protected function onSuccess(EventInterface $event, Request $request, TokenInterface $token) + private function onSuccess(EventInterface $event, Request $request, TokenInterface $token) { if (null !== $this->logger) { $this->logger->debug('User has been authenticated successfully'); @@ -246,7 +257,7 @@ protected function onSuccess(EventInterface $event, Request $request, TokenInter * * @return string */ - protected function determineTargetUrl(Request $request) + private function determineTargetUrl(Request $request) { if ($this->options['always_use_default_target_path']) { return $this->options['default_target_path']; @@ -269,15 +280,4 @@ protected function determineTargetUrl(Request $request) return $this->options['default_target_path']; } - - /** - * Performs authentication. - * - * @param Request $request A Request instance - * - * @return TokenInterface The authenticated token, or null if full authentication is not possible - * - * @throws AuthenticationException if the authentication fails - */ - abstract protected function attemptAuthentication(Request $request); } diff --git a/src/Symfony/Component/Security/Http/Firewall/AbstractPreAuthenticatedListener.php b/src/Symfony/Component/Security/Http/Firewall/AbstractPreAuthenticatedListener.php index afced74d1d614..716f5755918a6 100644 --- a/src/Symfony/Component/Security/Http/Firewall/AbstractPreAuthenticatedListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/AbstractPreAuthenticatedListener.php @@ -30,11 +30,11 @@ */ abstract class AbstractPreAuthenticatedListener implements ListenerInterface { - protected $securityContext; - protected $authenticationManager; - protected $providerKey; protected $logger; - protected $eventDispatcher; + private $securityContext; + private $authenticationManager; + private $providerKey; + private $eventDispatcher; public function __construct(SecurityContextInterface $securityContext, AuthenticationManagerInterface $authenticationManager, $providerKey, LoggerInterface $logger = null) { @@ -80,11 +80,7 @@ public function handle(EventInterface $event) list($user, $credentials) = $this->getPreAuthenticatedData($request); if (null !== $token = $this->securityContext->getToken()) { - if ($token->isImmutable()) { - return; - } - - if ($token instanceof PreAuthenticatedToken && $token->isAuthenticated() && (string) $token === $user) { + if ($token instanceof PreAuthenticatedToken && $token->isAuthenticated() && $token->getUsername() === $user) { return; } } diff --git a/src/Symfony/Component/Security/Http/Firewall/AccessListener.php b/src/Symfony/Component/Security/Http/Firewall/AccessListener.php index cb3e02381af05..3bbbc4b5d5892 100644 --- a/src/Symfony/Component/Security/Http/Firewall/AccessListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/AccessListener.php @@ -28,11 +28,11 @@ */ class AccessListener implements ListenerInterface { - protected $context; - protected $accessDecisionManager; - protected $map; - protected $authManager; - protected $logger; + private $context; + private $accessDecisionManager; + private $map; + private $authManager; + private $logger; public function __construct(SecurityContext $context, AccessDecisionManagerInterface $accessDecisionManager, AccessMap $map, AuthenticationManagerInterface $authManager, LoggerInterface $logger = null) { @@ -53,7 +53,7 @@ public function register(EventDispatcherInterface $dispatcher) { $dispatcher->connect('core.security', array($this, 'handle'), 0); } - + /** * {@inheritDoc} */ diff --git a/src/Symfony/Component/Security/Http/Firewall/AnonymousAuthenticationListener.php b/src/Symfony/Component/Security/Http/Firewall/AnonymousAuthenticationListener.php index 352872a8fc97c..94500064de9da 100644 --- a/src/Symfony/Component/Security/Http/Firewall/AnonymousAuthenticationListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/AnonymousAuthenticationListener.php @@ -25,9 +25,9 @@ */ class AnonymousAuthenticationListener implements ListenerInterface { - protected $context; - protected $key; - protected $logger; + private $context; + private $key; + private $logger; public function __construct(SecurityContextInterface $context, $key, LoggerInterface $logger = null) { diff --git a/src/Symfony/Component/Security/Http/Firewall/BasicAuthenticationListener.php b/src/Symfony/Component/Security/Http/Firewall/BasicAuthenticationListener.php index 8b5afd26d1a45..3ae3e514318da 100644 --- a/src/Symfony/Component/Security/Http/Firewall/BasicAuthenticationListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/BasicAuthenticationListener.php @@ -27,12 +27,12 @@ */ class BasicAuthenticationListener implements ListenerInterface { - protected $securityContext; - protected $authenticationManager; - protected $providerKey; - protected $authenticationEntryPoint; - protected $logger; - protected $ignoreFailure; + private $securityContext; + private $authenticationManager; + private $providerKey; + private $authenticationEntryPoint; + private $logger; + private $ignoreFailure; public function __construct(SecurityContextInterface $securityContext, AuthenticationManagerInterface $authenticationManager, $providerKey, AuthenticationEntryPointInterface $authenticationEntryPoint, LoggerInterface $logger = null) { @@ -80,11 +80,7 @@ public function handle(EventInterface $event) } if (null !== $token = $this->securityContext->getToken()) { - if ($token->isImmutable()) { - return; - } - - if ($token instanceof UsernamePasswordToken && $token->isAuthenticated() && (string) $token === $username) { + if ($token instanceof UsernamePasswordToken && $token->isAuthenticated() && $token->getUsername() === $username) { return; } } diff --git a/src/Symfony/Component/Security/Http/Firewall/ChannelListener.php b/src/Symfony/Component/Security/Http/Firewall/ChannelListener.php index 43c578edd28b8..b0db39839f346 100644 --- a/src/Symfony/Component/Security/Http/Firewall/ChannelListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/ChannelListener.php @@ -25,9 +25,9 @@ */ class ChannelListener implements ListenerInterface { - protected $map; - protected $authenticationEntryPoint; - protected $logger; + private $map; + private $authenticationEntryPoint; + private $logger; public function __construct(AccessMap $map, AuthenticationEntryPointInterface $authenticationEntryPoint, LoggerInterface $logger = null) { diff --git a/src/Symfony/Component/Security/Http/Firewall/ContextListener.php b/src/Symfony/Component/Security/Http/Firewall/ContextListener.php index bd9cd2f41f658..c61885dd16b1c 100644 --- a/src/Symfony/Component/Security/Http/Firewall/ContextListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/ContextListener.php @@ -19,9 +19,9 @@ use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; -use Symfony\Component\Security\Core\Exception\UnsupportedAccountException; +use Symfony\Component\Security\Core\Exception\UnsupportedUserException; use Symfony\Component\Security\Core\SecurityContext; -use Symfony\Component\Security\Core\User\AccountInterface; +use Symfony\Component\Security\Core\User\UserInterface; /** * ContextListener manages the SecurityContext persistence through a session. @@ -31,10 +31,10 @@ */ class ContextListener implements ListenerInterface { - protected $context; - protected $contextKey; - protected $logger; - protected $userProviders; + private $context; + private $contextKey; + private $logger; + private $userProviders; public function __construct(SecurityContext $context, array $userProviders, $contextKey, LoggerInterface $logger = null) { @@ -89,7 +89,7 @@ public function read(EventInterface $event) $token = unserialize($token); - if (null !== $token && false === $token->isImmutable()) { + if (null !== $token) { $token = $this->refreshUser($token); } @@ -132,10 +132,10 @@ public function write(EventInterface $event, Response $response) * * @return TokenInterface|null */ - protected function refreshUser(TokenInterface $token) + private function refreshUser(TokenInterface $token) { $user = $token->getUser(); - if (!$user instanceof AccountInterface) { + if (!$user instanceof UserInterface) { return $token; } @@ -145,25 +145,18 @@ protected function refreshUser(TokenInterface $token) foreach ($this->userProviders as $provider) { try { - $cUser = $provider->loadUserByAccount($user); - - $token->setRoles($cUser->getRoles()); - $token->setUser($cUser); - - if (false === $cUser->equals($user)) { - $token->setAuthenticated(false); - } + $token->setUser($provider->loadUser($user)); if (null !== $this->logger) { - $this->logger->debug(sprintf('Username "%s" was reloaded from user provider.', $user)); + $this->logger->debug(sprintf('Username "%s" was reloaded from user provider.', $user->getUsername())); } return $token; - } catch (UnsupportedAccountException $unsupported) { + } catch (UnsupportedUserException $unsupported) { // let's try the next user provider } catch (UsernameNotFoundException $notFound) { if (null !== $this->logger) { - $this->logger->debug(sprintf('Username "%s" could not be found.', $user)); + $this->logger->debug(sprintf('Username "%s" could not be found.', $user->getUsername())); } return null; diff --git a/src/Symfony/Component/Security/Http/Firewall/DigestAuthenticationListener.php b/src/Symfony/Component/Security/Http/Firewall/DigestAuthenticationListener.php index 537faaa0d98d4..de5ba1800ea29 100644 --- a/src/Symfony/Component/Security/Http/Firewall/DigestAuthenticationListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/DigestAuthenticationListener.php @@ -32,11 +32,11 @@ */ class DigestAuthenticationListener implements ListenerInterface { - protected $securityContext; - protected $provider; - protected $providerKey; - protected $authenticationEntryPoint; - protected $logger; + private $securityContext; + private $provider; + private $providerKey; + private $authenticationEntryPoint; + private $logger; public function __construct(SecurityContextInterface $securityContext, UserProviderInterface $provider, $providerKey, DigestAuthenticationEntryPoint $authenticationEntryPoint, LoggerInterface $logger = null) { @@ -85,11 +85,7 @@ public function handle(EventInterface $event) $digestAuth = new DigestData($header); if (null !== $token = $this->securityContext->getToken()) { - if ($token->isImmutable()) { - return; - } - - if ($token instanceof UsernamePasswordToken && $token->isAuthenticated() && (string) $token === $digestAuth->getUsername()) { + if ($token instanceof UsernamePasswordToken && $token->isAuthenticated() && $token->getUsername() === $digestAuth->getUsername()) { return; } } @@ -143,7 +139,7 @@ public function handle(EventInterface $event) $this->securityContext->setToken(new UsernamePasswordToken($user, $user->getPassword(), $this->providerKey)); } - protected function fail(EventInterface $event, Request $request, AuthenticationException $authException) + private function fail(EventInterface $event, Request $request, AuthenticationException $authException) { $this->securityContext->setToken(null); @@ -157,9 +153,9 @@ protected function fail(EventInterface $event, Request $request, AuthenticationE class DigestData { - protected $elements; - protected $header; - protected $nonceExpiryTime; + private $elements; + private $header; + private $nonceExpiryTime; public function __construct($header) { diff --git a/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php b/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php index 76a9c99f43854..90f5a017884a1 100644 --- a/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php @@ -34,12 +34,12 @@ */ class ExceptionListener implements ListenerInterface { - protected $context; - protected $accessDeniedHandler; - protected $authenticationEntryPoint; - protected $authenticationTrustResolver; - protected $errorPage; - protected $logger; + private $context; + private $accessDeniedHandler; + private $authenticationEntryPoint; + private $authenticationTrustResolver; + private $errorPage; + private $logger; public function __construct(SecurityContextInterface $context, AuthenticationTrustResolverInterface $trustResolver, AuthenticationEntryPointInterface $authenticationEntryPoint = null, $errorPage = null, AccessDeniedHandlerInterface $accessDeniedHandler = null, LoggerInterface $logger = null) { @@ -148,7 +148,7 @@ public function handleException(EventInterface $event) return $response; } - protected function startAuthentication(EventInterface $event, Request $request, AuthenticationException $authException) + private function startAuthentication(EventInterface $event, Request $request, AuthenticationException $authException) { $this->context->setToken(null); @@ -160,7 +160,7 @@ protected function startAuthentication(EventInterface $event, Request $request, $this->logger->debug('Calling Authentication entry point'); } - // session isn't required when using http basic authentification mecanism for example + // session isn't required when using http basic authentification mechanism for example if ($request->hasSession()) { $request->getSession()->set('_security.target_path', $request->getUri()); } diff --git a/src/Symfony/Component/Security/Http/Firewall/LogoutListener.php b/src/Symfony/Component/Security/Http/Firewall/LogoutListener.php index 40257396203fa..99637572515d3 100644 --- a/src/Symfony/Component/Security/Http/Firewall/LogoutListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/LogoutListener.php @@ -27,11 +27,11 @@ */ class LogoutListener implements ListenerInterface { - protected $securityContext; - protected $logoutPath; - protected $targetUrl; - protected $handlers; - protected $successHandler; + private $securityContext; + private $logoutPath; + private $targetUrl; + private $handlers; + private $successHandler; /** * Constructor diff --git a/src/Symfony/Component/Security/Http/Firewall/RememberMeListener.php b/src/Symfony/Component/Security/Http/Firewall/RememberMeListener.php index d44f3531d2189..6b23679af3654 100644 --- a/src/Symfony/Component/Security/Http/Firewall/RememberMeListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/RememberMeListener.php @@ -31,12 +31,12 @@ */ class RememberMeListener implements ListenerInterface { - protected $securityContext; - protected $rememberMeServices; - protected $authenticationManager; - protected $logger; - protected $lastState; - protected $eventDispatcher; + private $securityContext; + private $rememberMeServices; + private $authenticationManager; + private $logger; + private $lastState; + private $eventDispatcher; /** * Constructor diff --git a/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php b/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php index 2adc676dbcc26..96891bdae6d64 100644 --- a/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/SwitchUserListener.php @@ -14,7 +14,7 @@ use Symfony\Component\EventDispatcher\Event; use Symfony\Component\Security\Core\SecurityContextInterface; use Symfony\Component\Security\Core\User\UserProviderInterface; -use Symfony\Component\Security\Core\User\AccountCheckerInterface; +use Symfony\Component\Security\Core\User\UserCheckerInterface; use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface; use Symfony\Component\HttpKernel\Log\LoggerInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; @@ -36,20 +36,20 @@ */ class SwitchUserListener implements ListenerInterface { - protected $securityContext; - protected $provider; - protected $accountChecker; - protected $providerKey; - protected $accessDecisionManager; - protected $usernameParameter; - protected $role; - protected $logger; - protected $eventDispatcher; + private $securityContext; + private $provider; + private $userChecker; + private $providerKey; + private $accessDecisionManager; + private $usernameParameter; + private $role; + private $logger; + private $eventDispatcher; /** * Constructor. */ - public function __construct(SecurityContextInterface $securityContext, UserProviderInterface $provider, AccountCheckerInterface $accountChecker, $providerKey, AccessDecisionManagerInterface $accessDecisionManager, LoggerInterface $logger = null, $usernameParameter = '_switch_user', $role = 'ROLE_ALLOWED_TO_SWITCH') + public function __construct(SecurityContextInterface $securityContext, UserProviderInterface $provider, UserCheckerInterface $userChecker, $providerKey, AccessDecisionManagerInterface $accessDecisionManager, LoggerInterface $logger = null, $usernameParameter = '_switch_user', $role = 'ROLE_ALLOWED_TO_SWITCH') { if (empty($providerKey)) { throw new \InvalidArgumentException('$providerKey must not be empty.'); @@ -57,7 +57,7 @@ public function __construct(SecurityContextInterface $securityContext, UserProvi $this->securityContext = $securityContext; $this->provider = $provider; - $this->accountChecker = $accountChecker; + $this->userChecker = $userChecker; $this->providerKey = $providerKey; $this->accessDecisionManager = $accessDecisionManager; $this->usernameParameter = $usernameParameter; @@ -125,11 +125,11 @@ public function handle(EventInterface $event) * * @return TokenInterface|null The new TokenInterface if successfully switched, null otherwise */ - protected function attemptSwitchUser(Request $request) + private function attemptSwitchUser(Request $request) { $token = $this->securityContext->getToken(); if (false !== $this->getOriginalToken($token)) { - throw new \LogicException(sprintf('You are already switched to "%s" user.', (string) $token)); + throw new \LogicException(sprintf('You are already switched to "%s" user.', $token->getUsername())); } $this->accessDecisionManager->decide($token, array($this->role)); @@ -141,13 +141,12 @@ protected function attemptSwitchUser(Request $request) } $user = $this->provider->loadUserByUsername($username); - $this->accountChecker->checkPostAuth($user); + $this->userChecker->checkPostAuth($user); $roles = $user->getRoles(); $roles[] = new SwitchUserRole('ROLE_PREVIOUS_ADMIN', $this->securityContext->getToken()); $token = new UsernamePasswordToken($user, $user->getPassword(), $this->providerKey, $roles); - $token->setImmutable(true); if (null !== $this->eventDispatcher) { $this->eventDispatcher->notify(new Event($this, 'security.switch_user', array('request' => $request, 'target_user' => $token->getUser()))); @@ -163,7 +162,7 @@ protected function attemptSwitchUser(Request $request) * * @return TokenInterface The original TokenInterface instance */ - protected function attemptExitUser(Request $request) + private function attemptExitUser(Request $request) { if (false === $original = $this->getOriginalToken($this->securityContext->getToken())) { throw new AuthenticationCredentialsNotFoundException(sprintf('Could not find original Token object.')); @@ -183,7 +182,7 @@ protected function attemptExitUser(Request $request) * * @return TokenInterface|false The original TokenInterface instance, false if the current TokenInterface is not switched */ - protected function getOriginalToken(TokenInterface $token) + private function getOriginalToken(TokenInterface $token) { foreach ($token->getRoles() as $role) { if ($role instanceof SwitchUserRole) { diff --git a/src/Symfony/Component/Security/Http/Firewall/UsernamePasswordFormAuthenticationListener.php b/src/Symfony/Component/Security/Http/Firewall/UsernamePasswordFormAuthenticationListener.php index 126ef41bd57ef..3008273dc2c20 100644 --- a/src/Symfony/Component/Security/Http/Firewall/UsernamePasswordFormAuthenticationListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/UsernamePasswordFormAuthenticationListener.php @@ -30,7 +30,7 @@ */ class UsernamePasswordFormAuthenticationListener extends AbstractAuthenticationListener { - protected $csrfProvider; + private $csrfProvider; /** * {@inheritdoc} diff --git a/src/Symfony/Component/Security/Http/FirewallMap.php b/src/Symfony/Component/Security/Http/FirewallMap.php index c7a57f21df3ce..d5fc331665253 100644 --- a/src/Symfony/Component/Security/Http/FirewallMap.php +++ b/src/Symfony/Component/Security/Http/FirewallMap.php @@ -23,7 +23,7 @@ */ class FirewallMap implements FirewallMapInterface { - protected $map = array(); + private $map = array(); public function add(RequestMatcherInterface $requestMatcher = null, array $listeners = array(), ExceptionListener $exceptionListener = null) { diff --git a/src/Symfony/Component/Security/Http/Logout/CookieClearingLogoutHandler.php b/src/Symfony/Component/Security/Http/Logout/CookieClearingLogoutHandler.php index 8ca284db5184e..ebdcbed2c863d 100644 --- a/src/Symfony/Component/Security/Http/Logout/CookieClearingLogoutHandler.php +++ b/src/Symfony/Component/Security/Http/Logout/CookieClearingLogoutHandler.php @@ -22,7 +22,7 @@ */ class CookieClearingLogoutHandler implements LogoutHandlerInterface { - protected $cookies; + private $cookies; /** * Constructor diff --git a/src/Symfony/Component/Security/Http/RememberMe/PersistentTokenBasedRememberMeServices.php b/src/Symfony/Component/Security/Http/RememberMe/PersistentTokenBasedRememberMeServices.php index ff3306ed5a065..351ad0348b690 100644 --- a/src/Symfony/Component/Security/Http/RememberMe/PersistentTokenBasedRememberMeServices.php +++ b/src/Symfony/Component/Security/Http/RememberMe/PersistentTokenBasedRememberMeServices.php @@ -30,7 +30,7 @@ */ class PersistentTokenBasedRememberMeServices extends RememberMeServices { - protected $tokenProvider; + private $tokenProvider; /** * Sets the token provider @@ -43,6 +43,21 @@ public function setTokenProvider(TokenProviderInterface $tokenProvider) $this->tokenProvider = $tokenProvider; } + /** + * {@inheritDoc} + */ + public function logout(Request $request, Response $response, TokenInterface $token) + { + parent::logout($request, $response, $token); + + if (null !== ($cookie = $request->cookies->get($this->options['name'])) + && count($parts = $this->decodeCookie($cookie)) === 2 + ) { + list($series, $tokenValue) = $parts; + $this->tokenProvider->deleteTokenBySeries($series); + } + } + /** * {@inheritDoc} */ @@ -66,10 +81,8 @@ protected function processAutoLoginCookie(array $cookieParts, Request $request) } $user = $this->getUserProvider($persistentToken->getClass())->loadUserByUsername($persistentToken->getUsername()); - $authenticationToken = new RememberMeToken($user, $this->providerKey, $this->key); - $authenticationToken->setPersistentToken($persistentToken); - return $authenticationToken; + return new RememberMeToken($user, $this->providerKey, $this->key, $persistentToken); } /** @@ -114,21 +127,6 @@ protected function onLoginSuccess(Request $request, Response $response, TokenInt ); } - /** - * {@inheritDoc} - */ - public function logout(Request $request, Response $response, TokenInterface $token) - { - parent::logout($request, $response, $token); - - if (null !== ($cookie = $request->cookies->get($this->options['name'])) - && count($parts = $this->decodeCookie($cookie)) === 2 - ) { - list($series, $tokenValue) = $parts; - $this->tokenProvider->deleteTokenBySeries($series); - } - } - /** * Generates the value for the cookie * diff --git a/src/Symfony/Component/Security/Http/RememberMe/RememberMeServices.php b/src/Symfony/Component/Security/Http/RememberMe/RememberMeServices.php index 4370d92130049..e0ed52b47872d 100644 --- a/src/Symfony/Component/Security/Http/RememberMe/RememberMeServices.php +++ b/src/Symfony/Component/Security/Http/RememberMe/RememberMeServices.php @@ -2,7 +2,7 @@ namespace Symfony\Component\Security\Http\RememberMe; -use Symfony\Component\Security\Core\User\AccountInterface; +use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken; use Symfony\Component\Security\Http\Logout\LogoutHandlerInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; @@ -30,11 +30,11 @@ abstract class RememberMeServices implements RememberMeServicesInterface, Logout { const COOKIE_DELIMITER = ':'; - protected $userProviders; protected $options; protected $logger; - protected $key; protected $providerKey; + protected $key; + private $userProviders; /** * Constructor @@ -80,7 +80,7 @@ public function getRememberMeParameter() * @param Request $request * @return TokenInterface */ - public function autoLogin(Request $request) + public final function autoLogin(Request $request) { if (null === $cookie = $request->cookies->get($this->options['name'])) { return; @@ -139,12 +139,12 @@ public function loginFail(Request $request, Response $response) * @param TokenInterface $token The token that resulted in a successful authentication * @return void */ - public function loginSuccess(Request $request, Response $response, TokenInterface $token) + public final function loginSuccess(Request $request, Response $response, TokenInterface $token) { if (!$token instanceof RememberMeToken) { - if (!$token->getUser() instanceof AccountInterface) { + if (!$token->getUser() instanceof UserInterface) { if (null !== $this->logger) { - $this->logger->debug('Remember-me ignores token since it does not contain an AccountInterface implementation.'); + $this->logger->debug('Remember-me ignores token since it does not contain an UserInterface implementation.'); } return; diff --git a/src/Symfony/Component/Security/Http/RememberMe/TokenBasedRememberMeServices.php b/src/Symfony/Component/Security/Http/RememberMe/TokenBasedRememberMeServices.php index 40757f488942b..206e10b91ce59 100644 --- a/src/Symfony/Component/Security/Http/RememberMe/TokenBasedRememberMeServices.php +++ b/src/Symfony/Component/Security/Http/RememberMe/TokenBasedRememberMeServices.php @@ -8,7 +8,7 @@ use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken; use Symfony\Component\Security\Core\Exception\AuthenticationException; -use Symfony\Component\Security\Core\User\AccountInterface; +use Symfony\Component\Security\Core\User\UserInterface; /* * This file is part of the Symfony package. @@ -50,8 +50,8 @@ protected function processAutoLoginCookie(array $cookieParts, Request $request) throw $ex; } - if (!$user instanceof AccountInterface) { - throw new \RuntimeException(sprintf('The UserProviderInterface implementation must return an instance of AccountInterface, but returned "%s".', get_class($user))); + if (!$user instanceof UserInterface) { + throw new \RuntimeException(sprintf('The UserProviderInterface implementation must return an instance of UserInterface, but returned "%s".', get_class($user))); } if (true !== $this->compareHashes($hash, $this->generateCookieHash($class, $username, $expires, $user->getPassword()))) { @@ -76,7 +76,7 @@ protected function processAutoLoginCookie(array $cookieParts, Request $request) * * @return Boolean true if the two hashes are the same, false otherwise */ - protected function compareHashes($hash1, $hash2) + private function compareHashes($hash1, $hash2) { if (strlen($hash1) !== $c = strlen($hash2)) { return false; diff --git a/src/Symfony/Component/Security/Http/Session/SessionAuthenticationStrategy.php b/src/Symfony/Component/Security/Http/Session/SessionAuthenticationStrategy.php index 1d25bd917a769..dea34be31d22f 100644 --- a/src/Symfony/Component/Security/Http/Session/SessionAuthenticationStrategy.php +++ b/src/Symfony/Component/Security/Http/Session/SessionAuthenticationStrategy.php @@ -21,7 +21,7 @@ class SessionAuthenticationStrategy implements SessionAuthenticationStrategyInte const MIGRATE = 'migrate'; const INVALIDATE = 'invalidate'; - protected $strategy; + private $strategy; public function __construct($strategy) { diff --git a/tests/Symfony/Tests/Component/Security/Acl/Domain/PermissionGrantingStrategyTest.php b/tests/Symfony/Tests/Component/Security/Acl/Domain/PermissionGrantingStrategyTest.php index 9e7548b3164e7..a7356e3a44c5c 100644 --- a/tests/Symfony/Tests/Component/Security/Acl/Domain/PermissionGrantingStrategyTest.php +++ b/tests/Symfony/Tests/Component/Security/Acl/Domain/PermissionGrantingStrategyTest.php @@ -21,20 +21,6 @@ class PermissionGrantingStrategyTest extends \PHPUnit_Framework_TestCase { - /** - * @covers:Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy::getAuditLogger - * @covers:Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy::setAuditLogger - */ - public function testGetSetAuditLogger() - { - $strategy = new PermissionGrantingStrategy(); - $logger = $this->getMock('Symfony\Component\Security\Acl\Model\AuditLoggerInterface'); - - $this->assertNull($strategy->getAuditLogger()); - $strategy->setAuditLogger($logger); - $this->assertSame($logger, $strategy->getAuditLogger()); - } - public function testIsGrantedObjectAcesHavePriority() { $strategy = new PermissionGrantingStrategy(); diff --git a/tests/Symfony/Tests/Component/Security/Acl/Domain/SecurityIdentityRetrievalStrategyTest.php b/tests/Symfony/Tests/Component/Security/Acl/Domain/SecurityIdentityRetrievalStrategyTest.php index d9216cdff98f4..1621bfa68f520 100644 --- a/tests/Symfony/Tests/Component/Security/Acl/Domain/SecurityIdentityRetrievalStrategyTest.php +++ b/tests/Symfony/Tests/Component/Security/Acl/Domain/SecurityIdentityRetrievalStrategyTest.php @@ -109,7 +109,7 @@ public function getSecurityIdentityRetrievalTests() protected function getAccount($username, $class) { - $account = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface', array(), array(), $class); + $account = $this->getMock('Symfony\Component\Security\Core\User\UserInterface', array(), array(), $class); $account ->expects($this->any()) ->method('getUsername') diff --git a/tests/Symfony/Tests/Component/Security/Acl/Domain/UserSecurityIdentityTest.php b/tests/Symfony/Tests/Component/Security/Acl/Domain/UserSecurityIdentityTest.php index 40d61304e42b9..a9172c6cf49a0 100644 --- a/tests/Symfony/Tests/Component/Security/Acl/Domain/UserSecurityIdentityTest.php +++ b/tests/Symfony/Tests/Component/Security/Acl/Domain/UserSecurityIdentityTest.php @@ -34,7 +34,7 @@ public function testEquals($id1, $id2, $equal) public function getCompareData() { - $account = $this->getMockBuilder('Symfony\Component\Security\Core\User\AccountInterface') + $account = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface') ->setMockClassName('USI_AccountImpl') ->getMock(); $account diff --git a/tests/Symfony/Tests/Component/Security/Core/Authentication/AuthenticationProviderManagerTest.php b/tests/Symfony/Tests/Component/Security/Core/Authentication/AuthenticationProviderManagerTest.php index 69d1ba46b5fc4..3e7c1ddfcfb0c 100644 --- a/tests/Symfony/Tests/Component/Security/Core/Authentication/AuthenticationProviderManagerTest.php +++ b/tests/Symfony/Tests/Component/Security/Core/Authentication/AuthenticationProviderManagerTest.php @@ -19,23 +19,12 @@ class AuthenticationProviderManagerTest extends \PHPUnit_Framework_TestCase { - public function testProviderAccessors() - { - $manager = new AuthenticationProviderManager(); - $manager->add($provider = $this->getMock('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface')); - $this->assertSame(array($provider), $manager->all()); - - $manager->setProviders($providers = array($this->getMock('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface'))); - $this->assertSame($providers, $manager->all()); - } - /** - * @expectedException LogicException + * @expectedException InvalidArgumentException */ public function testAuthenticateWithoutProviders() { - $manager = new AuthenticationProviderManager(); - $manager->authenticate($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')); + new AuthenticationProviderManager(array()); } public function testAuthenticateWhenNoProviderSupportsToken() diff --git a/tests/Symfony/Tests/Component/Security/Core/Authentication/Provider/DaoAuthenticationProviderTest.php b/tests/Symfony/Tests/Component/Security/Core/Authentication/Provider/DaoAuthenticationProviderTest.php index 52417457e5e98..cf82ebf6d7bc5 100644 --- a/tests/Symfony/Tests/Component/Security/Core/Authentication/Provider/DaoAuthenticationProviderTest.php +++ b/tests/Symfony/Tests/Component/Security/Core/Authentication/Provider/DaoAuthenticationProviderTest.php @@ -22,7 +22,7 @@ class DaoAuthenticationProviderTest extends \PHPUnit_Framework_TestCase /** * @expectedException Symfony\Component\Security\Core\Exception\AuthenticationServiceException */ - public function testRetrieveUserWhenProviderDoesNotReturnAnAccountInterface() + public function testRetrieveUserWhenProviderDoesNotReturnAnUserInterface() { $provider = $this->getProvider('fabien'); $method = new \ReflectionMethod($provider, 'retrieveUser'); @@ -42,7 +42,7 @@ public function testRetrieveUserWhenUsernameIsNotFound() ->will($this->throwException($this->getMock('Symfony\Component\Security\Core\Exception\UsernameNotFoundException', null, array(), '', false))) ; - $provider = new DaoAuthenticationProvider($userProvider, $this->getMock('Symfony\Component\Security\Core\User\AccountCheckerInterface'), 'key', $this->getMock('Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface')); + $provider = new DaoAuthenticationProvider($userProvider, $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface'), 'key', $this->getMock('Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface')); $method = new \ReflectionMethod($provider, 'retrieveUser'); $method->setAccessible(true); @@ -60,7 +60,7 @@ public function testRetrieveUserWhenAnExceptionOccurs() ->will($this->throwException($this->getMock('RuntimeException', null, array(), '', false))) ; - $provider = new DaoAuthenticationProvider($userProvider, $this->getMock('Symfony\Component\Security\Core\User\AccountCheckerInterface'), 'key', $this->getMock('Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface')); + $provider = new DaoAuthenticationProvider($userProvider, $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface'), 'key', $this->getMock('Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface')); $method = new \ReflectionMethod($provider, 'retrieveUser'); $method->setAccessible(true); @@ -74,14 +74,14 @@ public function testRetrieveUserReturnsUserFromTokenOnReauthentication() ->method('loadUserByUsername') ; - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $token = $this->getSupportedToken(); $token->expects($this->once()) ->method('getUser') ->will($this->returnValue($user)) ; - $provider = new DaoAuthenticationProvider($userProvider, $this->getMock('Symfony\Component\Security\Core\User\AccountCheckerInterface'), 'key', $this->getMock('Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface')); + $provider = new DaoAuthenticationProvider($userProvider, $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface'), 'key', $this->getMock('Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface')); $reflection = new \ReflectionMethod($provider, 'retrieveUser'); $reflection->setAccessible(true); $result = $reflection->invoke($provider, null, $token); @@ -91,7 +91,7 @@ public function testRetrieveUserReturnsUserFromTokenOnReauthentication() public function testRetrieveUser() { - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $userProvider = $this->getMock('Symfony\Component\Security\Core\User\UserProviderInterface'); $userProvider->expects($this->once()) @@ -99,7 +99,7 @@ public function testRetrieveUser() ->will($this->returnValue($user)) ; - $provider = new DaoAuthenticationProvider($userProvider, $this->getMock('Symfony\Component\Security\Core\User\AccountCheckerInterface'), 'key', $this->getMock('Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface')); + $provider = new DaoAuthenticationProvider($userProvider, $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface'), 'key', $this->getMock('Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface')); $method = new \ReflectionMethod($provider, 'retrieveUser'); $method->setAccessible(true); @@ -121,7 +121,7 @@ public function testCheckAuthenticationWhenCredentialsAreEmpty() ->will($this->returnValue('')) ; - $method->invoke($provider, $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'), $token); + $method->invoke($provider, $this->getMock('Symfony\Component\Security\Core\User\UserInterface'), $token); } /** @@ -145,7 +145,7 @@ public function testCheckAuthenticationWhenCredentialsAreNotValid() ->will($this->returnValue('foo')) ; - $method->invoke($provider, $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'), $token); + $method->invoke($provider, $this->getMock('Symfony\Component\Security\Core\User\UserInterface'), $token); } /** @@ -153,7 +153,7 @@ public function testCheckAuthenticationWhenCredentialsAreNotValid() */ public function testCheckAuthenticationDoesNotReauthenticateWhenPasswordHasChanged() { - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $user->expects($this->once()) ->method('getPassword') ->will($this->returnValue('foo')) @@ -164,7 +164,7 @@ public function testCheckAuthenticationDoesNotReauthenticateWhenPasswordHasChang ->method('getUser') ->will($this->returnValue($user)); - $dbUser = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $dbUser = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $dbUser->expects($this->once()) ->method('getPassword') ->will($this->returnValue('newFoo')) @@ -178,7 +178,7 @@ public function testCheckAuthenticationDoesNotReauthenticateWhenPasswordHasChang public function testCheckAuthenticationWhenTokenNeedsReauthenticationWorksWithoutOriginalCredentials() { - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $user->expects($this->once()) ->method('getPassword') ->will($this->returnValue('foo')) @@ -189,7 +189,7 @@ public function testCheckAuthenticationWhenTokenNeedsReauthenticationWorksWithou ->method('getUser') ->will($this->returnValue($user)); - $dbUser = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $dbUser = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $dbUser->expects($this->once()) ->method('getPassword') ->will($this->returnValue('foo')) @@ -219,12 +219,12 @@ public function testCheckAuthentication() ->will($this->returnValue('foo')) ; - $method->invoke($provider, $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'), $token); + $method->invoke($provider, $this->getMock('Symfony\Component\Security\Core\User\UserInterface'), $token); } protected function getSupportedToken() { - $mock = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', array('getCredentials', 'getUser'), array(), '', false); + $mock = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', array('getCredentials', 'getUser', 'getProviderKey'), array(), '', false); $mock ->expects($this->any()) ->method('getProviderKey') @@ -245,7 +245,7 @@ protected function getProvider($user = false, $userChecker = false, $passwordEnc } if (false === $userChecker) { - $userChecker = $this->getMock('Symfony\Component\Security\Core\User\AccountCheckerInterface'); + $userChecker = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface'); } if (null === $passwordEncoder) { diff --git a/tests/Symfony/Tests/Component/Security/Core/Authentication/Provider/PreAuthenticatedAuthenticationProviderTest.php b/tests/Symfony/Tests/Component/Security/Core/Authentication/Provider/PreAuthenticatedAuthenticationProviderTest.php index af775abc49df6..4b3fae6b9646e 100644 --- a/tests/Symfony/Tests/Component/Security/Core/Authentication/Provider/PreAuthenticatedAuthenticationProviderTest.php +++ b/tests/Symfony/Tests/Component/Security/Core/Authentication/Provider/PreAuthenticatedAuthenticationProviderTest.php @@ -52,7 +52,12 @@ public function testAuthenticateWhenNoUserIsSet() public function testAuthenticate() { - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); + $user + ->expects($this->once()) + ->method('getRoles') + ->will($this->returnValue(array())) + ; $provider = $this->getProvider($user); $token = $provider->authenticate($this->getSupportedToken('fabien', 'pass')); @@ -67,11 +72,11 @@ public function testAuthenticate() /** * @expectedException Symfony\Component\Security\Core\Exception\LockedException */ - public function testAuthenticateWhenAccountCheckerThrowsException() + public function testAuthenticateWhenUserCheckerThrowsException() { - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); - $userChecker = $this->getMock('Symfony\Component\Security\Core\User\AccountCheckerInterface'); + $userChecker = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface'); $userChecker->expects($this->once()) ->method('checkPostAuth') ->will($this->throwException($this->getMock('Symfony\Component\Security\Core\Exception\LockedException', null, array(), '', false))) @@ -120,7 +125,7 @@ protected function getProvider($user = false, $userChecker = false) } if (false === $userChecker) { - $userChecker = $this->getMock('Symfony\Component\Security\Core\User\AccountCheckerInterface'); + $userChecker = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface'); } return new PreAuthenticatedAuthenticationProvider($userProvider, $userChecker, 'key'); diff --git a/tests/Symfony/Tests/Component/Security/Core/Authentication/Provider/RememberMeAuthenticationProviderTest.php b/tests/Symfony/Tests/Component/Security/Core/Authentication/Provider/RememberMeAuthenticationProviderTest.php index 290bb466b50a4..47920c0b1c5a4 100644 --- a/tests/Symfony/Tests/Component/Security/Core/Authentication/Provider/RememberMeAuthenticationProviderTest.php +++ b/tests/Symfony/Tests/Component/Security/Core/Authentication/Provider/RememberMeAuthenticationProviderTest.php @@ -35,28 +35,12 @@ public function testAuthenticateWhenKeysDoNotMatch() $provider->authenticate($token); } - /** - * @expectedException Symfony\Component\Security\Core\Exception\CredentialsExpiredException - */ - public function testAuthenticateWhenPreChecksFails() - { - $userChecker = $this->getMock('Symfony\Component\Security\Core\User\AccountCheckerInterface'); - $userChecker->expects($this->once()) - ->method('checkPreAuth') - ->will($this->throwException($this->getMock('Symfony\Component\Security\Core\Exception\CredentialsExpiredException', null, array(), '', false))) - ; - - $provider = $this->getProvider($userChecker); - - $provider->authenticate($this->getSupportedToken()); - } - /** * @expectedException Symfony\Component\Security\Core\Exception\AccountExpiredException */ public function testAuthenticateWhenPostChecksFails() { - $userChecker = $this->getMock('Symfony\Component\Security\Core\User\AccountCheckerInterface'); + $userChecker = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface'); $userChecker->expects($this->once()) ->method('checkPostAuth') ->will($this->throwException($this->getMock('Symfony\Component\Security\Core\Exception\AccountExpiredException', null, array(), '', false))) @@ -69,8 +53,8 @@ public function testAuthenticateWhenPostChecksFails() public function testAuthenticate() { - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); - $user->expects($this->once()) + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); + $user->expects($this->exactly(2)) ->method('getRoles') ->will($this->returnValue(array('ROLE_FOO'))) ; @@ -78,24 +62,18 @@ public function testAuthenticate() $provider = $this->getProvider(); $token = $this->getSupportedToken($user); - $token - ->expects($this->once()) - ->method('getCredentials') - ->will($this->returnValue('foo')) - ; - $authToken = $provider->authenticate($token); $this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken', $authToken); $this->assertSame($user, $authToken->getUser()); $this->assertEquals(array(new Role('ROLE_FOO')), $authToken->getRoles()); - $this->assertEquals('foo', $authToken->getCredentials()); + $this->assertEquals('', $authToken->getCredentials()); } protected function getSupportedToken($user = null, $key = 'test') { if (null === $user) { - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $user ->expects($this->any()) ->method('getRoles') @@ -103,7 +81,7 @@ protected function getSupportedToken($user = null, $key = 'test') ; } - $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken', array('getCredentials', 'getProviderKey'), array($user, 'foo', $key)); + $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken', array('getProviderKey'), array($user, 'foo', $key)); $token ->expects($this->once()) ->method('getProviderKey') @@ -116,7 +94,7 @@ protected function getSupportedToken($user = null, $key = 'test') protected function getProvider($userChecker = null, $key = 'test') { if (null === $userChecker) { - $userChecker = $this->getMock('Symfony\Component\Security\Core\User\AccountCheckerInterface'); + $userChecker = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface'); } return new RememberMeAuthenticationProvider($userChecker, $key, 'foo'); diff --git a/tests/Symfony/Tests/Component/Security/Core/Authentication/Provider/UserAuthenticationProviderTest.php b/tests/Symfony/Tests/Component/Security/Core/Authentication/Provider/UserAuthenticationProviderTest.php index 872da08cb93b3..ac233d658697e 100644 --- a/tests/Symfony/Tests/Component/Security/Core/Authentication/Provider/UserAuthenticationProviderTest.php +++ b/tests/Symfony/Tests/Component/Security/Core/Authentication/Provider/UserAuthenticationProviderTest.php @@ -62,7 +62,7 @@ public function testAuthenticateWhenUsernameIsNotFoundAndHideIsTrue() /** * @expectedException Symfony\Component\Security\Core\Exception\AuthenticationServiceException */ - public function testAuthenticateWhenProviderDoesNotReturnAnAccountInterface() + public function testAuthenticateWhenProviderDoesNotReturnAnUserInterface() { $provider = $this->getProvider(false, true); $provider->expects($this->once()) @@ -78,7 +78,7 @@ public function testAuthenticateWhenProviderDoesNotReturnAnAccountInterface() */ public function testAuthenticateWhenPreChecksFails() { - $userChecker = $this->getMock('Symfony\Component\Security\Core\User\AccountCheckerInterface'); + $userChecker = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface'); $userChecker->expects($this->once()) ->method('checkPreAuth') ->will($this->throwException($this->getMock('Symfony\Component\Security\Core\Exception\CredentialsExpiredException', null, array(), '', false))) @@ -87,7 +87,7 @@ public function testAuthenticateWhenPreChecksFails() $provider = $this->getProvider($userChecker); $provider->expects($this->once()) ->method('retrieveUser') - ->will($this->returnValue($this->getMock('Symfony\Component\Security\Core\User\AccountInterface'))) + ->will($this->returnValue($this->getMock('Symfony\Component\Security\Core\User\UserInterface'))) ; $provider->authenticate($this->getSupportedToken()); @@ -98,7 +98,7 @@ public function testAuthenticateWhenPreChecksFails() */ public function testAuthenticateWhenPostChecksFails() { - $userChecker = $this->getMock('Symfony\Component\Security\Core\User\AccountCheckerInterface'); + $userChecker = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface'); $userChecker->expects($this->once()) ->method('checkPostAuth') ->will($this->throwException($this->getMock('Symfony\Component\Security\Core\Exception\AccountExpiredException', null, array(), '', false))) @@ -107,7 +107,7 @@ public function testAuthenticateWhenPostChecksFails() $provider = $this->getProvider($userChecker); $provider->expects($this->once()) ->method('retrieveUser') - ->will($this->returnValue($this->getMock('Symfony\Component\Security\Core\User\AccountInterface'))) + ->will($this->returnValue($this->getMock('Symfony\Component\Security\Core\User\UserInterface'))) ; $provider->authenticate($this->getSupportedToken()); @@ -121,7 +121,7 @@ public function testAuthenticateWhenPostCheckAuthenticationFails() $provider = $this->getProvider(); $provider->expects($this->once()) ->method('retrieveUser') - ->will($this->returnValue($this->getMock('Symfony\Component\Security\Core\User\AccountInterface'))) + ->will($this->returnValue($this->getMock('Symfony\Component\Security\Core\User\UserInterface'))) ; $provider->expects($this->once()) ->method('checkAuthentication') @@ -133,7 +133,7 @@ public function testAuthenticateWhenPostCheckAuthenticationFails() public function testAuthenticate() { - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $user->expects($this->once()) ->method('getRoles') ->will($this->returnValue(array('ROLE_FOO'))) @@ -177,7 +177,7 @@ protected function getSupportedToken() protected function getProvider($userChecker = false, $hide = true) { if (false === $userChecker) { - $userChecker = $this->getMock('Symfony\Component\Security\Core\User\AccountCheckerInterface'); + $userChecker = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface'); } return $this->getMockForAbstractClass('Symfony\Component\Security\Core\Authentication\Provider\UserAuthenticationProvider', array($userChecker, 'key', $hide)); diff --git a/tests/Symfony/Tests/Component/Security/Core/Authentication/Token/TokenTest.php b/tests/Symfony/Tests/Component/Security/Core/Authentication/Token/AbstractTokenTest.php similarity index 54% rename from tests/Symfony/Tests/Component/Security/Core/Authentication/Token/TokenTest.php rename to tests/Symfony/Tests/Component/Security/Core/Authentication/Token/AbstractTokenTest.php index 68cd9863af7a4..9b6def7e52abe 100644 --- a/tests/Symfony/Tests/Component/Security/Core/Authentication/Token/TokenTest.php +++ b/tests/Symfony/Tests/Component/Security/Core/Authentication/Token/AbstractTokenTest.php @@ -11,17 +11,8 @@ namespace Symfony\Tests\Component\Security\Core\Authentication\Token; -use Symfony\Component\Security\Core\Authentication\Token\Token as BaseToken; use Symfony\Component\Security\Core\Role\Role; -class Token extends BaseToken -{ - public function setCredentials($credentials) - { - $this->credentials = $credentials; - } -} - class TestUser { protected $name; @@ -37,33 +28,28 @@ public function __toString() } } -class TokenTest extends \PHPUnit_Framework_TestCase +class AbstractTokenTest extends \PHPUnit_Framework_TestCase { - public function testMagicToString() + public function testGetUsername() { - $token = new Token(array('ROLE_FOO')); + $token = $this->getToken(array('ROLE_FOO')); $token->setUser('fabien'); - $this->assertEquals('fabien', (string) $token); + $this->assertEquals('fabien', $token->getUsername()); $token->setUser(new TestUser('fabien')); - $this->assertEquals('fabien', (string) $token); + $this->assertEquals('fabien', $token->getUsername()); - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $user->expects($this->once())->method('getUsername')->will($this->returnValue('fabien')); - $token->setUser($user); - $this->assertEquals('fabien', (string) $token); + $this->assertEquals('fabien', $token->getUsername()); } public function testEraseCredentials() { - $token = new Token(array('ROLE_FOO')); - - $credentials = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); - $credentials->expects($this->once())->method('eraseCredentials'); - $token->setCredentials($credentials); + $token = $this->getToken(array('ROLE_FOO')); - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $user->expects($this->once())->method('eraseCredentials'); $token->setUser($user); @@ -76,10 +62,13 @@ public function testEraseCredentials() */ public function testSerialize() { - $token = new Token(array('ROLE_FOO')); + $token = $this->getToken(array('ROLE_FOO')); $token->setAttributes(array('foo' => 'bar')); - $this->assertEquals($token, unserialize(serialize($token))); + $uToken = unserialize(serialize($token)); + + $this->assertEquals($token->getRoles(), $uToken->getRoles()); + $this->assertEquals($token->getAttributes(), $uToken->getAttributes()); } /** @@ -87,27 +76,13 @@ public function testSerialize() */ public function testConstructor() { - $token = new Token(array('ROLE_FOO')); - $this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles()); - - $token = new Token(array(new Role('ROLE_FOO'))); + $token = $this->getToken(array('ROLE_FOO')); $this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles()); - $token = new Token(array(new Role('ROLE_FOO'), 'ROLE_BAR')); - $this->assertEquals(array(new Role('ROLE_FOO'), new Role('ROLE_BAR')), $token->getRoles()); - } - - /** - * @covers Symfony\Component\Security\Core\Authentication\Token\Token::addRole - * @covers Symfony\Component\Security\Core\Authentication\Token\Token::getRoles - */ - public function testAddRole() - { - $token = new Token(); - $token->addRole(new Role('ROLE_FOO')); + $token = $this->getToken(array(new Role('ROLE_FOO'))); $this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles()); - $token->addRole(new Role('ROLE_BAR')); + $token = $this->getToken(array(new Role('ROLE_FOO'), 'ROLE_BAR')); $this->assertEquals(array(new Role('ROLE_FOO'), new Role('ROLE_BAR')), $token->getRoles()); } @@ -117,7 +92,7 @@ public function testAddRole() */ public function testAuthenticatedFlag() { - $token = new Token(); + $token = $this->getToken(); $this->assertFalse($token->isAuthenticated()); $token->setAuthenticated(true); @@ -127,42 +102,6 @@ public function testAuthenticatedFlag() $this->assertFalse($token->isAuthenticated()); } - /** - * @covers Symfony\Component\Security\Core\Authentication\Token\Token::isImmutable - * @covers Symfony\Component\Security\Core\Authentication\Token\Token::setImmutable - */ - public function testImmutableFlag() - { - $token = new Token(); - $this->assertFalse($token->isImmutable()); - - $token->setImmutable(); - $this->assertTrue($token->isImmutable()); - } - - /** - * @expectedException \LogicException - * @dataProvider getImmutabilityTests - */ - public function testImmutabilityIsEnforced($setter, $value) - { - $token = new Token(); - $token->setImmutable(true); - $token->$setter($value); - } - - public function getImmutabilityTests() - { - return array( - array('setUser', 'foo'), - array('eraseCredentials', null), - array('setAuthenticated', true), - array('setAuthenticated', false), - array('addRole', new Role('foo')), - array('setRoles', array('foo', 'asdf')), - ); - } - /** * @covers Symfony\Component\Security\Core\Authentication\Token\Token::getAttributes * @covers Symfony\Component\Security\Core\Authentication\Token\Token::setAttributes @@ -173,7 +112,7 @@ public function getImmutabilityTests() public function testAttributes() { $attributes = array('foo' => 'bar'); - $token = new Token(); + $token = $this->getToken(); $token->setAttributes($attributes); $this->assertEquals($attributes, $token->getAttributes(), '->getAttributes() returns the token attributes'); @@ -191,4 +130,107 @@ public function testAttributes() $this->assertEquals('This token has no "foobar" attribute.', $e->getMessage(), '->getAttribute() throws an \InvalidArgumentException exception when the attribute does not exist'); } } + + /** + * @dataProvider getUsers + */ + public function testSetUser($user) + { + $token = $this->getToken(); + $token->setUser($user); + $this->assertSame($user, $token->getUser()); + } + + public function getUsers() + { + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); + $user + ->expects($this->any()) + ->method('equals') + ->will($this->returnValue(true)) + ; + + return array( + array($user), + array(new TestUser('foo')), + array('foo'), + ); + } + + /** + * @dataProvider getUserChanges + */ + public function testSetUserSetsAuthenticatedToFalseWhenUserChanges($firstUser, $secondUser) + { + $token = $this->getToken(); + $token->setAuthenticated(true); + $this->assertTrue($token->isAuthenticated()); + + $token->setUser($firstUser); + $this->assertTrue($token->isAuthenticated()); + + $token->setUser($secondUser); + $this->assertFalse($token->isAuthenticated()); + } + + public function getUserChanges() + { + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); + $user + ->expects($this->any()) + ->method('equals') + ->will($this->returnValue(false)) + ; + + return array( + array( + 'foo', 'bar', + ), + array( + 'foo', new TestUser('bar'), + ), + array( + 'foo', $user, + ), + array( + $user, $user, + ), + array( + $user, 'foo' + ), + array( + $user, new TestUser('foo'), + ), + array( + new TestUser('foo'), new TestUser('bar'), + ), + array( + new TestUser('foo'), 'bar', + ), + array( + new TestUser('foo'), $user, + ), + ); + } + + /** + * @dataProvider getUsers + */ + public function testSetUserDoesNotSetAuthenticatedToFalseWhenUserDoesNotChange($user) + { + $token = $this->getToken(); + $token->setAuthenticated(true); + $this->assertTrue($token->isAuthenticated()); + + $token->setUser($user); + $this->assertTrue($token->isAuthenticated()); + + $token->setUser($user); + $this->assertTrue($token->isAuthenticated()); + } + + protected function getToken(array $roles = array()) + { + return $this->getMockForAbstractClass('Symfony\Component\Security\Core\Authentication\Token\AbstractToken', array($roles)); + } } diff --git a/tests/Symfony/Tests/Component/Security/Core/Authentication/Token/RememerMeTokenTest.php b/tests/Symfony/Tests/Component/Security/Core/Authentication/Token/RememerMeTokenTest.php index 89071ca0b6c09..1a614519c9bd5 100644 --- a/tests/Symfony/Tests/Component/Security/Core/Authentication/Token/RememerMeTokenTest.php +++ b/tests/Symfony/Tests/Component/Security/Core/Authentication/Token/RememerMeTokenTest.php @@ -62,17 +62,14 @@ public function getUserArguments() public function testPersistentToken() { - $token = new RememberMeToken($this->getUser(), 'fookey', 'foo'); - $persistentToken = $this->getMock('Symfony\Component\Security\Core\Authentication\RememberMe\PersistentTokenInterface'); + $token = new RememberMeToken($this->getUser(), 'fookey', 'foo', $persistentToken = $this->getMock('Symfony\Component\Security\Core\Authentication\RememberMe\PersistentTokenInterface')); - $this->assertNull($token->getPersistentToken()); - $token->setPersistentToken($persistentToken); $this->assertSame($persistentToken, $token->getPersistentToken()); } protected function getUser($roles = array('ROLE_FOO')) { - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $user ->expects($this->once()) ->method('getRoles') diff --git a/tests/Symfony/Tests/Component/Security/Core/Authorization/AccessDecisionManagerTest.php b/tests/Symfony/Tests/Component/Security/Core/Authorization/AccessDecisionManagerTest.php index 77204b6df1ff5..0ef6ccb306167 100644 --- a/tests/Symfony/Tests/Component/Security/Core/Authorization/AccessDecisionManagerTest.php +++ b/tests/Symfony/Tests/Component/Security/Core/Authorization/AccessDecisionManagerTest.php @@ -47,27 +47,11 @@ public function testSupportsAttribute() } /** - * @expectedException LogicException + * @expectedException InvalidArgumentException */ public function testSetVotersEmpty() { - $manager = new AccessDecisionManager(); - $manager->setVoters(array()); - } - - public function testSetVoters() - { - $manager = new AccessDecisionManager(); - $manager->setVoters(array($voter = $this->getVoterSupportsAttribute(true))); - - $this->assertSame(array($voter), $manager->getVoters()); - } - - public function testGetVoters() - { - $manager = new AccessDecisionManager(array($voter = $this->getVoterSupportsAttribute(true))); - - $this->assertSame(array($voter), $manager->getVoters()); + $manager = new AccessDecisionManager(array()); } /** @@ -88,7 +72,6 @@ public function getStrategyTests() array('affirmative', $this->getVoters(1, 0, 0), false, true, true), array('affirmative', $this->getVoters(1, 2, 0), false, true, true), array('affirmative', $this->getVoters(0, 1, 0), false, true, false), - array('affirmative', $this->getVoters(0, 0, 0), false, true, false), array('affirmative', $this->getVoters(0, 0, 1), false, true, false), array('affirmative', $this->getVoters(0, 0, 1), true, true, true), @@ -97,10 +80,8 @@ public function getStrategyTests() array('consensus', $this->getVoters(1, 2, 0), false, true, false), array('consensus', $this->getVoters(2, 1, 0), false, true, true), - array('consensus', $this->getVoters(0, 0, 0), false, true, false), array('consensus', $this->getVoters(0, 0, 1), false, true, false), - array('consensus', $this->getVoters(0, 0, 0), true, true, true), array('consensus', $this->getVoters(0, 0, 1), true, true, true), array('consensus', $this->getVoters(2, 2, 0), false, true, true), @@ -114,9 +95,6 @@ public function getStrategyTests() array('unanimous', $this->getVoters(1, 0, 1), false, true, true), array('unanimous', $this->getVoters(1, 1, 0), false, true, false), - array('unanimous', $this->getVoters(0, 0, 0), false, true, false), - array('unanimous', $this->getVoters(0, 0, 0), true, true, true), - array('unanimous', $this->getVoters(0, 0, 2), false, true, false), array('unanimous', $this->getVoters(0, 0, 2), true, true, true), ); diff --git a/tests/Symfony/Tests/Component/Security/Core/Encoder/EncoderFactoryTest.php b/tests/Symfony/Tests/Component/Security/Core/Encoder/EncoderFactoryTest.php index b480dda43fcae..5393a985861d1 100644 --- a/tests/Symfony/Tests/Component/Security/Core/Encoder/EncoderFactoryTest.php +++ b/tests/Symfony/Tests/Component/Security/Core/Encoder/EncoderFactoryTest.php @@ -18,12 +18,12 @@ class EncoderFactoryTest extends \PHPUnit_Framework_TestCase { public function testGetEncoderWithMessageDigestEncoder() { - $factory = new EncoderFactory(array('Symfony\Component\Security\Core\User\AccountInterface' => array( + $factory = new EncoderFactory(array('Symfony\Component\Security\Core\User\UserInterface' => array( 'class' => 'Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder', 'arguments' => array('sha512', true, 5), ))); - $encoder = $factory->getEncoder($this->getMock('Symfony\Component\Security\Core\User\AccountInterface')); + $encoder = $factory->getEncoder($this->getMock('Symfony\Component\Security\Core\User\UserInterface')); $expectedEncoder = new MessageDigestPasswordEncoder('sha512', true, 5); $this->assertEquals($expectedEncoder->encodePassword('foo', 'moo'), $encoder->encodePassword('foo', 'moo')); @@ -32,10 +32,10 @@ public function testGetEncoderWithMessageDigestEncoder() public function testGetEncoderWithService() { $factory = new EncoderFactory(array( - 'Symfony\Component\Security\Core\User\AccountInterface' => new MessageDigestPasswordEncoder('sha1'), + 'Symfony\Component\Security\Core\User\UserInterface' => new MessageDigestPasswordEncoder('sha1'), )); - $encoder = $factory->getEncoder($this->getMock('Symfony\Component\Security\Core\User\AccountInterface')); + $encoder = $factory->getEncoder($this->getMock('Symfony\Component\Security\Core\User\UserInterface')); $expectedEncoder = new MessageDigestPasswordEncoder('sha1'); $this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', '')); diff --git a/tests/Symfony/Tests/Component/Security/Core/SecurityContextTest.php b/tests/Symfony/Tests/Component/Security/Core/SecurityContextTest.php index 353d5164b748e..f041cdb2386cf 100644 --- a/tests/Symfony/Tests/Component/Security/Core/SecurityContextTest.php +++ b/tests/Symfony/Tests/Component/Security/Core/SecurityContextTest.php @@ -37,7 +37,7 @@ public function testVoteAuthenticatesTokenIfNecessary() ->will($this->returnValue(true)) ; - $this->assertTrue($context->vote('foo')); + $this->assertTrue($context->isGranted('foo')); $this->assertSame($newToken, $context->getToken()); } @@ -51,10 +51,10 @@ public function testVoteWithoutAuthenticationToken() $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface') ); - $context->vote('ROLE_FOO'); + $context->isGranted('ROLE_FOO'); } - public function testVote() + public function testIsGranted() { $manager = $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface'); $manager->expects($this->once())->method('decide')->will($this->returnValue(false)); @@ -65,7 +65,7 @@ public function testVote() ->method('isAuthenticated') ->will($this->returnValue(true)) ; - $this->assertFalse($context->vote('ROLE_FOO')); + $this->assertFalse($context->isGranted('ROLE_FOO')); $manager = $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface'); $manager->expects($this->once())->method('decide')->will($this->returnValue(true)); @@ -76,7 +76,7 @@ public function testVote() ->method('isAuthenticated') ->will($this->returnValue(true)) ; - $this->assertTrue($context->vote('ROLE_FOO')); + $this->assertTrue($context->isGranted('ROLE_FOO')); } public function testGetSetToken() diff --git a/tests/Symfony/Tests/Component/Security/Core/User/AccountCheckerTest.php b/tests/Symfony/Tests/Component/Security/Core/User/AccountCheckerTest.php index 24f98d4b13f2a..001e1ed8fbd05 100644 --- a/tests/Symfony/Tests/Component/Security/Core/User/AccountCheckerTest.php +++ b/tests/Symfony/Tests/Component/Security/Core/User/AccountCheckerTest.php @@ -11,22 +11,22 @@ namespace Symfony\Tests\Component\Security\Core\User; -use Symfony\Component\Security\Core\User\AccountChecker; +use Symfony\Component\Security\Core\User\UserChecker; -class AccountCheckerTest extends \PHPUnit_Framework_TestCase +class UserCheckerTest extends \PHPUnit_Framework_TestCase { - public function testCheckPreAuthNotAdvancedAccountInterface() + public function testCheckPreAuthNotAdvancedUserInterface() { - $checker = new AccountChecker(); + $checker = new UserChecker(); - $this->assertNull($checker->checkPreAuth($this->getMock('Symfony\Component\Security\Core\User\AccountInterface'))); + $this->assertNull($checker->checkPreAuth($this->getMock('Symfony\Component\Security\Core\User\UserInterface'))); } public function testCheckPreAuthPass() { - $checker = new AccountChecker(); + $checker = new UserChecker(); - $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedAccountInterface'); + $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedUserInterface'); $account->expects($this->once())->method('isCredentialsNonExpired')->will($this->returnValue(true)); $this->assertNull($checker->checkPreAuth($account)); @@ -37,26 +37,26 @@ public function testCheckPreAuthPass() */ public function testCheckPreAuthCredentialsExpired() { - $checker = new AccountChecker(); + $checker = new UserChecker(); - $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedAccountInterface'); + $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedUserInterface'); $account->expects($this->once())->method('isCredentialsNonExpired')->will($this->returnValue(false)); $checker->checkPreAuth($account); } - public function testCheckPostAuthNotAdvancedAccountInterface() + public function testCheckPostAuthNotAdvancedUserInterface() { - $checker = new AccountChecker(); + $checker = new UserChecker(); - $this->assertNull($checker->checkPostAuth($this->getMock('Symfony\Component\Security\Core\User\AccountInterface'))); + $this->assertNull($checker->checkPostAuth($this->getMock('Symfony\Component\Security\Core\User\UserInterface'))); } public function testCheckPostAuthPass() { - $checker = new AccountChecker(); + $checker = new UserChecker(); - $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedAccountInterface'); + $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedUserInterface'); $account->expects($this->once())->method('isAccountNonLocked')->will($this->returnValue(true)); $account->expects($this->once())->method('isEnabled')->will($this->returnValue(true)); $account->expects($this->once())->method('isAccountNonExpired')->will($this->returnValue(true)); @@ -69,9 +69,9 @@ public function testCheckPostAuthPass() */ public function testCheckPostAuthAccountLocked() { - $checker = new AccountChecker(); + $checker = new UserChecker(); - $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedAccountInterface'); + $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedUserInterface'); $account->expects($this->once())->method('isAccountNonLocked')->will($this->returnValue(false)); $checker->checkPostAuth($account); @@ -82,9 +82,9 @@ public function testCheckPostAuthAccountLocked() */ public function testCheckPostAuthDisabled() { - $checker = new AccountChecker(); + $checker = new UserChecker(); - $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedAccountInterface'); + $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedUserInterface'); $account->expects($this->once())->method('isAccountNonLocked')->will($this->returnValue(true)); $account->expects($this->once())->method('isEnabled')->will($this->returnValue(false)); @@ -96,9 +96,9 @@ public function testCheckPostAuthDisabled() */ public function testCheckPostAuthAccountExpired() { - $checker = new AccountChecker(); + $checker = new UserChecker(); - $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedAccountInterface'); + $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedUserInterface'); $account->expects($this->once())->method('isAccountNonLocked')->will($this->returnValue(true)); $account->expects($this->once())->method('isEnabled')->will($this->returnValue(true)); $account->expects($this->once())->method('isAccountNonExpired')->will($this->returnValue(false)); diff --git a/tests/Symfony/Tests/Component/Security/Core/User/ChainUserProviderTest.php b/tests/Symfony/Tests/Component/Security/Core/User/ChainUserProviderTest.php index 5d2d5bc9df7d4..4c3dabf69986b 100644 --- a/tests/Symfony/Tests/Component/Security/Core/User/ChainUserProviderTest.php +++ b/tests/Symfony/Tests/Component/Security/Core/User/ChainUserProviderTest.php @@ -2,7 +2,7 @@ namespace Symfony\Tests\Component\Security\Core\User; -use Symfony\Component\Security\Core\Exception\UnsupportedAccountException; +use Symfony\Component\Security\Core\Exception\UnsupportedUserException; use Symfony\Component\Security\Core\User\ChainUserProvider; @@ -57,47 +57,47 @@ public function testLoadUserByUsernameThrowsUsernameNotFoundException() $provider->loadUserByUsername('foo'); } - public function testLoadUserByAccount() + public function testloadUser() { $provider1 = $this->getProvider(); $provider1 ->expects($this->once()) - ->method('loadUserByAccount') - ->will($this->throwException(new UnsupportedAccountException('unsupported'))) + ->method('loadUser') + ->will($this->throwException(new UnsupportedUserException('unsupported'))) ; $provider2 = $this->getProvider(); $provider2 ->expects($this->once()) - ->method('loadUserByAccount') + ->method('loadUser') ->will($this->returnValue($account = $this->getAccount())) ; $provider = new ChainUserProvider(array($provider1, $provider2)); - $this->assertSame($account, $provider->loadUserByAccount($this->getAccount())); + $this->assertSame($account, $provider->loadUser($this->getAccount())); } /** - * @expectedException Symfony\Component\Security\Core\Exception\UnsupportedAccountException + * @expectedException Symfony\Component\Security\Core\Exception\UnsupportedUserException */ - public function testLoadUserByAccountThrowsUnsupportedAccountException() + public function testloadUserThrowsUnsupportedUserException() { $provider1 = $this->getProvider(); $provider1 ->expects($this->once()) - ->method('loadUserByAccount') - ->will($this->throwException(new UnsupportedAccountException('unsupported'))) + ->method('loadUser') + ->will($this->throwException(new UnsupportedUserException('unsupported'))) ; $provider2 = $this->getProvider(); $provider2 ->expects($this->once()) - ->method('loadUserByAccount') - ->will($this->throwException(new UnsupportedAccountException('unsupported'))) + ->method('loadUser') + ->will($this->throwException(new UnsupportedUserException('unsupported'))) ; $provider = new ChainUserProvider(array($provider1, $provider2)); - $provider->loadUserByAccount($this->getAccount()); + $provider->loadUser($this->getAccount()); } public function testSupportsClass() @@ -146,7 +146,7 @@ public function testSupportsClassWhenNotSupported() protected function getAccount() { - return $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + return $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); } protected function getProvider() diff --git a/tests/Symfony/Tests/Component/Security/Core/User/UserTest.php b/tests/Symfony/Tests/Component/Security/Core/User/UserTest.php index b248a81680e32..477bd929b46c3 100644 --- a/tests/Symfony/Tests/Component/Security/Core/User/UserTest.php +++ b/tests/Symfony/Tests/Component/Security/Core/User/UserTest.php @@ -123,13 +123,4 @@ public function testEraseCredentials() $user->eraseCredentials(); $this->assertEquals('superpass', $user->getPassword()); } - - /** - * @covers Symfony\Component\Security\Core\User\User::__toString - */ - public function testMagicToString() - { - $user = new User('fabien', 'superpass'); - $this->assertEquals('fabien', (string) $user); - } } diff --git a/tests/Symfony/Tests/Component/Security/Http/RememberMe/PersistentTokenBasedRememberMeServicesTest.php b/tests/Symfony/Tests/Component/Security/Http/RememberMe/PersistentTokenBasedRememberMeServicesTest.php index 82ac1a8ee50fa..bdaa053660efd 100644 --- a/tests/Symfony/Tests/Component/Security/Http/RememberMe/PersistentTokenBasedRememberMeServicesTest.php +++ b/tests/Symfony/Tests/Component/Security/Http/RememberMe/PersistentTokenBasedRememberMeServicesTest.php @@ -142,7 +142,7 @@ public function testAutoLoginDoesNotAcceptAnExpiredCookie() public function testAutoLogin() { - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $user ->expects($this->once()) ->method('getRoles') @@ -269,7 +269,7 @@ public function testLoginSuccessRenewsRememberMeTokenWhenUsedForLogin() $request = new Request; $response = new Response; - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $user ->expects($this->once()) ->method('getRoles') @@ -315,7 +315,7 @@ public function testLoginSuccessThrowsExceptionWhenRememberMeTokenDoesNotContain $request = new Request; $response = new Response; - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $user ->expects($this->once()) ->method('getRoles') @@ -338,7 +338,7 @@ public function testLoginSuccessSetsCookieWhenLoggedInWithNonRememberMeTokenInte $request = new Request; $response = new Response; - $account = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $account = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $account ->expects($this->once()) ->method('getUsername') diff --git a/tests/Symfony/Tests/Component/Security/Http/RememberMe/RememberMeServicesTest.php b/tests/Symfony/Tests/Component/Security/Http/RememberMe/RememberMeServicesTest.php index 05c29cfef88a6..68246fceee775 100644 --- a/tests/Symfony/Tests/Component/Security/Http/RememberMe/RememberMeServicesTest.php +++ b/tests/Symfony/Tests/Component/Security/Http/RememberMe/RememberMeServicesTest.php @@ -86,12 +86,12 @@ public function testLoginFail() $this->assertTrue($response->headers->getCookie('foo')->isCleared()); } - public function testLoginSuccessIsNotProcessedWhenTokenDoesNotContainAccountInterfaceImplementation() + public function testLoginSuccessIsNotProcessedWhenTokenDoesNotContainUserInterfaceImplementation() { $service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => true)); $request = new Request; $response = new Response; - $account = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $account = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'); $token ->expects($this->once()) @@ -114,7 +114,7 @@ public function testLoginSuccessIsNotProcessedWhenRememberMeIsNotRequested() $service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => false, 'remember_me_parameter' => 'foo')); $request = new Request; $response = new Response; - $account = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $account = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'); $token ->expects($this->once()) @@ -138,7 +138,7 @@ public function testLoginSuccessWhenRememberMeAlwaysIsTrue() $service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => true)); $request = new Request; $response = new Response; - $account = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $account = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'); $token ->expects($this->once()) @@ -165,7 +165,7 @@ public function testLoginSuccessWhenRememberMeParameterIsPositive($value) $request = new Request; $request->request->set('foo', $value); $response = new Response; - $account = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $account = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'); $token ->expects($this->once()) diff --git a/tests/Symfony/Tests/Component/Security/Http/RememberMe/TokenBasedRememberMeServicesTest.php b/tests/Symfony/Tests/Component/Security/Http/RememberMe/TokenBasedRememberMeServicesTest.php index 54320b5652c8b..daaad7d0917eb 100644 --- a/tests/Symfony/Tests/Component/Security/Http/RememberMe/TokenBasedRememberMeServicesTest.php +++ b/tests/Symfony/Tests/Component/Security/Http/RememberMe/TokenBasedRememberMeServicesTest.php @@ -65,7 +65,7 @@ public function testAutoLoginDoesNotAcceptCookieWithInvalidHash() $request = new Request; $request->cookies->set('foo', base64_encode('class:'.base64_encode('foouser').':123456789:fooHash')); - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $user ->expects($this->once()) ->method('getPassword') @@ -93,7 +93,7 @@ public function testAutoLoginDoesNotAcceptAnExpiredCookie() $request = new Request; $request->cookies->set('foo', $this->getCookie('fooclass', 'foouser', time() - 1, 'foopass')); - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $user ->expects($this->once()) ->method('getPassword') @@ -112,7 +112,7 @@ public function testAutoLoginDoesNotAcceptAnExpiredCookie() public function testAutoLogin() { - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $user ->expects($this->once()) ->method('getRoles') @@ -182,7 +182,7 @@ public function testLoginSuccessDoesNotRenewRememberMeToken() $request = new Request; $response = new Response; - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $user ->expects($this->once()) ->method('getRoles') @@ -198,7 +198,7 @@ public function testLoginSuccessDoesNotRenewRememberMeToken() $this->assertFalse($response->headers->hasCookie('foo')); } - public function testLoginSuccessIgnoresTokensWhichDoNotContainAnAccountInterfaceImplementation() + public function testLoginSuccessIgnoresTokensWhichDoNotContainAnUserInterfaceImplementation() { $service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => true)); $request = new Request; @@ -224,7 +224,7 @@ public function testLoginSuccess() $response = new Response; $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'); - $user = $this->getMock('Symfony\Component\Security\Core\User\AccountInterface'); + $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); $user ->expects($this->once()) ->method('getPassword')