Upgrade 1-11.38

This commit is contained in:
xesmyd
2026-03-30 14:10:30 +02:00
parent f2a7e6d1fc
commit ac648ef29d
24665 changed files with 69682 additions and 2205004 deletions
@@ -11,15 +11,15 @@
namespace Symfony\Component\Security\Core\Authentication;
use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
use Symfony\Component\Security\Core\Event\AuthenticationEvent;
use Symfony\Component\Security\Core\AuthenticationEvents;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\AuthenticationEvents;
use Symfony\Component\Security\Core\Event\AuthenticationEvent;
use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\ProviderNotFoundException;
use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* AuthenticationProviderManager uses a list of AuthenticationProviderInterface
@@ -35,25 +35,17 @@ class AuthenticationProviderManager implements AuthenticationManagerInterface
private $eventDispatcher;
/**
* Constructor.
*
* @param AuthenticationProviderInterface[] $providers An array of AuthenticationProviderInterface instances
* @param bool $eraseCredentials Whether to erase credentials after authentication or not
* @param iterable|AuthenticationProviderInterface[] $providers An iterable with AuthenticationProviderInterface instances as values
* @param bool $eraseCredentials Whether to erase credentials after authentication or not
*
* @throws \InvalidArgumentException
*/
public function __construct(array $providers, $eraseCredentials = true)
public function __construct($providers, $eraseCredentials = true)
{
if (!$providers) {
throw new \InvalidArgumentException('You must at least add one authentication provider.');
}
foreach ($providers as $provider) {
if (!$provider instanceof AuthenticationProviderInterface) {
throw new \InvalidArgumentException(sprintf('Provider "%s" must implement the AuthenticationProviderInterface.', get_class($provider)));
}
}
$this->providers = $providers;
$this->eraseCredentials = (bool) $eraseCredentials;
}
@@ -72,6 +64,10 @@ class AuthenticationProviderManager implements AuthenticationManagerInterface
$result = null;
foreach ($this->providers as $provider) {
if (!$provider instanceof AuthenticationProviderInterface) {
throw new \InvalidArgumentException(sprintf('Provider "%s" must implement the AuthenticationProviderInterface.', \get_class($provider)));
}
if (!$provider->supports($token)) {
continue;
}
@@ -104,7 +100,7 @@ class AuthenticationProviderManager implements AuthenticationManagerInterface
}
if (null === $lastException) {
$lastException = new ProviderNotFoundException(sprintf('No Authentication Provider found for token of class "%s".', get_class($token)));
$lastException = new ProviderNotFoundException(sprintf('No Authentication Provider found for token of class "%s".', \get_class($token)));
}
if (null !== $this->eventDispatcher) {
@@ -24,8 +24,6 @@ class AuthenticationTrustResolver implements AuthenticationTrustResolverInterfac
private $rememberMeClass;
/**
* Constructor.
*
* @param string $anonymousClass
* @param string $rememberMeClass
*/
@@ -26,8 +26,6 @@ interface AuthenticationTrustResolverInterface
*
* If null is passed, the method must return false.
*
* @param TokenInterface $token
*
* @return bool
*/
public function isAnonymous(TokenInterface $token = null);
@@ -36,8 +34,6 @@ interface AuthenticationTrustResolverInterface
* Resolves whether the passed token implementation is authenticated
* using remember-me capabilities.
*
* @param TokenInterface $token
*
* @return bool
*/
public function isRememberMe(TokenInterface $token = null);
@@ -45,8 +41,6 @@ interface AuthenticationTrustResolverInterface
/**
* Resolves whether the passed token implementation is fully authenticated.
*
* @param TokenInterface $token
*
* @return bool
*/
public function isFullFledged(TokenInterface $token = null);
@@ -11,9 +11,10 @@
namespace Symfony\Component\Security\Core\Authentication\Provider;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
/**
* AnonymousAuthenticationProvider validates AnonymousToken instances.
@@ -31,8 +32,6 @@ class AnonymousAuthenticationProvider implements AuthenticationProviderInterface
private $secret;
/**
* Constructor.
*
* @param string $secret The secret shared with the AnonymousToken
*/
public function __construct($secret)
@@ -46,7 +45,7 @@ class AnonymousAuthenticationProvider implements AuthenticationProviderInterface
public function authenticate(TokenInterface $token)
{
if (!$this->supports($token)) {
return;
throw new AuthenticationException('The token is not supported by this authentication provider.');
}
if ($this->secret !== $token->getSecret()) {
@@ -11,8 +11,8 @@
namespace Symfony\Component\Security\Core\Authentication\Provider;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* AuthenticationProviderInterface is the interface for all authentication
@@ -34,8 +34,6 @@ interface AuthenticationProviderInterface extends AuthenticationManagerInterface
/**
* Checks whether this provider supports the given token.
*
* @param TokenInterface $token A TokenInterface instance
*
* @return bool true if the implementation supports the Token, false otherwise
*/
public function supports(TokenInterface $token);
@@ -11,14 +11,14 @@
namespace Symfony\Component\Security\Core\Authentication\Provider;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
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;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
/**
* DaoAuthenticationProvider uses a UserProviderInterface to retrieve the user
@@ -32,8 +32,6 @@ class DaoAuthenticationProvider extends UserAuthenticationProvider
private $userProvider;
/**
* Constructor.
*
* @param UserProviderInterface $userProvider An UserProviderInterface instance
* @param UserCheckerInterface $userChecker An UserCheckerInterface instance
* @param string $providerKey The provider key
@@ -63,7 +61,7 @@ class DaoAuthenticationProvider extends UserAuthenticationProvider
throw new BadCredentialsException('The presented password cannot be empty.');
}
if (!$this->encoderFactory->getEncoder($user)->isPasswordValid($user->getPassword(), $presentedPassword, $user->getSalt())) {
if (null === $user->getPassword() || !$this->encoderFactory->getEncoder($user)->isPasswordValid($user->getPassword(), $presentedPassword, $user->getSalt())) {
throw new BadCredentialsException('The presented password is invalid.');
}
}
@@ -11,14 +11,14 @@
namespace Symfony\Component\Security\Core\Authentication\Provider;
use Symfony\Component\Ldap\Exception\ConnectionException;
use Symfony\Component\Ldap\LdapInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Ldap\LdapInterface;
use Symfony\Component\Ldap\Exception\ConnectionException;
/**
* LdapBindAuthenticationProvider authenticates a user against an LDAP server.
@@ -33,10 +33,9 @@ class LdapBindAuthenticationProvider extends UserAuthenticationProvider
private $userProvider;
private $ldap;
private $dnString;
private $queryString;
/**
* Constructor.
*
* @param UserProviderInterface $userProvider A UserProvider
* @param UserCheckerInterface $userChecker A UserChecker
* @param string $providerKey The provider key
@@ -53,13 +52,23 @@ class LdapBindAuthenticationProvider extends UserAuthenticationProvider
$this->dnString = $dnString;
}
/**
* Set a query string to use in order to find a DN for the username.
*
* @param string $queryString
*/
public function setQueryString($queryString)
{
$this->queryString = $queryString;
}
/**
* {@inheritdoc}
*/
protected function retrieveUser($username, UsernamePasswordToken $token)
{
if (AuthenticationProviderInterface::USERNAME_NONE_PROVIDED === $username) {
throw new UsernameNotFoundException('Username can not be null');
throw new UsernameNotFoundException('Username can not be null.');
}
return $this->userProvider->loadUserByUsername($username);
@@ -73,13 +82,24 @@ class LdapBindAuthenticationProvider extends UserAuthenticationProvider
$username = $token->getUsername();
$password = $token->getCredentials();
if ('' === $password) {
if ('' === (string) $password) {
throw new BadCredentialsException('The presented password must not be empty.');
}
try {
$username = $this->ldap->escape($username, '', LdapInterface::ESCAPE_DN);
$dn = str_replace('{username}', $username, $this->dnString);
if ($this->queryString) {
$username = $this->ldap->escape($username, '', LdapInterface::ESCAPE_FILTER);
$query = str_replace('{username}', $username, $this->queryString);
$result = $this->ldap->query($this->dnString, $query)->execute();
if (1 !== $result->count()) {
throw new BadCredentialsException('The presented username is invalid.');
}
$dn = $result[0]->getDn();
} else {
$username = $this->ldap->escape($username, '', LdapInterface::ESCAPE_DN);
$dn = str_replace('{username}', $username, $this->dnString);
}
$this->ldap->bind($dn, $password);
} catch (ConnectionException $e) {
@@ -11,11 +11,12 @@
namespace Symfony\Component\Security\Core\Authentication\Provider;
use Symfony\Component\Security\Core\User\UserProviderInterface;
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;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
/**
* Processes a pre-authenticated authentication request.
@@ -33,13 +34,6 @@ class PreAuthenticatedAuthenticationProvider implements AuthenticationProviderIn
private $userChecker;
private $providerKey;
/**
* Constructor.
*
* @param UserProviderInterface $userProvider An UserProviderInterface instance
* @param UserCheckerInterface $userChecker An UserCheckerInterface instance
* @param string $providerKey The provider key
*/
public function __construct(UserProviderInterface $userProvider, UserCheckerInterface $userChecker, $providerKey)
{
$this->userProvider = $userProvider;
@@ -53,7 +47,7 @@ class PreAuthenticatedAuthenticationProvider implements AuthenticationProviderIn
public function authenticate(TokenInterface $token)
{
if (!$this->supports($token)) {
return;
throw new AuthenticationException('The token is not supported by this authentication provider.');
}
if (!$user = $token->getUser()) {
@@ -11,10 +11,13 @@
namespace Symfony\Component\Security\Core\Authentication\Provider;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\LogicException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class RememberMeAuthenticationProvider implements AuthenticationProviderInterface
{
@@ -23,8 +26,6 @@ class RememberMeAuthenticationProvider implements AuthenticationProviderInterfac
private $providerKey;
/**
* Constructor.
*
* @param UserCheckerInterface $userChecker An UserCheckerInterface interface
* @param string $secret A secret
* @param string $providerKey A provider secret
@@ -42,7 +43,7 @@ class RememberMeAuthenticationProvider implements AuthenticationProviderInterfac
public function authenticate(TokenInterface $token)
{
if (!$this->supports($token)) {
return;
throw new AuthenticationException('The token is not supported by this authentication provider.');
}
if ($this->secret !== $token->getSecret()) {
@@ -50,7 +51,13 @@ class RememberMeAuthenticationProvider implements AuthenticationProviderInterfac
}
$user = $token->getUser();
if (!$token->getUser() instanceof UserInterface) {
throw new LogicException(sprintf('Method "%s::getUser()" must return a "%s" instance, "%s" returned.', \get_class($token), UserInterface::class, \is_object($user) ? \get_class($user) : \gettype($user)));
}
$this->userChecker->checkPreAuth($user);
$this->userChecker->checkPostAuth($user);
$authenticatedToken = new RememberMeToken($user, $this->providerKey, $this->secret);
$authenticatedToken->setAttributes($token->getAttributes());
@@ -11,10 +11,13 @@
namespace Symfony\Component\Security\Core\Authentication\Provider;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserChecker;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
@@ -24,23 +27,34 @@ class SimpleAuthenticationProvider implements AuthenticationProviderInterface
private $simpleAuthenticator;
private $userProvider;
private $providerKey;
private $userChecker;
public function __construct(SimpleAuthenticatorInterface $simpleAuthenticator, UserProviderInterface $userProvider, $providerKey)
public function __construct(SimpleAuthenticatorInterface $simpleAuthenticator, UserProviderInterface $userProvider, $providerKey, UserCheckerInterface $userChecker = null)
{
$this->simpleAuthenticator = $simpleAuthenticator;
$this->userProvider = $userProvider;
$this->providerKey = $providerKey;
$this->userChecker = $userChecker ?: new UserChecker();
}
public function authenticate(TokenInterface $token)
{
$authToken = $this->simpleAuthenticator->authenticateToken($token, $this->userProvider, $this->providerKey);
if ($authToken instanceof TokenInterface) {
if (!$authToken instanceof TokenInterface) {
throw new AuthenticationException('Simple authenticator failed to return an authenticated token.');
}
$user = $authToken->getUser();
if (!$user instanceof UserInterface) {
return $authToken;
}
throw new AuthenticationException('Simple authenticator failed to return an authenticated token.');
$this->userChecker->checkPreAuth($user);
$this->userChecker->checkPostAuth($user);
return $authToken;
}
public function supports(TokenInterface $token)
@@ -11,15 +11,16 @@
namespace Symfony\Component\Security\Core\Authentication\Provider;
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;
use Symfony\Component\Security\Core\Exception\AuthenticationServiceException;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\AuthenticationServiceException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* UserProviderInterface retrieves users for UsernamePasswordToken tokens.
@@ -33,8 +34,6 @@ abstract class UserAuthenticationProvider implements AuthenticationProviderInter
private $providerKey;
/**
* Constructor.
*
* @param UserCheckerInterface $userChecker An UserCheckerInterface interface
* @param string $providerKey A provider key
* @param bool $hideUserNotFoundExceptions Whether to hide user not found exception or not
@@ -58,7 +57,7 @@ abstract class UserAuthenticationProvider implements AuthenticationProviderInter
public function authenticate(TokenInterface $token)
{
if (!$this->supports($token)) {
return;
throw new AuthenticationException('The token is not supported by this authentication provider.');
}
$username = $token->getUsername();
@@ -85,8 +84,8 @@ abstract class UserAuthenticationProvider implements AuthenticationProviderInter
$this->userChecker->checkPreAuth($user);
$this->checkAuthentication($user, $token);
$this->userChecker->checkPostAuth($user);
} catch (BadCredentialsException $e) {
if ($this->hideUserNotFoundExceptions) {
} catch (AuthenticationException $e) {
if ($this->hideUserNotFoundExceptions && ($e instanceof AccountStatusException || $e instanceof BadCredentialsException)) {
throw new BadCredentialsException('Bad credentials.', 0, $e);
}
@@ -110,9 +109,6 @@ abstract class UserAuthenticationProvider implements AuthenticationProviderInter
/**
* Retrieves roles from user and appends SwitchUserRole if original token contained one.
*
* @param UserInterface $user The user
* @param TokenInterface $token The token
*
* @return array The user roles
*/
private function getRoles(UserInterface $user, TokenInterface $token)
@@ -146,9 +142,6 @@ abstract class UserAuthenticationProvider implements AuthenticationProviderInter
* Does additional checks on the user and token (like validating the
* credentials).
*
* @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(UserInterface $user, UsernamePasswordToken $token);
@@ -20,7 +20,7 @@ use Symfony\Component\Security\Core\Exception\TokenNotFoundException;
*/
class InMemoryTokenProvider implements TokenProviderInterface
{
private $tokens = array();
private $tokens = [];
/**
* {@inheritdoc}
@@ -25,13 +25,10 @@ final class PersistentToken implements PersistentTokenInterface
private $lastUsed;
/**
* Constructor.
*
* @param string $class
* @param string $username
* @param string $series
* @param string $tokenValue
* @param \DateTime $lastUsed
* @param string $class
* @param string $username
* @param string $series
* @param string $tokenValue
*
* @throws \InvalidArgumentException
*/
@@ -41,9 +41,8 @@ interface TokenProviderInterface
/**
* Updates the token according to this data.
*
* @param string $series
* @param string $tokenValue
* @param \DateTime $lastUsed
* @param string $series
* @param string $tokenValue
*
* @throws TokenNotFoundException if the token is not found
*/
@@ -51,8 +50,6 @@ interface TokenProviderInterface
/**
* Creates a new token.
*
* @param PersistentTokenInterface $token
*/
public function createNewToken(PersistentTokenInterface $token);
}
@@ -11,11 +11,11 @@
namespace Symfony\Component\Security\Core\Authentication\Token;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Component\Security\Core\User\EquatableInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Base class for Token instances.
@@ -26,24 +26,22 @@ use Symfony\Component\Security\Core\User\EquatableInterface;
abstract class AbstractToken implements TokenInterface
{
private $user;
private $roles = array();
private $roles = [];
private $authenticated = false;
private $attributes = array();
private $attributes = [];
/**
* Constructor.
*
* @param (RoleInterface|string)[] $roles An array of roles
* @param (Role|string)[] $roles An array of roles
*
* @throws \InvalidArgumentException
*/
public function __construct(array $roles = array())
public function __construct(array $roles = [])
{
foreach ($roles as $role) {
if (is_string($role)) {
if (\is_string($role)) {
$role = new Role($role);
} elseif (!$role instanceof RoleInterface) {
throw new \InvalidArgumentException(sprintf('$roles must be an array of strings, or RoleInterface instances, but got %s.', gettype($role)));
throw new \InvalidArgumentException(sprintf('$roles must be an array of strings or Role instances, but got "%s".', \gettype($role)));
}
$this->roles[] = $role;
@@ -79,18 +77,11 @@ abstract class AbstractToken implements TokenInterface
}
/**
* Sets the user in the token.
*
* The user can be a UserInterface instance, or an object implementing
* a __toString method or the username as a regular string.
*
* @param string|object $user The user
*
* @throws \InvalidArgumentException
* {@inheritdoc}
*/
public function setUser($user)
{
if (!($user instanceof UserInterface || (is_object($user) && method_exists($user, '__toString')) || is_string($user))) {
if (!($user instanceof UserInterface || (\is_object($user) && method_exists($user, '__toString')) || \is_string($user))) {
throw new \InvalidArgumentException('$user must be an instanceof UserInterface, an object implementing a __toString method, or a primitive string.');
}
@@ -146,14 +137,9 @@ abstract class AbstractToken implements TokenInterface
*/
public function serialize()
{
return serialize(
array(
is_object($this->user) ? clone $this->user : $this->user,
$this->authenticated,
array_map(function ($role) { return clone $role; }, $this->roles),
$this->attributes,
)
);
$serialized = [$this->user, $this->authenticated, $this->roles, $this->attributes];
return $this->doSerialize($serialized, \func_num_args() ? func_get_arg(0) : null);
}
/**
@@ -161,7 +147,7 @@ abstract class AbstractToken implements TokenInterface
*/
public function unserialize($serialized)
{
list($this->user, $this->authenticated, $this->roles, $this->attributes) = unserialize($serialized);
list($this->user, $this->authenticated, $this->roles, $this->attributes) = \is_array($serialized) ? $serialized : unserialize($serialized);
}
/**
@@ -193,7 +179,7 @@ abstract class AbstractToken implements TokenInterface
*/
public function hasAttribute($name)
{
return array_key_exists($name, $this->attributes);
return \array_key_exists($name, $this->attributes);
}
/**
@@ -207,7 +193,7 @@ abstract class AbstractToken implements TokenInterface
*/
public function getAttribute($name)
{
if (!array_key_exists($name, $this->attributes)) {
if (!\array_key_exists($name, $this->attributes)) {
throw new \InvalidArgumentException(sprintf('This token has no "%s" attribute.', $name));
}
@@ -230,10 +216,10 @@ abstract class AbstractToken implements TokenInterface
*/
public function __toString()
{
$class = get_class($this);
$class = static::class;
$class = substr($class, strrpos($class, '\\') + 1);
$roles = array();
$roles = [];
foreach ($this->roles as $role) {
$roles[] = $role->getRole();
}
@@ -241,6 +227,19 @@ abstract class AbstractToken implements TokenInterface
return sprintf('%s(user="%s", authenticated=%s, roles="%s")', $class, $this->getUsername(), json_encode($this->authenticated), implode(', ', $roles));
}
/**
* @internal
*/
protected function doSerialize($serialized, $isCalledFromOverridingMethod)
{
if (null === $isCalledFromOverridingMethod) {
$trace = debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT, 3);
$isCalledFromOverridingMethod = isset($trace[2]['function'], $trace[2]['object']) && 'serialize' === $trace[2]['function'] && $this === $trace[2]['object'];
}
return $isCalledFromOverridingMethod ? $serialized : serialize($serialized);
}
private function hasUserChanged(UserInterface $user)
{
if (!($this->user instanceof UserInterface)) {
@@ -11,7 +11,8 @@
namespace Symfony\Component\Security\Core\Authentication\Token;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* AnonymousToken represents an anonymous token.
@@ -23,13 +24,11 @@ class AnonymousToken extends AbstractToken
private $secret;
/**
* Constructor.
*
* @param string $secret A secret used to make sure the token is created by the app and not by a malicious client
* @param string|object $user The user can be a UserInterface instance, or an object implementing a __toString method or the username as a regular string
* @param RoleInterface[] $roles An array of roles
* @param string $secret A secret used to make sure the token is created by the app and not by a malicious client
* @param string|\Stringable|UserInterface $user
* @param (Role|string)[] $roles
*/
public function __construct($secret, $user, array $roles = array())
public function __construct($secret, $user, array $roles = [])
{
parent::__construct($roles);
@@ -61,7 +60,9 @@ class AnonymousToken extends AbstractToken
*/
public function serialize()
{
return serialize(array($this->secret, parent::serialize()));
$serialized = [$this->secret, parent::serialize(true)];
return $this->doSerialize($serialized, \func_num_args() ? func_get_arg(0) : null);
}
/**
@@ -69,7 +70,7 @@ class AnonymousToken extends AbstractToken
*/
public function unserialize($serialized)
{
list($this->secret, $parentStr) = unserialize($serialized);
list($this->secret, $parentStr) = \is_array($serialized) ? $serialized : unserialize($serialized);
parent::unserialize($parentStr);
}
}
@@ -11,7 +11,8 @@
namespace Symfony\Component\Security\Core\Authentication\Token;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* PreAuthenticatedToken implements a pre-authenticated token.
@@ -24,14 +25,12 @@ class PreAuthenticatedToken extends AbstractToken
private $providerKey;
/**
* Constructor.
*
* @param string|object $user The user can be a UserInterface instance, or an object implementing a __toString method or the username as a regular string
* @param mixed $credentials The user credentials
* @param string $providerKey The provider key
* @param (RoleInterface|string)[] $roles An array of roles
* @param string|\Stringable|UserInterface $user
* @param mixed $credentials
* @param string $providerKey
* @param (Role|string)[] $roles
*/
public function __construct($user, $credentials, $providerKey, array $roles = array())
public function __construct($user, $credentials, $providerKey, array $roles = [])
{
parent::__construct($roles);
@@ -81,7 +80,9 @@ class PreAuthenticatedToken extends AbstractToken
*/
public function serialize()
{
return serialize(array($this->credentials, $this->providerKey, parent::serialize()));
$serialized = [$this->credentials, $this->providerKey, parent::serialize(true)];
return $this->doSerialize($serialized, \func_num_args() ? func_get_arg(0) : null);
}
/**
@@ -89,7 +90,7 @@ class PreAuthenticatedToken extends AbstractToken
*/
public function unserialize($str)
{
list($this->credentials, $this->providerKey, $parentStr) = unserialize($str);
list($this->credentials, $this->providerKey, $parentStr) = \is_array($str) ? $str : unserialize($str);
parent::unserialize($parentStr);
}
}
@@ -24,11 +24,8 @@ class RememberMeToken extends AbstractToken
private $providerKey;
/**
* Constructor.
*
* @param UserInterface $user
* @param string $providerKey
* @param string $secret A secret used to make sure the token is created by the app and not by a malicious client
* @param string $providerKey
* @param string $secret A secret used to make sure the token is created by the app and not by a malicious client
*
* @throws \InvalidArgumentException
*/
@@ -96,11 +93,9 @@ class RememberMeToken extends AbstractToken
*/
public function serialize()
{
return serialize(array(
$this->secret,
$this->providerKey,
parent::serialize(),
));
$serialized = [$this->secret, $this->providerKey, parent::serialize(true)];
return $this->doSerialize($serialized, \func_num_args() ? func_get_arg(0) : null);
}
/**
@@ -108,7 +103,7 @@ class RememberMeToken extends AbstractToken
*/
public function unserialize($serialized)
{
list($this->secret, $this->providerKey, $parentStr) = unserialize($serialized);
list($this->secret, $this->providerKey, $parentStr) = \is_array($serialized) ? $serialized : unserialize($serialized);
parent::unserialize($parentStr);
}
}
@@ -12,6 +12,7 @@
namespace Symfony\Component\Security\Core\Authentication\Token;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* TokenInterface is the interface for the user authentication information.
@@ -47,17 +48,21 @@ interface TokenInterface extends \Serializable
/**
* Returns a user representation.
*
* @return mixed Can be a UserInterface instance, an object implementing a __toString method,
* or the username as a regular string
* @return string|\Stringable|UserInterface
*
* @see AbstractToken::setUser()
*/
public function getUser();
/**
* Sets a user.
* Sets the user in the token.
*
* @param mixed $user
* The user can be a UserInterface instance, or an object implementing
* a __toString method or the username as a regular string.
*
* @param string|\Stringable|UserInterface $user
*
* @throws \InvalidArgumentException
*/
public function setUser($user);
@@ -11,7 +11,8 @@
namespace Symfony\Component\Security\Core\Authentication\Token;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* UsernamePasswordToken implements a username and password token.
@@ -24,16 +25,14 @@ class UsernamePasswordToken extends AbstractToken
private $providerKey;
/**
* Constructor.
*
* @param string|object $user The username (like a nickname, email address, etc.), or a UserInterface instance or an object implementing a __toString method
* @param mixed $credentials This usually is the password of the user
* @param string $providerKey The provider key
* @param (RoleInterface|string)[] $roles An array of roles
* @param string|\Stringable|UserInterface $user The username (like a nickname, email address, etc.) or a UserInterface instance
* @param mixed $credentials
* @param string $providerKey
* @param (Role|string)[] $roles
*
* @throws \InvalidArgumentException
*/
public function __construct($user, $credentials, $providerKey, array $roles = array())
public function __construct($user, $credentials, $providerKey, array $roles = [])
{
parent::__construct($roles);
@@ -45,7 +44,7 @@ class UsernamePasswordToken extends AbstractToken
$this->credentials = $credentials;
$this->providerKey = $providerKey;
parent::setAuthenticated(count($roles) > 0);
parent::setAuthenticated(\count($roles) > 0);
}
/**
@@ -93,7 +92,9 @@ class UsernamePasswordToken extends AbstractToken
*/
public function serialize()
{
return serialize(array($this->credentials, $this->providerKey, parent::serialize()));
$serialized = [$this->credentials, $this->providerKey, parent::serialize(true)];
return $this->doSerialize($serialized, \func_num_args() ? func_get_arg(0) : null);
}
/**
@@ -101,7 +102,7 @@ class UsernamePasswordToken extends AbstractToken
*/
public function unserialize($serialized)
{
list($this->credentials, $this->providerKey, $parentStr) = unserialize($serialized);
list($this->credentials, $this->providerKey, $parentStr) = \is_array($serialized) ? $serialized : unserialize($serialized);
parent::unserialize($parentStr);
}
}
-4
View File
@@ -18,8 +18,6 @@ final class AuthenticationEvents
* by one provider.
*
* @Event("Symfony\Component\Security\Core\Event\AuthenticationEvent")
*
* @var string
*/
const AUTHENTICATION_SUCCESS = 'security.authentication.success';
@@ -28,8 +26,6 @@ final class AuthenticationEvents
* authenticated by any of the providers.
*
* @Event("Symfony\Component\Security\Core\Event\AuthenticationFailureEvent")
*
* @var string
*/
const AUTHENTICATION_FAILURE = 'security.authentication.failure';
}
@@ -11,8 +11,9 @@
namespace Symfony\Component\Security\Core\Authorization;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Exception\LogicException;
/**
* AccessDecisionManager is the base class for all access decision managers
@@ -32,19 +33,17 @@ class AccessDecisionManager implements AccessDecisionManagerInterface
private $allowIfEqualGrantedDeniedDecisions;
/**
* Constructor.
*
* @param VoterInterface[] $voters An array of VoterInterface instances
* @param string $strategy The vote strategy
* @param bool $allowIfAllAbstainDecisions Whether to grant access if all voters abstained or not
* @param bool $allowIfEqualGrantedDeniedDecisions Whether to grant access if result are equals
* @param iterable|VoterInterface[] $voters An iterator of VoterInterface instances
* @param string $strategy The vote strategy
* @param bool $allowIfAllAbstainDecisions Whether to grant access if all voters abstained or not
* @param bool $allowIfEqualGrantedDeniedDecisions Whether to grant access if result are equals
*
* @throws \InvalidArgumentException
*/
public function __construct(array $voters = array(), $strategy = self::STRATEGY_AFFIRMATIVE, $allowIfAllAbstainDecisions = false, $allowIfEqualGrantedDeniedDecisions = true)
public function __construct($voters = [], $strategy = self::STRATEGY_AFFIRMATIVE, $allowIfAllAbstainDecisions = false, $allowIfEqualGrantedDeniedDecisions = true)
{
$strategyMethod = 'decide'.ucfirst($strategy);
if (!is_callable(array($this, $strategyMethod))) {
if ('' === $strategy || !\is_callable([$this, $strategyMethod])) {
throw new \InvalidArgumentException(sprintf('The strategy "%s" is not supported.', $strategy));
}
@@ -58,9 +57,13 @@ class AccessDecisionManager implements AccessDecisionManagerInterface
* Configures the voters.
*
* @param VoterInterface[] $voters An array of VoterInterface instances
*
* @deprecated since version 3.3, to be removed in 4.0. Pass the voters to the constructor instead.
*/
public function setVoters(array $voters)
{
@trigger_error(sprintf('The "%s()" method is deprecated since Symfony 3.3 and will be removed in 4.0. Pass the voters to the constructor instead.', __METHOD__), \E_USER_DEPRECATED);
$this->voters = $voters;
}
@@ -82,18 +85,14 @@ class AccessDecisionManager implements AccessDecisionManagerInterface
{
$deny = 0;
foreach ($this->voters as $voter) {
$result = $voter->vote($token, $object, $attributes);
switch ($result) {
case VoterInterface::ACCESS_GRANTED:
return true;
$result = $this->vote($voter, $token, $object, $attributes);
case VoterInterface::ACCESS_DENIED:
++$deny;
if (VoterInterface::ACCESS_GRANTED === $result) {
return true;
}
break;
default:
break;
if (VoterInterface::ACCESS_DENIED === $result) {
++$deny;
}
}
@@ -123,18 +122,12 @@ class AccessDecisionManager implements AccessDecisionManagerInterface
$grant = 0;
$deny = 0;
foreach ($this->voters as $voter) {
$result = $voter->vote($token, $object, $attributes);
$result = $this->vote($voter, $token, $object, $attributes);
switch ($result) {
case VoterInterface::ACCESS_GRANTED:
++$grant;
break;
case VoterInterface::ACCESS_DENIED:
++$deny;
break;
if (VoterInterface::ACCESS_GRANTED === $result) {
++$grant;
} elseif (VoterInterface::ACCESS_DENIED === $result) {
++$deny;
}
}
@@ -162,21 +155,16 @@ class AccessDecisionManager implements AccessDecisionManagerInterface
private function decideUnanimous(TokenInterface $token, array $attributes, $object = null)
{
$grant = 0;
foreach ($attributes as $attribute) {
foreach ($this->voters as $voter) {
$result = $voter->vote($token, $object, array($attribute));
foreach ($this->voters as $voter) {
foreach ($attributes as $attribute) {
$result = $this->vote($voter, $token, $object, [$attribute]);
switch ($result) {
case VoterInterface::ACCESS_GRANTED:
++$grant;
if (VoterInterface::ACCESS_DENIED === $result) {
return false;
}
break;
case VoterInterface::ACCESS_DENIED:
return false;
default:
break;
if (VoterInterface::ACCESS_GRANTED === $result) {
++$grant;
}
}
}
@@ -188,4 +176,27 @@ class AccessDecisionManager implements AccessDecisionManagerInterface
return $this->allowIfAllAbstainDecisions;
}
/**
* TokenInterface vote proxy method.
*
* Acts as a BC layer when the VoterInterface is not implemented on the voter.
*
* @deprecated as of 3.4 and will be removed in 4.0. Call the voter directly as the instance will always be a VoterInterface
*/
private function vote($voter, TokenInterface $token, $subject, $attributes)
{
if ($voter instanceof VoterInterface) {
return $voter->vote($token, $subject, $attributes);
}
if (method_exists($voter, 'vote')) {
@trigger_error(sprintf('Calling vote() on an voter without %1$s is deprecated as of 3.4 and will be removed in 4.0. Implement the %1$s on your voter.', VoterInterface::class), \E_USER_DEPRECATED);
// making the assumption that the signature matches
return $voter->vote($token, $subject, $attributes);
}
throw new LogicException(sprintf('"%s" should implement the "%s" interface when used as voter.', \get_class($voter), VoterInterface::class));
}
}
@@ -31,9 +31,6 @@ class AuthorizationChecker implements AuthorizationCheckerInterface
private $alwaysAuthenticate;
/**
* Constructor.
*
* @param TokenStorageInterface $tokenStorage
* @param AuthenticationManagerInterface $authenticationManager An AuthenticationManager instance
* @param AccessDecisionManagerInterface $accessDecisionManager An AccessDecisionManager instance
* @param bool $alwaysAuthenticate
@@ -49,9 +46,9 @@ class AuthorizationChecker implements AuthorizationCheckerInterface
/**
* {@inheritdoc}
*
* @throws AuthenticationCredentialsNotFoundException when the token storage has no authentication token.
* @throws AuthenticationCredentialsNotFoundException when the token storage has no authentication token
*/
final public function isGranted($attributes, $object = null)
final public function isGranted($attributes, $subject = null)
{
if (null === ($token = $this->tokenStorage->getToken())) {
throw new AuthenticationCredentialsNotFoundException('The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.');
@@ -61,10 +58,10 @@ class AuthorizationChecker implements AuthorizationCheckerInterface
$this->tokenStorage->setToken($token = $this->authenticationManager->authenticate($token));
}
if (!is_array($attributes)) {
$attributes = array($attributes);
if (!\is_array($attributes)) {
$attributes = [$attributes];
}
return $this->accessDecisionManager->decide($token, $attributes, $object);
return $this->accessDecisionManager->decide($token, $attributes, $subject);
}
}
@@ -19,12 +19,12 @@ namespace Symfony\Component\Security\Core\Authorization;
interface AuthorizationCheckerInterface
{
/**
* Checks if the attributes are granted against the current authentication token and optionally supplied object.
* Checks if the attributes are granted against the current authentication token and optionally supplied subject.
*
* @param mixed $attributes
* @param mixed $object
* @param mixed $subject
*
* @return bool
*/
public function isGranted($attributes, $object = null);
public function isGranted($attributes, $subject = null);
}
@@ -13,86 +13,24 @@ namespace Symfony\Component\Security\Core\Authorization;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* Decorates the original AccessDecisionManager class to log information
* about the security voters and the decisions made by them.
*
* @author Javier Eguiluz <javier.eguiluz@gmail.com>
*
* @internal
*/
class DebugAccessDecisionManager implements AccessDecisionManagerInterface
{
private $manager;
private $strategy;
private $voters = array();
private $decisionLog = array();
class_exists(TraceableAccessDecisionManager::class);
public function __construct(AccessDecisionManagerInterface $manager)
if (false) {
/**
* This is a placeholder for the old class, that got renamed; this is not a BC break since the class is internal, this
* placeholder is here just to help backward compatibility with older SecurityBundle versions.
*
* @deprecated The DebugAccessDecisionManager class has been renamed and is deprecated since version 3.3 and will be removed in 4.0. Use the TraceableAccessDecisionManager class instead.
*
* @internal
*/
class DebugAccessDecisionManager implements AccessDecisionManagerInterface
{
$this->manager = $manager;
if ($this->manager instanceof AccessDecisionManager) {
// The strategy is stored in a private property of the decorated service
$reflection = new \ReflectionProperty(AccessDecisionManager::class, 'strategy');
$reflection->setAccessible(true);
$this->strategy = $reflection->getValue($manager);
/**
* {@inheritdoc}
*/
public function decide(TokenInterface $token, array $attributes, $object = null)
{
}
}
/**
* {@inheritdoc}
*/
public function decide(TokenInterface $token, array $attributes, $object = null)
{
$result = $this->manager->decide($token, $attributes, $object);
$this->decisionLog[] = array(
'attributes' => $attributes,
'object' => $object,
'result' => $result,
);
return $result;
}
/**
* {@inheritdoc}
*/
public function setVoters(array $voters)
{
if (!method_exists($this->manager, 'setVoters')) {
return;
}
$this->voters = $voters;
$this->manager->setVoters($voters);
}
/**
* @return string
*/
public function getStrategy()
{
// The $strategy property is misleading because it stores the name of its
// method (e.g. 'decideAffirmative') instead of the original strategy name
// (e.g. 'affirmative')
return null === $this->strategy ? '-' : strtolower(substr($this->strategy, 6));
}
/**
* @return array
*/
public function getVoters()
{
return $this->voters;
}
/**
* @return array
*/
public function getDecisionLog()
{
return $this->decisionLog;
}
}
@@ -13,23 +13,27 @@ namespace Symfony\Component\Security\Core\Authorization;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage as BaseExpressionLanguage;
/**
* Adds some function to the default ExpressionLanguage.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @see ExpressionLanguageProvider
*/
class ExpressionLanguage extends BaseExpressionLanguage
{
if (!class_exists(BaseExpressionLanguage::class)) {
throw new \LogicException(sprintf('The "%s" class requires the "ExpressionLanguage" component. Try running "composer require symfony/expression-language".', ExpressionLanguage::class));
} else {
/**
* {@inheritdoc}
* Adds some function to the default ExpressionLanguage.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @see ExpressionLanguageProvider
*/
public function __construct($cache = null, array $providers = array())
class ExpressionLanguage extends BaseExpressionLanguage
{
// prepend the default provider to let users override it easily
array_unshift($providers, new ExpressionLanguageProvider());
/**
* {@inheritdoc}
*/
public function __construct($cache = null, array $providers = [])
{
// prepend the default provider to let users override it easily
array_unshift($providers, new ExpressionLanguageProvider());
parent::__construct($cache, $providers);
parent::__construct($cache, $providers);
}
}
}
@@ -23,7 +23,7 @@ class ExpressionLanguageProvider implements ExpressionFunctionProviderInterface
{
public function getFunctions()
{
return array(
return [
new ExpressionFunction('is_anonymous', function () {
return '$trust_resolver->isAnonymous($token)';
}, function (array $variables) {
@@ -51,8 +51,8 @@ class ExpressionLanguageProvider implements ExpressionFunctionProviderInterface
new ExpressionFunction('has_role', function ($role) {
return sprintf('in_array(%s, $roles)', $role);
}, function (array $variables, $role) {
return in_array($role, $variables['roles']);
return \in_array($role, $variables['roles']);
}),
);
];
}
}
@@ -31,11 +31,6 @@ class AuthenticatedVoter implements VoterInterface
private $authenticationTrustResolver;
/**
* Constructor.
*
* @param AuthenticationTrustResolverInterface $authenticationTrustResolver
*/
public function __construct(AuthenticationTrustResolverInterface $authenticationTrustResolver)
{
$this->authenticationTrustResolver = $authenticationTrustResolver;
@@ -11,13 +11,13 @@
namespace Symfony\Component\Security\Core\Authorization\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\ExpressionLanguage;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\HttpFoundation\Request;
/**
* ExpressionVoter votes based on the evaluation of an expression.
@@ -30,13 +30,6 @@ class ExpressionVoter implements VoterInterface
private $trustResolver;
private $roleHierarchy;
/**
* Constructor.
*
* @param ExpressionLanguage $expressionLanguage
* @param AuthenticationTrustResolverInterface $trustResolver
* @param RoleHierarchyInterface|null $roleHierarchy
*/
public function __construct(ExpressionLanguage $expressionLanguage, AuthenticationTrustResolverInterface $trustResolver, RoleHierarchyInterface $roleHierarchy = null)
{
$this->expressionLanguage = $expressionLanguage;
@@ -82,14 +75,14 @@ class ExpressionVoter implements VoterInterface
$roles = $token->getRoles();
}
$variables = array(
$variables = [
'token' => $token,
'user' => $token->getUser(),
'object' => $subject,
'subject' => $subject,
'roles' => array_map(function ($role) { return $role->getRole(); }, $roles),
'trust_resolver' => $this->trustResolver,
);
];
// this is mainly to propose a better experience when the expression is used
// in an access control rule, as the developer does not know that it's going
@@ -24,8 +24,6 @@ class RoleVoter implements VoterInterface
private $prefix;
/**
* Constructor.
*
* @param string $prefix The role prefix
*/
public function __construct($prefix = 'ROLE_')
@@ -46,7 +44,7 @@ class RoleVoter implements VoterInterface
$attribute = $attribute->getRole();
}
if (!is_string($attribute) || 0 !== strpos($attribute, $this->prefix)) {
if (!\is_string($attribute) || 0 !== strpos($attribute, $this->prefix)) {
continue;
}
+2 -3
View File
@@ -60,9 +60,8 @@ abstract class Voter implements VoterInterface
* Perform a single access check operation on a given attribute, subject and token.
* It is safe to assume that $attribute and $subject already passed the "supports()" method check.
*
* @param string $attribute
* @param mixed $subject
* @param TokenInterface $token
* @param string $attribute
* @param mixed $subject
*
* @return bool
*/
@@ -17,18 +17,13 @@ use Symfony\Component\Security\Core\Exception\BadCredentialsException;
* @author Elnur Abdurrakhimov <elnur@elnur.pro>
* @author Terje Bråten <terje@braten.be>
*/
class BCryptPasswordEncoder extends BasePasswordEncoder
class BCryptPasswordEncoder extends BasePasswordEncoder implements SelfSaltingEncoderInterface
{
const MAX_PASSWORD_LENGTH = 72;
/**
* @var string
*/
private $cost;
/**
* Constructor.
*
* @param int $cost The algorithmic cost that should be used
*
* @throws \RuntimeException When no BCrypt encoder is available
@@ -70,13 +65,13 @@ class BCryptPasswordEncoder extends BasePasswordEncoder
throw new BadCredentialsException('Invalid password.');
}
$options = array('cost' => $this->cost);
$options = ['cost' => $this->cost];
if ($salt) {
// Ignore $salt, the auto-generated one is always the best
}
return password_hash($raw, PASSWORD_BCRYPT, $options);
return password_hash($raw, \PASSWORD_BCRYPT, $options);
}
/**
@@ -30,26 +30,26 @@ abstract class BasePasswordEncoder implements PasswordEncoderInterface
protected function demergePasswordAndSalt($mergedPasswordSalt)
{
if (empty($mergedPasswordSalt)) {
return array('', '');
return ['', ''];
}
$password = $mergedPasswordSalt;
$salt = '';
$saltBegins = strrpos($mergedPasswordSalt, '{');
if (false !== $saltBegins && $saltBegins + 1 < strlen($mergedPasswordSalt)) {
if (false !== $saltBegins && $saltBegins + 1 < \strlen($mergedPasswordSalt)) {
$salt = substr($mergedPasswordSalt, $saltBegins + 1, -1);
$password = substr($mergedPasswordSalt, 0, $saltBegins);
}
return array($password, $salt);
return [$password, $salt];
}
/**
* Merges a password and a salt.
*
* @param string $password the password to be used
* @param string $salt the salt to be used
* @param string $password The password to be used
* @param string|null $salt The salt to be used
*
* @return string a merged password and salt
*
@@ -93,6 +93,6 @@ abstract class BasePasswordEncoder implements PasswordEncoderInterface
*/
protected function isPasswordTooLong($password)
{
return strlen($password) > static::MAX_PASSWORD_LENGTH;
return \strlen($password) > static::MAX_PASSWORD_LENGTH;
}
}
@@ -22,7 +22,7 @@ interface EncoderAwareInterface
* If the method returns null, the standard way to retrieve the encoder
* will be used instead.
*
* @return string
* @return string|null
*/
public function getEncoderName();
}
+25 -21
View File
@@ -33,14 +33,14 @@ class EncoderFactory implements EncoderFactoryInterface
$encoderKey = null;
if ($user instanceof EncoderAwareInterface && (null !== $encoderName = $user->getEncoderName())) {
if (!array_key_exists($encoderName, $this->encoders)) {
if (!\array_key_exists($encoderName, $this->encoders)) {
throw new \RuntimeException(sprintf('The encoder "%s" was not configured.', $encoderName));
}
$encoderKey = $encoderName;
} else {
foreach ($this->encoders as $class => $encoder) {
if ((is_object($user) && $user instanceof $class) || (!is_object($user) && (is_subclass_of($user, $class) || $user == $class))) {
if ((\is_object($user) && $user instanceof $class) || (!\is_object($user) && (is_subclass_of($user, $class) || $user == $class))) {
$encoderKey = $class;
break;
}
@@ -48,7 +48,7 @@ class EncoderFactory implements EncoderFactoryInterface
}
if (null === $encoderKey) {
throw new \RuntimeException(sprintf('No encoder has been configured for account "%s".', is_object($user) ? get_class($user) : $user));
throw new \RuntimeException(sprintf('No encoder has been configured for account "%s".', \is_object($user) ? \get_class($user) : $user));
}
if (!$this->encoders[$encoderKey] instanceof PasswordEncoderInterface) {
@@ -61,8 +61,6 @@ class EncoderFactory implements EncoderFactoryInterface
/**
* Creates the actual encoder instance.
*
* @param array $config
*
* @return PasswordEncoderInterface
*
* @throws \InvalidArgumentException
@@ -73,10 +71,10 @@ class EncoderFactory implements EncoderFactoryInterface
$config = $this->getEncoderConfigFromAlgorithm($config);
}
if (!isset($config['class'])) {
throw new \InvalidArgumentException(sprintf('"class" must be set in %s.', json_encode($config)));
throw new \InvalidArgumentException('"class" must be set in '.json_encode($config));
}
if (!isset($config['arguments'])) {
throw new \InvalidArgumentException(sprintf('"arguments" must be set in %s.', json_encode($config)));
throw new \InvalidArgumentException('"arguments" must be set in '.json_encode($config));
}
$reflection = new \ReflectionClass($config['class']);
@@ -88,36 +86,42 @@ class EncoderFactory implements EncoderFactoryInterface
{
switch ($config['algorithm']) {
case 'plaintext':
return array(
return [
'class' => PlaintextPasswordEncoder::class,
'arguments' => array($config['ignore_case']),
);
'arguments' => [$config['ignore_case']],
];
case 'pbkdf2':
return array(
return [
'class' => Pbkdf2PasswordEncoder::class,
'arguments' => array(
'arguments' => [
$config['hash_algorithm'],
$config['encode_as_base64'],
$config['iterations'],
$config['key_length'],
),
);
],
];
case 'bcrypt':
return array(
return [
'class' => BCryptPasswordEncoder::class,
'arguments' => array($config['cost']),
);
'arguments' => [$config['cost']],
];
case 'argon2i':
return [
'class' => Argon2iPasswordEncoder::class,
'arguments' => [],
];
}
return array(
return [
'class' => MessageDigestPasswordEncoder::class,
'arguments' => array(
'arguments' => [
$config['algorithm'],
$config['encode_as_base64'],
$config['iterations'],
),
);
],
];
}
}
@@ -25,8 +25,6 @@ class MessageDigestPasswordEncoder extends BasePasswordEncoder
private $iterations;
/**
* Constructor.
*
* @param string $algorithm The digest algorithm to use
* @param bool $encodeHashAsBase64 Whether to base64 encode the password hash
* @param int $iterations The number of iterations to use to stretch the password hash
@@ -47,7 +45,7 @@ class MessageDigestPasswordEncoder extends BasePasswordEncoder
throw new BadCredentialsException('Invalid password.');
}
if (!in_array($this->algorithm, hash_algos(), true)) {
if (!\in_array($this->algorithm, hash_algos(), true)) {
throw new \LogicException(sprintf('The algorithm "%s" is not supported.', $this->algorithm));
}
@@ -11,6 +11,8 @@
namespace Symfony\Component\Security\Core\Encoder;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
/**
* PasswordEncoderInterface is the interface for all encoders.
*
@@ -21,21 +23,26 @@ interface PasswordEncoderInterface
/**
* Encodes the raw password.
*
* @param string $raw The password to encode
* @param string $salt The salt
* @param string $raw The password to encode
* @param string|null $salt The salt
*
* @return string The encoded password
*
* @throws BadCredentialsException If the raw password is invalid, e.g. excessively long
* @throws \InvalidArgumentException If the salt is invalid
*/
public function encodePassword($raw, $salt);
/**
* Checks a raw password against an encoded password.
*
* @param string $encoded An encoded password
* @param string $raw A raw password
* @param string $salt The salt
* @param string $encoded An encoded password
* @param string $raw A raw password
* @param string|null $salt The salt
*
* @return bool true if the password is valid, false otherwise
*
* @throws \InvalidArgumentException If the salt is invalid
*/
public function isPasswordValid($encoded, $raw, $salt);
}
@@ -34,8 +34,6 @@ class Pbkdf2PasswordEncoder extends BasePasswordEncoder
private $length;
/**
* Constructor.
*
* @param string $algorithm The digest algorithm to use
* @param bool $encodeHashAsBase64 Whether to base64 encode the password hash
* @param int $iterations The number of iterations to use to stretch the password hash
@@ -60,7 +58,7 @@ class Pbkdf2PasswordEncoder extends BasePasswordEncoder
throw new BadCredentialsException('Invalid password.');
}
if (!in_array($this->algorithm, hash_algos(), true)) {
if (!\in_array($this->algorithm, hash_algos(), true)) {
throw new \LogicException(sprintf('The algorithm "%s" is not supported.', $this->algorithm));
}
@@ -14,7 +14,9 @@ namespace Symfony\Component\Security\Core\Encoder;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
/**
* PlaintextPasswordEncoder does not do any encoding.
* PlaintextPasswordEncoder does not do any encoding but is useful in testing environments.
*
* As this encoder is not cryptographically secure, usage of it in production environments is discouraged.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
@@ -23,8 +25,6 @@ class PlaintextPasswordEncoder extends BasePasswordEncoder
private $ignorePasswordCase;
/**
* Constructor.
*
* @param bool $ignorePasswordCase Compare password case-insensitive
*/
public function __construct($ignorePasswordCase = false)
@@ -20,14 +20,8 @@ use Symfony\Component\Security\Core\User\UserInterface;
*/
class UserPasswordEncoder implements UserPasswordEncoderInterface
{
/**
* @var EncoderFactoryInterface
*/
private $encoderFactory;
/**
* @param EncoderFactoryInterface $encoderFactory The encoder factory
*/
public function __construct(EncoderFactoryInterface $encoderFactory)
{
$this->encoderFactory = $encoderFactory;
@@ -48,6 +42,10 @@ class UserPasswordEncoder implements UserPasswordEncoderInterface
*/
public function isPasswordValid(UserInterface $user, $raw)
{
if (null === $user->getPassword()) {
return false;
}
$encoder = $this->encoderFactory->getEncoder($user);
return $encoder->isPasswordValid($user->getPassword(), $raw, $user->getSalt());
+1 -1
View File
@@ -11,8 +11,8 @@
namespace Symfony\Component\Security\Core\Event;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* This is a general purpose authentication event.
@@ -11,8 +11,8 @@
namespace Symfony\Component\Security\Core\Event;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
/**
* This event is dispatched on authentication failure.
@@ -18,7 +18,7 @@ namespace Symfony\Component\Security\Core\Exception;
*/
class AccessDeniedException extends \RuntimeException
{
private $attributes = array();
private $attributes = [];
private $subject;
public function __construct($message = 'Access Denied.', \Exception $previous = null)
@@ -34,11 +34,6 @@ abstract class AccountStatusException extends AuthenticationException
return $this->user;
}
/**
* Set the user.
*
* @param UserInterface $user
*/
public function setUser(UserInterface $user)
{
$this->user = $user;
@@ -49,10 +44,9 @@ abstract class AccountStatusException extends AuthenticationException
*/
public function serialize()
{
return serialize(array(
$this->user,
parent::serialize(),
));
$serialized = [$this->user, parent::serialize(true)];
return $this->doSerialize($serialized, \func_num_args() ? func_get_arg(0) : null);
}
/**
@@ -60,7 +54,7 @@ abstract class AccountStatusException extends AuthenticationException
*/
public function unserialize($str)
{
list($this->user, $parentData) = unserialize($str);
list($this->user, $parentData) = \is_array($str) ? $str : unserialize($str);
parent::unserialize($parentData);
}
@@ -26,32 +26,45 @@ class AuthenticationException extends \RuntimeException implements \Serializable
/**
* Get the token.
*
* @return TokenInterface
* @return TokenInterface|null
*/
public function getToken()
{
return $this->token;
}
/**
* Set the token.
*
* @param TokenInterface $token
*/
public function setToken(TokenInterface $token)
{
$this->token = $token;
}
/**
* {@inheritdoc}
*/
public function serialize()
{
return serialize(array(
$serialized = [
$this->token,
$this->code,
$this->message,
$this->file,
$this->line,
));
];
return $this->doSerialize($serialized, \func_num_args() ? func_get_arg(0) : null);
}
/**
* @internal
*/
protected function doSerialize($serialized, $isCalledFromOverridingMethod)
{
if (null === $isCalledFromOverridingMethod) {
$trace = debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT, 3);
$isCalledFromOverridingMethod = isset($trace[2]['function'], $trace[2]['object']) && 'serialize' === $trace[2]['function'] && $this === $trace[2]['object'];
}
return $isCalledFromOverridingMethod ? $serialized : serialize($serialized);
}
public function unserialize($str)
@@ -62,7 +75,7 @@ class AuthenticationException extends \RuntimeException implements \Serializable
$this->message,
$this->file,
$this->line
) = unserialize($str);
) = \is_array($str) ? $str : unserialize($str);
}
/**
@@ -82,6 +95,6 @@ class AuthenticationException extends \RuntimeException implements \Serializable
*/
public function getMessageData()
{
return array();
return [];
}
}
@@ -12,7 +12,7 @@
namespace Symfony\Component\Security\Core\Exception;
/**
* AuthenticationServiceException is thrown when an authenticated token becomes un-authenticated between requests.
* AuthenticationExpiredException is thrown when an authenticated token becomes un-authenticated between requests.
*
* In practice, this is due to the User changing between requests (e.g. password changes),
* causes the token to become un-authenticated.
@@ -24,9 +24,9 @@ class CustomUserMessageAuthenticationException extends AuthenticationException
{
private $messageKey;
private $messageData = array();
private $messageData = [];
public function __construct($message = '', array $messageData = array(), $code = 0, \Exception $previous = null)
public function __construct($message = '', array $messageData = [], $code = 0, \Exception $previous = null)
{
parent::__construct($message, $code, $previous);
@@ -39,7 +39,7 @@ class CustomUserMessageAuthenticationException extends AuthenticationException
* @param string $messageKey The message or message key
* @param array $messageData Data to be passed into the translator
*/
public function setSafeMessage($messageKey, array $messageData = array())
public function setSafeMessage($messageKey, array $messageData = [])
{
$this->messageKey = $messageKey;
$this->messageData = $messageData;
@@ -60,11 +60,9 @@ class CustomUserMessageAuthenticationException extends AuthenticationException
*/
public function serialize()
{
return serialize(array(
parent::serialize(),
$this->messageKey,
$this->messageData,
));
$serialized = [parent::serialize(true), $this->messageKey, $this->messageData];
return $this->doSerialize($serialized, \func_num_args() ? func_get_arg(0) : null);
}
/**
@@ -72,7 +70,7 @@ class CustomUserMessageAuthenticationException extends AuthenticationException
*/
public function unserialize($str)
{
list($parentData, $this->messageKey, $this->messageData) = unserialize($str);
list($parentData, $this->messageKey, $this->messageData) = \is_array($str) ? $str : unserialize($str);
parent::unserialize($parentData);
}
@@ -11,12 +11,16 @@
namespace Symfony\Component\Security\Core\Exception;
@trigger_error(sprintf('The %s class and the whole HTTP digest authentication system is deprecated since Symfony 3.4 and will be removed in 4.0.', NonceExpiredException::class), \E_USER_DEPRECATED);
/**
* NonceExpiredException is thrown when an authentication is rejected because
* the digest nonce has expired.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander <iam.asm89@gmail.com>
*
* @deprecated since 3.4, to be removed in 4.0
*/
class NonceExpiredException extends AuthenticationException
{
@@ -54,10 +54,9 @@ class UsernameNotFoundException extends AuthenticationException
*/
public function serialize()
{
return serialize(array(
$this->username,
parent::serialize(),
));
$serialized = [$this->username, parent::serialize(true)];
return $this->doSerialize($serialized, \func_num_args() ? func_get_arg(0) : null);
}
/**
@@ -65,7 +64,7 @@ class UsernameNotFoundException extends AuthenticationException
*/
public function unserialize($str)
{
list($this->username, $parentData) = unserialize($str);
list($this->username, $parentData) = \is_array($str) ? $str : unserialize($str);
parent::unserialize($parentData);
}
@@ -75,6 +74,6 @@ class UsernameNotFoundException extends AuthenticationException
*/
public function getMessageData()
{
return array('{{ username }}' => $this->username);
return ['{{ username }}' => $this->username];
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (c) 2004-2017 Fabien Potencier
Copyright (c) 2004-2020 Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+1 -1
View File
@@ -9,7 +9,7 @@ the Java Spring framework.
Resources
---------
* [Documentation](https://symfony.com/doc/current/components/security/index.html)
* [Documentation](https://symfony.com/doc/current/components/security.html)
* [Contributing](https://symfony.com/doc/current/contributing/index.html)
* [Report issues](https://github.com/symfony/symfony/issues) and
[send Pull Requests](https://github.com/symfony/symfony/pulls)
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>الحساب مغلق.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>عدد كبير جدا من محاولات الدخول الفاشلة، يرجى المحاولة مرة أخرى في وقت لاحق.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>رابط تسجيل الدخول غير صالح أو منتهي الصلاحية.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>Акаунта е заключен.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>Твърде много грешни опити за вход, моля опитайте по-късно.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>Невалиден или изтекъл линк за вход.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>Účet je zablokovaný.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>Příliš mnoho nepovedených pokusů přihlášení. Zkuste to prosím později.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>Neplatný nebo expirovaný odkaz na přihlášení.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -24,11 +24,11 @@
</trans-unit>
<trans-unit id="6">
<source>Not privileged to request the resource.</source>
<target>Ingen tilladselese at anvende kilden.</target>
<target>Ingen adgang til at forespørge ressourcen.</target>
</trans-unit>
<trans-unit id="7">
<source>Invalid CSRF token.</source>
<target>Ugyldigt CSRF token.</target>
<target>Ugyldig CSRF-token.</target>
</trans-unit>
<trans-unit id="8">
<source>Digest nonce has expired.</source>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>Der Account ist gesperrt.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>Zu viele fehlgeschlagene Anmeldeversuche, bitte versuchen Sie es später noch einmal.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>Ungültiger oder abgelaufener Anmelde-Link.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>Account is locked.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>Too many failed login attempts, please try again later.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>Invalid or expired login link.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>La cuenta está bloqueada.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>Demasiados intentos fallidos de inicio de sesión, inténtelo de nuevo más tarde.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>Enlace de inicio de sesión inválido o expirado.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -4,43 +4,43 @@
<body>
<trans-unit id="1">
<source>An authentication exception occurred.</source>
<target>خطایی هنگام تعیین اعتبار اتفاق افتاد.</target>
<target>خطایی هنگام احراز هویت رخ داده است.</target>
</trans-unit>
<trans-unit id="2">
<source>Authentication credentials could not be found.</source>
<target>شرایط تعیین اعتبار پیدا نشد.</target>
<target>شرایط احراز هویت یافت نشد.</target>
</trans-unit>
<trans-unit id="3">
<source>Authentication request could not be processed due to a system problem.</source>
<target>درخواست تعیین اعتبار به دلیل مشکل سیستم قابل بررسی نیست.</target>
<target>درخواست احراز هویت به دلیل وجود مشکل در سیستم قابل پردازش نمی باشد.</target>
</trans-unit>
<trans-unit id="4">
<source>Invalid credentials.</source>
<target>شرایط نامعتبر.</target>
<target>احراز هویت نامعتبر می باشد.</target>
</trans-unit>
<trans-unit id="5">
<source>Cookie has already been used by someone else.</source>
<target>کوکی قبلا برای شخص دیگری استفاده شده است.</target>
<target>Cookie قبلا توسط شخص دیگری استفاده گردیده است.</target>
</trans-unit>
<trans-unit id="6">
<source>Not privileged to request the resource.</source>
<target>دسترسی لازم برای درخواست این منبع را ندارید.</target>
<target>دسترسی لازم برای درخواست از این منبع را دارا نمی باشید.</target>
</trans-unit>
<trans-unit id="7">
<source>Invalid CSRF token.</source>
<target>توکن CSRF معتبر نیست.</target>
<target>توکن CSRF معتبر نمی باشد.</target>
</trans-unit>
<trans-unit id="8">
<source>Digest nonce has expired.</source>
<target>Digest nonce منقضی شده است.</target>
<target>Digest nonce منقضی گردیده است.</target>
</trans-unit>
<trans-unit id="9">
<source>No authentication provider found to support the authentication token.</source>
<target>هیچ ارایه کننده تعیین اعتباری برای ساپورت توکن تعیین اعتبار پیدا نشد.</target>
<target>هیچ ارایه دهنده احراز هویتی برای پشتیبانی از توکن احراز هویت پیدا نشد.</target>
</trans-unit>
<trans-unit id="10">
<source>No session available, it either timed out or cookies are not enabled.</source>
<target>جلسه‌ای در دسترس نیست. این میتواند یا به دلیل پایان یافتن زمان باشد یا اینکه کوکی ها فعال نیستند.</target>
<target>هیچ جلسه‌ای در دسترس نمی باشد. این میتواند به دلیل پایان یافتن زمان و یا فعال نبودن کوکی ها باشد.</target>
</trans-unit>
<trans-unit id="11">
<source>No token could be found.</source>
@@ -52,19 +52,27 @@
</trans-unit>
<trans-unit id="13">
<source>Account has expired.</source>
<target>حساب کاربری منقضی شده است.</target>
<target>حساب کاربری منقضی گردیده است.</target>
</trans-unit>
<trans-unit id="14">
<source>Credentials have expired.</source>
<target>پارامترهای تعیین اعتبار منقضی شده‌اند.</target>
<target>مجوزهای احراز هویت منقضی گردیده‌اند.</target>
</trans-unit>
<trans-unit id="15">
<source>Account is disabled.</source>
<target>حساب کاربری غیرفعال است.</target>
<target>حساب کاربری غیرفعال می باشد.</target>
</trans-unit>
<trans-unit id="16">
<source>Account is locked.</source>
<target>حساب کاربری قفل شده است.</target>
<target>حساب کاربری قفل گردیده است.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>تلاش‌های ناموفق زیادی برای ورود صورت گرفته است، لطفاً بعداً دوباره تلاش کنید.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>لینک ورود نامعتبر یا تاریخ‌گذشته است.</target>
</trans-unit>
</body>
</file>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>Le compte est bloqué.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>Plusieurs tentatives de connexion ont échoué, veuillez réessayer plus tard.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>Lien de connexion invalide ou expiré.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -4,7 +4,7 @@
<body>
<trans-unit id="1">
<source>An authentication exception occurred.</source>
<target>An authentication exception occurred.</target>
<target>שגיאה באימות</target>
</trans-unit>
<trans-unit id="2">
<source>Authentication credentials could not be found.</source>
@@ -12,11 +12,11 @@
</trans-unit>
<trans-unit id="3">
<source>Authentication request could not be processed due to a system problem.</source>
<target>Authentication request could not be processed due to a system problem.</target>
<target>לא ניתן היה לעבד את בקשת אימות בגלל בעיית מערכת.</target>
</trans-unit>
<trans-unit id="4">
<source>Invalid credentials.</source>
<target>Invalid credentials.</target>
<target>שם משתמש או סיסמא שגויים</target>
</trans-unit>
<trans-unit id="5">
<source>Cookie has already been used by someone else.</source>
@@ -40,7 +40,7 @@
</trans-unit>
<trans-unit id="10">
<source>No session available, it either timed out or cookies are not enabled.</source>
<target>No session available, it either timed out or cookies are not enabled.</target>
<target>אין סיישן זמין, או שתם הזמן הקצוב או העוגיות אינן מופעלות.</target>
</trans-unit>
<trans-unit id="11">
<source>No token could be found.</source>
@@ -48,23 +48,23 @@
</trans-unit>
<trans-unit id="12">
<source>Username could not be found.</source>
<target>Username could not be found.</target>
<target>שם משתמש לא נמצא במערכת</target>
</trans-unit>
<trans-unit id="13">
<source>Account has expired.</source>
<target>Account has expired.</target>
<target>החשבון פג תוקף.</target>
</trans-unit>
<trans-unit id="14">
<source>Credentials have expired.</source>
<target>Credentials have expired.</target>
<target>פרטי התחברות פקעו תוקף</target>
</trans-unit>
<trans-unit id="15">
<source>Account is disabled.</source>
<target>Account is disabled.</target>
<target>החשבון מבוטל.</target>
</trans-unit>
<trans-unit id="16">
<source>Account is locked.</source>
<target>Account is locked.</target>
<target>החשבון נעול.</target>
</trans-unit>
</body>
</file>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>Akun terkunci.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>Terlalu banyak percobaan login yang salah, Silahkan coba lagi nanti.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>Link login salah atau sudah kadaluwarsa.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>L'account è bloccato.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>Troppi tentaivi di login falliti. Riprova tra un po'.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>Link di login scaduto o non valido.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>アカウントはロックされています。</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>ログイン試行回数を超えました。しばらくして再度お試しください。</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>ログインリンクが有効期限切れ、もしくは無効です。</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -8,7 +8,7 @@
</trans-unit>
<trans-unit id="2">
<source>Authentication credentials could not be found.</source>
<target>Nepavyko rasti autentifikacijos duomneų.</target>
<target>Nepavyko rasti autentifikacijos duomenų.</target>
</trans-unit>
<trans-unit id="3">
<source>Authentication request could not be processed due to a system problem.</source>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>Konts ir slēgts.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>Pārāk daudz atteiktu ieejas mēģinājumu, lūdzu, mēģiniet vēlreiz vēlāk.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>Ieejas saite ir nederīga vai arī tai ir beidzies derīguma termiņš.</target>
</trans-unit>
</body>
</file>
</xliff>
</xliff>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>Account is geblokkeerd.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>Te veel onjuiste inlogpogingen, probeer het later nogmaals.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>Ongeldige of verlopen inloglink.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -16,7 +16,7 @@
</trans-unit>
<trans-unit id="4">
<source>Invalid credentials.</source>
<target>Ugyldig påloggingsinformasjonen.</target>
<target>Ugyldig påloggingsinformasjon.</target>
</trans-unit>
<trans-unit id="5">
<source>Cookie has already been used by someone else.</source>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>Konto jest zablokowane.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>Zbyt dużo nieudanych prób logowania, proszę spróbować ponownie później.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>Nieprawidłowy lub wygasły link logowania.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -12,7 +12,7 @@
</trans-unit>
<trans-unit id="3">
<source>Authentication request could not be processed due to a system problem.</source>
<target>A autenticação não pôde ser concluída devido a um problema no sistema.</target>
<target>A solicitação de autenticação não pôde ser processada devido a um problema no sistema.</target>
</trans-unit>
<trans-unit id="4">
<source>Invalid credentials.</source>
@@ -20,11 +20,11 @@
</trans-unit>
<trans-unit id="5">
<source>Cookie has already been used by someone else.</source>
<target>Este cookie já está em uso.</target>
<target>Este cookie já foi usado por outra pessoa.</target>
</trans-unit>
<trans-unit id="6">
<source>Not privileged to request the resource.</source>
<target>Não possui privilégios o bastante para requisitar este recurso.</target>
<target>Sem privilégio para solicitar o recurso.</target>
</trans-unit>
<trans-unit id="7">
<source>Invalid CSRF token.</source>
@@ -40,7 +40,7 @@
</trans-unit>
<trans-unit id="10">
<source>No session available, it either timed out or cookies are not enabled.</source>
<target>Nenhuma sessão disponível, ela expirou ou os cookies estão desativados.</target>
<target>Nenhuma sessão disponível, ela expirou ou os cookies não estão habilitados.</target>
</trans-unit>
<trans-unit id="11">
<source>No token could be found.</source>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>A conta está travada.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>Muitas tentativas de login malsucedidas, tente novamente mais tarde.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>Link de login inválido ou expirado.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>Учетная запись заблокирована.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>Слишком много неудачных попыток входа, пожалуйста, попробуйте позже.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>Ссылка для входа недействительна или просрочена.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>Účet je zablokovaný.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>Príliš mnoho neúspešných pokusov o prihlásenie. Skúste to prosím znovu neskôr.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>Neplatný alebo expirovaný odkaz na prihlásenie.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>Kontot är låst.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>För många misslyckade inloggningsförsök, försök igen senare.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>Ogiltig eller utgången inloggningslänk.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>Hesap kilitlenmiş.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>Çok fazla başarısız giriş denemesi, lütfen daha sonra tekrar deneyin.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>Geçersiz veya süresi dolmuş oturum açma bağlantısı.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -1,71 +0,0 @@
<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="file.ext">
<body>
<trans-unit id="1">
<source>An authentication exception occurred.</source>
<target>Помилка автентифікації.</target>
</trans-unit>
<trans-unit id="2">
<source>Authentication credentials could not be found.</source>
<target>Автентифікаційні дані не знайдено.</target>
</trans-unit>
<trans-unit id="3">
<source>Authentication request could not be processed due to a system problem.</source>
<target>Запит на автентифікацію не може бути опрацьовано у зв’язку з проблемою в системі.</target>
</trans-unit>
<trans-unit id="4">
<source>Invalid credentials.</source>
<target>Невірні автентифікаційні дані.</target>
</trans-unit>
<trans-unit id="5">
<source>Cookie has already been used by someone else.</source>
<target>Хтось інший вже використав цей сookie.</target>
</trans-unit>
<trans-unit id="6">
<source>Not privileged to request the resource.</source>
<target>Відсутні права на запит цього ресурсу.</target>
</trans-unit>
<trans-unit id="7">
<source>Invalid CSRF token.</source>
<target>Невірний токен CSRF.</target>
</trans-unit>
<trans-unit id="8">
<source>Digest nonce has expired.</source>
<target>Закінчився термін дії одноразового ключа дайджесту.</target>
</trans-unit>
<trans-unit id="9">
<source>No authentication provider found to support the authentication token.</source>
<target>Не знайдено провайдера автентифікації, що підтримує токен автентифікаціії.</target>
</trans-unit>
<trans-unit id="10">
<source>No session available, it either timed out or cookies are not enabled.</source>
<target>Сесія недоступна, її час вийшов, або cookies вимкнено.</target>
</trans-unit>
<trans-unit id="11">
<source>No token could be found.</source>
<target>Токен не знайдено.</target>
</trans-unit>
<trans-unit id="12">
<source>Username could not be found.</source>
<target>Ім’я користувача не знайдено.</target>
</trans-unit>
<trans-unit id="13">
<source>Account has expired.</source>
<target>Термін дії облікового запису вичерпано.</target>
</trans-unit>
<trans-unit id="14">
<source>Credentials have expired.</source>
<target>Термін дії автентифікаційних даних вичерпано.</target>
</trans-unit>
<trans-unit id="15">
<source>Account is disabled.</source>
<target>Обліковий запис відключено.</target>
</trans-unit>
<trans-unit id="16">
<source>Account is locked.</source>
<target>Обліковий запис заблоковано.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -48,7 +48,7 @@
</trans-unit>
<trans-unit id="12">
<source>Username could not be found.</source>
<target>Không tìm thấy tên người dùng username.</target>
<target>Không tìm thấy tên người dùng.</target>
</trans-unit>
<trans-unit id="13">
<source>Account has expired.</source>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>Tài khoản bị khóa.</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>Đăng nhập sai quá nhiều lần, vui lòng thử lại lần nữa.</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>Liên kết đăng nhập không hợp lệ hoặc quá hạn.</target>
</trans-unit>
</body>
</file>
</xliff>
@@ -66,6 +66,14 @@
<source>Account is locked.</source>
<target>帐号已被锁定。</target>
</trans-unit>
<trans-unit id="17">
<source>Too many failed login attempts, please try again later.</source>
<target>登入失败的次数过多,请稍后再试。</target>
</trans-unit>
<trans-unit id="18">
<source>Invalid or expired login link.</source>
<target>失效或过期的登入链接。</target>
</trans-unit>
</body>
</file>
</xliff>
+1 -4
View File
@@ -12,8 +12,7 @@
namespace Symfony\Component\Security\Core\Role;
/**
* Role is a simple implementation of a RoleInterface where the role is a
* string.
* Role is a simple implementation representing a role identified by a string.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
@@ -22,8 +21,6 @@ class Role implements RoleInterface
private $role;
/**
* Constructor.
*
* @param string $role The role name
*/
public function __construct($role)
+2 -4
View File
@@ -22,8 +22,6 @@ class RoleHierarchy implements RoleHierarchyInterface
protected $map;
/**
* Constructor.
*
* @param array $hierarchy An array defining the hierarchy
*/
public function __construct(array $hierarchy)
@@ -54,10 +52,10 @@ class RoleHierarchy implements RoleHierarchyInterface
protected function buildRoleMap()
{
$this->map = array();
$this->map = [];
foreach ($this->hierarchy as $main => $roles) {
$this->map[$main] = $roles;
$visited = array();
$visited = [];
$additionalRoles = $roles;
while ($role = array_shift($additionalRoles)) {
if (!isset($this->hierarchy[$role])) {
+2
View File
@@ -18,6 +18,8 @@ namespace Symfony\Component\Security\Core\Role;
* supported by at least one AccessDecisionManager.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated The RoleInterface is deprecated since version 3.3 and will be removed in 4.0. Extend the Symfony\Component\Security\Core\Role\Role class instead.
*/
interface RoleInterface
{
-2
View File
@@ -24,8 +24,6 @@ class SwitchUserRole extends Role
private $source;
/**
* Constructor.
*
* @param string $role The role as a string
* @param TokenInterface $source The original token
*/
+53 -3
View File
@@ -11,15 +11,65 @@
namespace Symfony\Component\Security\Core;
use Psr\Container\ContainerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* This class holds security information.
* Helper class for commonly-needed security tasks.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
* @final
*/
final class Security
class Security
{
const ACCESS_DENIED_ERROR = '_security.403_error';
const AUTHENTICATION_ERROR = '_security.last_error';
const LAST_USERNAME = '_security.last_username';
const MAX_USERNAME_LENGTH = 4096;
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* @return UserInterface|null
*/
public function getUser()
{
if (!$token = $this->getToken()) {
return null;
}
$user = $token->getUser();
if (!\is_object($user)) {
return null;
}
return $user;
}
/**
* Checks if the attributes are granted against the current authentication token and optionally supplied subject.
*
* @param mixed $attributes
* @param mixed $subject
*
* @return bool
*/
public function isGranted($attributes, $subject = null)
{
return $this->container->get('security.authorization_checker')
->isGranted($attributes, $subject);
}
/**
* @return TokenInterface|null
*/
public function getToken()
{
return $this->container->get('security.token_storage')->getToken();
}
}
@@ -13,39 +13,36 @@ namespace Symfony\Component\Security\Core\Tests\Authentication;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\AuthenticationEvents;
use Symfony\Component\Security\Core\Event\AuthenticationEvent;
use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
use Symfony\Component\Security\Core\Exception\ProviderNotFoundException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\ProviderNotFoundException;
class AuthenticationProviderManagerTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
public function testAuthenticateWithoutProviders()
{
new AuthenticationProviderManager(array());
$this->expectException('InvalidArgumentException');
new AuthenticationProviderManager([]);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testAuthenticateWithProvidersWithIncorrectInterface()
{
new AuthenticationProviderManager(array(
$this->expectException('InvalidArgumentException');
(new AuthenticationProviderManager([
new \stdClass(),
));
]))->authenticate($this->getMockBuilder(TokenInterface::class)->getMock());
}
public function testAuthenticateWhenNoProviderSupportsToken()
{
$manager = new AuthenticationProviderManager(array(
$manager = new AuthenticationProviderManager([
$this->getAuthenticationProvider(false),
));
]);
try {
$manager->authenticate($token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
@@ -57,9 +54,15 @@ class AuthenticationProviderManagerTest extends TestCase
public function testAuthenticateWhenProviderReturnsAccountStatusException()
{
$manager = new AuthenticationProviderManager(array(
$secondAuthenticationProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface')->getMock();
$manager = new AuthenticationProviderManager([
$this->getAuthenticationProvider(true, null, 'Symfony\Component\Security\Core\Exception\AccountStatusException'),
));
$secondAuthenticationProvider,
]);
// AccountStatusException stops authentication
$secondAuthenticationProvider->expects($this->never())->method('supports');
try {
$manager->authenticate($token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
@@ -71,9 +74,9 @@ class AuthenticationProviderManagerTest extends TestCase
public function testAuthenticateWhenProviderReturnsAuthenticationException()
{
$manager = new AuthenticationProviderManager(array(
$manager = new AuthenticationProviderManager([
$this->getAuthenticationProvider(true, null, 'Symfony\Component\Security\Core\Exception\AuthenticationException'),
));
]);
try {
$manager->authenticate($token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
@@ -85,10 +88,10 @@ class AuthenticationProviderManagerTest extends TestCase
public function testAuthenticateWhenOneReturnsAuthenticationExceptionButNotAll()
{
$manager = new AuthenticationProviderManager(array(
$manager = new AuthenticationProviderManager([
$this->getAuthenticationProvider(true, null, 'Symfony\Component\Security\Core\Exception\AuthenticationException'),
$this->getAuthenticationProvider(true, $expected = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()),
));
]);
$token = $manager->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->assertSame($expected, $token);
@@ -101,10 +104,10 @@ class AuthenticationProviderManagerTest extends TestCase
->expects($this->never())
->method('supports')
;
$manager = new AuthenticationProviderManager(array(
$manager = new AuthenticationProviderManager([
$this->getAuthenticationProvider(true, $expected = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()),
$second,
));
]);
$token = $manager->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->assertSame($expected, $token);
@@ -112,16 +115,16 @@ class AuthenticationProviderManagerTest extends TestCase
public function testEraseCredentialFlag()
{
$manager = new AuthenticationProviderManager(array(
$manager = new AuthenticationProviderManager([
$this->getAuthenticationProvider(true, $token = new UsernamePasswordToken('foo', 'bar', 'key')),
));
]);
$token = $manager->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->assertEquals('', $token->getCredentials());
$manager = new AuthenticationProviderManager(array(
$manager = new AuthenticationProviderManager([
$this->getAuthenticationProvider(true, $token = new UsernamePasswordToken('foo', 'bar', 'key')),
), false);
], false);
$token = $manager->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$this->assertEquals('bar', $token->getCredentials());
@@ -140,7 +143,7 @@ class AuthenticationProviderManagerTest extends TestCase
->method('dispatch')
->with(AuthenticationEvents::AUTHENTICATION_FAILURE, $this->equalTo(new AuthenticationFailureEvent($token, $exception)));
$manager = new AuthenticationProviderManager(array($provider));
$manager = new AuthenticationProviderManager([$provider]);
$manager->setEventDispatcher($dispatcher);
try {
@@ -165,7 +168,7 @@ class AuthenticationProviderManagerTest extends TestCase
->method('dispatch')
->with(AuthenticationEvents::AUTHENTICATION_SUCCESS, $this->equalTo(new AuthenticationEvent($token)));
$manager = new AuthenticationProviderManager(array($provider));
$manager = new AuthenticationProviderManager([$provider]);
$manager->setEventDispatcher($dispatcher);
$this->assertSame($token, $manager->authenticate($token));
@@ -176,18 +179,18 @@ class AuthenticationProviderManagerTest extends TestCase
$provider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface')->getMock();
$provider->expects($this->once())
->method('supports')
->will($this->returnValue($supports))
->willReturn($supports)
;
if (null !== $token) {
$provider->expects($this->once())
->method('authenticate')
->will($this->returnValue($token))
->willReturn($token)
;
} elseif (null !== $exception) {
$provider->expects($this->once())
->method('authenticate')
->will($this->throwException($this->getMockBuilder($exception)->setMethods(null)->getMock()))
->willThrowException($this->getMockBuilder($exception)->setMethods(null)->getMock())
;
}
@@ -53,12 +53,12 @@ class AuthenticationTrustResolverTest extends TestCase
protected function getAnonymousToken()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken')->setConstructorArgs(array('', ''))->getMock();
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken')->setConstructorArgs(['', ''])->getMock();
}
protected function getRememberMeToken()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken')->setMethods(array('setPersistent'))->disableOriginalConstructor()->getMock();
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken')->setMethods(['setPersistent'])->disableOriginalConstructor()->getMock();
}
protected function getResolver()
@@ -26,16 +26,16 @@ class AnonymousAuthenticationProviderTest extends TestCase
public function testAuthenticateWhenTokenIsNotSupported()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationException');
$this->expectExceptionMessage('The token is not supported by this authentication provider.');
$provider = $this->getProvider('foo');
$this->assertNull($provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()));
$provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testAuthenticateWhenSecretIsNotValid()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$provider = $this->getProvider('foo');
$provider->authenticate($this->getSupportedToken('bar'));
@@ -51,10 +51,10 @@ class AnonymousAuthenticationProviderTest extends TestCase
protected function getSupportedToken($secret)
{
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken')->setMethods(array('getSecret'))->disableOriginalConstructor()->getMock();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken')->setMethods(['getSecret'])->disableOriginalConstructor()->getMock();
$token->expects($this->any())
->method('getSecret')
->will($this->returnValue($secret))
->willReturn($secret)
;
return $token;
@@ -12,17 +12,19 @@
namespace Symfony\Component\Security\Core\Tests\Authentication\Provider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder;
use Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider;
use Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\User;
class DaoAuthenticationProviderTest extends TestCase
{
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationServiceException
* @group legacy
*/
public function testRetrieveUserWhenProviderDoesNotReturnAnUserInterface()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationServiceException');
$provider = $this->getProvider('fabien');
$method = new \ReflectionMethod($provider, 'retrieveUser');
$method->setAccessible(true);
@@ -30,15 +32,13 @@ class DaoAuthenticationProviderTest extends TestCase
$method->invoke($provider, 'fabien', $this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
*/
public function testRetrieveUserWhenUsernameIsNotFound()
{
$this->expectException('Symfony\Component\Security\Core\Exception\UsernameNotFoundException');
$userProvider = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface')->getMock();
$userProvider->expects($this->once())
->method('loadUserByUsername')
->will($this->throwException(new UsernameNotFoundException()))
->willThrowException(new UsernameNotFoundException())
;
$provider = new DaoAuthenticationProvider($userProvider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface')->getMock(), 'key', $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface')->getMock());
@@ -48,15 +48,13 @@ class DaoAuthenticationProviderTest extends TestCase
$method->invoke($provider, 'fabien', $this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationServiceException
*/
public function testRetrieveUserWhenAnExceptionOccurs()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationServiceException');
$userProvider = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface')->getMock();
$userProvider->expects($this->once())
->method('loadUserByUsername')
->will($this->throwException(new \RuntimeException()))
->willThrowException(new \RuntimeException())
;
$provider = new DaoAuthenticationProvider($userProvider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface')->getMock(), 'key', $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface')->getMock());
@@ -77,7 +75,7 @@ class DaoAuthenticationProviderTest extends TestCase
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getUser')
->will($this->returnValue($user))
->willReturn($user)
;
$provider = new DaoAuthenticationProvider($userProvider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface')->getMock(), 'key', $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface')->getMock());
@@ -95,7 +93,7 @@ class DaoAuthenticationProviderTest extends TestCase
$userProvider = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface')->getMock();
$userProvider->expects($this->once())
->method('loadUserByUsername')
->will($this->returnValue($user))
->willReturn($user)
;
$provider = new DaoAuthenticationProvider($userProvider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface')->getMock(), 'key', $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface')->getMock());
@@ -105,11 +103,9 @@ class DaoAuthenticationProviderTest extends TestCase
$this->assertSame($user, $method->invoke($provider, 'fabien', $this->getSupportedToken()));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testCheckAuthenticationWhenCredentialsAreEmpty()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$encoder = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface')->getMock();
$encoder
->expects($this->never())
@@ -124,7 +120,7 @@ class DaoAuthenticationProviderTest extends TestCase
$token
->expects($this->once())
->method('getCredentials')
->will($this->returnValue(''))
->willReturn('')
;
$method->invoke(
@@ -140,7 +136,7 @@ class DaoAuthenticationProviderTest extends TestCase
$encoder
->expects($this->once())
->method('isPasswordValid')
->will($this->returnValue(true))
->willReturn(true)
;
$provider = $this->getProvider(null, null, $encoder);
@@ -151,25 +147,23 @@ class DaoAuthenticationProviderTest extends TestCase
$token
->expects($this->once())
->method('getCredentials')
->will($this->returnValue('0'))
->willReturn('0')
;
$method->invoke(
$provider,
$this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock(),
new User('username', 'password'),
$token
);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testCheckAuthenticationWhenCredentialsAreNotValid()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$encoder = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface')->getMock();
$encoder->expects($this->once())
->method('isPasswordValid')
->will($this->returnValue(false))
->willReturn(false)
;
$provider = $this->getProvider(null, null, $encoder);
@@ -179,32 +173,30 @@ class DaoAuthenticationProviderTest extends TestCase
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getCredentials')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$method->invoke($provider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock(), $token);
$method->invoke($provider, new User('username', 'password'), $token);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testCheckAuthenticationDoesNotReauthenticateWhenPasswordHasChanged()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$user = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock();
$user->expects($this->once())
->method('getPassword')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getUser')
->will($this->returnValue($user));
->willReturn($user);
$dbUser = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock();
$dbUser->expects($this->once())
->method('getPassword')
->will($this->returnValue('newFoo'))
->willReturn('newFoo')
;
$provider = $this->getProvider();
@@ -218,18 +210,18 @@ class DaoAuthenticationProviderTest extends TestCase
$user = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock();
$user->expects($this->once())
->method('getPassword')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getUser')
->will($this->returnValue($user));
->willReturn($user);
$dbUser = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock();
$dbUser->expects($this->once())
->method('getPassword')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$provider = $this->getProvider();
@@ -243,7 +235,7 @@ class DaoAuthenticationProviderTest extends TestCase
$encoder = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface')->getMock();
$encoder->expects($this->once())
->method('isPasswordValid')
->will($this->returnValue(true))
->willReturn(true)
;
$provider = $this->getProvider(null, null, $encoder);
@@ -253,19 +245,19 @@ class DaoAuthenticationProviderTest extends TestCase
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getCredentials')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$method->invoke($provider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock(), $token);
$method->invoke($provider, new User('username', 'password'), $token);
}
protected function getSupportedToken()
{
$mock = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Authentication\\Token\\UsernamePasswordToken')->setMethods(array('getCredentials', 'getUser', 'getProviderKey'))->disableOriginalConstructor()->getMock();
$mock = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Authentication\\Token\\UsernamePasswordToken')->setMethods(['getCredentials', 'getUser', 'getProviderKey'])->disableOriginalConstructor()->getMock();
$mock
->expects($this->any())
->method('getProviderKey')
->will($this->returnValue('key'))
->willReturn('key')
;
return $mock;
@@ -277,7 +269,7 @@ class DaoAuthenticationProviderTest extends TestCase
if (null !== $user) {
$userProvider->expects($this->once())
->method('loadUserByUsername')
->will($this->returnValue($user))
->willReturn($user)
;
}
@@ -293,7 +285,7 @@ class DaoAuthenticationProviderTest extends TestCase
$encoderFactory
->expects($this->any())
->method('getEncoder')
->will($this->returnValue($passwordEncoder))
->willReturn($passwordEncoder)
;
return new DaoAuthenticationProvider($userProvider, $userChecker, 'key', $encoderFactory);
@@ -12,11 +12,14 @@
namespace Symfony\Component\Security\Core\Tests\Authentication\Provider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Ldap\Adapter\CollectionInterface;
use Symfony\Component\Ldap\Adapter\QueryInterface;
use Symfony\Component\Ldap\Entry;
use Symfony\Component\Ldap\Exception\ConnectionException;
use Symfony\Component\Ldap\LdapInterface;
use Symfony\Component\Security\Core\Authentication\Provider\LdapBindAuthenticationProvider;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Ldap\Exception\ConnectionException;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
@@ -25,12 +28,10 @@ use Symfony\Component\Security\Core\User\UserProviderInterface;
*/
class LdapBindAuthenticationProviderTest extends TestCase
{
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
* @expectedExceptionMessage The presented password must not be empty.
*/
public function testEmptyPasswordShouldThrowAnException()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$this->expectExceptionMessage('The presented password must not be empty.');
$userProvider = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserProviderInterface')->getMock();
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
@@ -42,18 +43,31 @@ class LdapBindAuthenticationProviderTest extends TestCase
$reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', '', 'key'));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
* @expectedExceptionMessage The presented password is invalid.
*/
public function testNullPasswordShouldThrowAnException()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$this->expectExceptionMessage('The presented password must not be empty.');
$userProvider = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserProviderInterface')->getMock();
$ldap = $this->getMockBuilder('Symfony\Component\Ldap\LdapInterface')->getMock();
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$provider = new LdapBindAuthenticationProvider($userProvider, $userChecker, 'key', $ldap);
$reflection = new \ReflectionMethod($provider, 'checkAuthentication');
$reflection->setAccessible(true);
$reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', null, 'key'));
}
public function testBindFailureShouldThrowAnException()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$this->expectExceptionMessage('The presented password is invalid.');
$userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock();
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$ldap
->expects($this->once())
->method('bind')
->will($this->throwException(new ConnectionException()))
->willThrowException(new ConnectionException())
;
$userChecker = $this->getMockBuilder(UserCheckerInterface::class)->getMock();
@@ -82,4 +96,71 @@ class LdapBindAuthenticationProviderTest extends TestCase
$reflection->invoke($provider, 'foo', new UsernamePasswordToken('foo', 'bar', 'key'));
}
public function testQueryForDn()
{
$userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock();
$collection = new \ArrayIterator([new Entry('')]);
$query = $this->getMockBuilder(QueryInterface::class)->getMock();
$query
->expects($this->once())
->method('execute')
->willReturn($collection)
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$ldap
->expects($this->once())
->method('escape')
->with('foo', '')
->willReturn('foo')
;
$ldap
->expects($this->once())
->method('query')
->with('{username}', 'foobar')
->willReturn($query)
;
$userChecker = $this->getMockBuilder(UserCheckerInterface::class)->getMock();
$provider = new LdapBindAuthenticationProvider($userProvider, $userChecker, 'key', $ldap);
$provider->setQueryString('{username}bar');
$reflection = new \ReflectionMethod($provider, 'checkAuthentication');
$reflection->setAccessible(true);
$reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', 'bar', 'key'));
}
public function testEmptyQueryResultShouldThrowAnException()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$this->expectExceptionMessage('The presented username is invalid.');
$userProvider = $this->getMockBuilder(UserProviderInterface::class)->getMock();
$collection = $this->getMockBuilder(CollectionInterface::class)->getMock();
$query = $this->getMockBuilder(QueryInterface::class)->getMock();
$query
->expects($this->once())
->method('execute')
->willReturn($collection)
;
$ldap = $this->getMockBuilder(LdapInterface::class)->getMock();
$ldap
->expects($this->once())
->method('query')
->willReturn($query)
;
$userChecker = $this->getMockBuilder(UserCheckerInterface::class)->getMock();
$provider = new LdapBindAuthenticationProvider($userProvider, $userChecker, 'key', $ldap);
$provider->setQueryString('{username}bar');
$reflection = new \ReflectionMethod($provider, 'checkAuthentication');
$reflection->setAccessible(true);
$reflection->invoke($provider, new User('foo', null), new UsernamePasswordToken('foo', 'bar', 'key'));
}
}
@@ -31,23 +31,23 @@ class PreAuthenticatedAuthenticationProviderTest extends TestCase
$token
->expects($this->once())
->method('getProviderKey')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$this->assertFalse($provider->supports($token));
}
public function testAuthenticateWhenTokenIsNotSupported()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationException');
$this->expectExceptionMessage('The token is not supported by this authentication provider.');
$provider = $this->getProvider();
$this->assertNull($provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()));
$provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testAuthenticateWhenNoUserIsSet()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$provider = $this->getProvider();
$provider->authenticate($this->getSupportedToken(''));
}
@@ -58,7 +58,7 @@ class PreAuthenticatedAuthenticationProviderTest extends TestCase
$user
->expects($this->once())
->method('getRoles')
->will($this->returnValue(array()))
->willReturn([])
;
$provider = $this->getProvider($user);
@@ -66,22 +66,20 @@ class PreAuthenticatedAuthenticationProviderTest extends TestCase
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken', $token);
$this->assertEquals('pass', $token->getCredentials());
$this->assertEquals('key', $token->getProviderKey());
$this->assertEquals(array(), $token->getRoles());
$this->assertEquals(array('foo' => 'bar'), $token->getAttributes(), '->authenticate() copies token attributes');
$this->assertEquals([], $token->getRoles());
$this->assertEquals(['foo' => 'bar'], $token->getAttributes(), '->authenticate() copies token attributes');
$this->assertSame($user, $token->getUser());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\LockedException
*/
public function testAuthenticateWhenUserCheckerThrowsException()
{
$this->expectException('Symfony\Component\Security\Core\Exception\LockedException');
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$userChecker->expects($this->once())
->method('checkPostAuth')
->will($this->throwException(new LockedException()))
->willThrowException(new LockedException())
;
$provider = $this->getProvider($user, $userChecker);
@@ -91,27 +89,27 @@ class PreAuthenticatedAuthenticationProviderTest extends TestCase
protected function getSupportedToken($user = false, $credentials = false)
{
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken')->setMethods(array('getUser', 'getCredentials', 'getProviderKey'))->disableOriginalConstructor()->getMock();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken')->setMethods(['getUser', 'getCredentials', 'getProviderKey'])->disableOriginalConstructor()->getMock();
if (false !== $user) {
$token->expects($this->once())
->method('getUser')
->will($this->returnValue($user))
->willReturn($user)
;
}
if (false !== $credentials) {
$token->expects($this->once())
->method('getCredentials')
->will($this->returnValue($credentials))
->willReturn($credentials)
;
}
$token
->expects($this->any())
->method('getProviderKey')
->will($this->returnValue('key'))
->willReturn('key')
;
$token->setAttributes(array('foo' => 'bar'));
$token->setAttributes(['foo' => 'bar']);
return $token;
}
@@ -122,7 +120,7 @@ class PreAuthenticatedAuthenticationProviderTest extends TestCase
if (null !== $user) {
$userProvider->expects($this->once())
->method('loadUserByUsername')
->will($this->returnValue($user))
->willReturn($user)
;
}
@@ -13,8 +13,10 @@ namespace Symfony\Component\Security\Core\Tests\Authentication\Provider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Provider\RememberMeAuthenticationProvider;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Exception\DisabledException;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\User\User;
class RememberMeAuthenticationProviderTest extends TestCase
{
@@ -24,36 +26,46 @@ class RememberMeAuthenticationProviderTest extends TestCase
$this->assertTrue($provider->supports($this->getSupportedToken()));
$this->assertFalse($provider->supports($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()));
$this->assertFalse($provider->supports($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken')->disableOriginalConstructor()->getMock()));
}
public function testAuthenticateWhenTokenIsNotSupported()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationException');
$this->expectExceptionMessage('The token is not supported by this authentication provider.');
$provider = $this->getProvider();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$this->assertNull($provider->authenticate($token));
$provider->authenticate($token);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testAuthenticateWhenSecretsDoNotMatch()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$provider = $this->getProvider(null, 'secret1');
$token = $this->getSupportedToken(null, 'secret2');
$provider->authenticate($token);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\DisabledException
*/
public function testAuthenticateThrowsOnNonUserInterfaceInstance()
{
$this->expectException('Symfony\Component\Security\Core\Exception\LogicException');
$this->expectExceptionMessage('Method "Symfony\Component\Security\Core\Authentication\Token\RememberMeToken::getUser()" must return a "Symfony\Component\Security\Core\User\UserInterface" instance, "string" returned.');
$provider = $this->getProvider();
$token = new RememberMeToken(new User('dummyuser', null), 'foo', 'test');
$token->setUser('stringish-user');
$provider->authenticate($token);
}
public function testAuthenticateWhenPreChecksFails()
{
$this->expectException('Symfony\Component\Security\Core\Exception\DisabledException');
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$userChecker->expects($this->once())
->method('checkPreAuth')
->will($this->throwException(new DisabledException()));
->willThrowException(new DisabledException());
$provider = $this->getProvider($userChecker);
@@ -65,7 +77,7 @@ class RememberMeAuthenticationProviderTest extends TestCase
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->exactly(2))
->method('getRoles')
->will($this->returnValue(array('ROLE_FOO')));
->willReturn(['ROLE_FOO']);
$provider = $this->getProvider();
@@ -74,7 +86,7 @@ class RememberMeAuthenticationProviderTest extends TestCase
$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([new Role('ROLE_FOO')], $authToken->getRoles());
$this->assertEquals('', $authToken->getCredentials());
}
@@ -85,14 +97,14 @@ class RememberMeAuthenticationProviderTest extends TestCase
$user
->expects($this->any())
->method('getRoles')
->will($this->returnValue(array()));
->willReturn([]);
}
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken')->setMethods(array('getProviderKey'))->setConstructorArgs(array($user, 'foo', $secret))->getMock();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken')->setMethods(['getProviderKey'])->setConstructorArgs([$user, 'foo', $secret])->getMock();
$token
->expects($this->once())
->method('getProviderKey')
->will($this->returnValue('foo'));
->willReturn('foo');
return $token;
}
@@ -18,6 +18,7 @@ use Symfony\Component\Security\Core\Exception\CredentialsExpiredException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Core\User\UserInterface;
class UserAuthenticationProviderTest extends TestCase
{
@@ -31,126 +32,135 @@ class UserAuthenticationProviderTest extends TestCase
public function testAuthenticateWhenTokenIsNotSupported()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationException');
$this->expectExceptionMessage('The token is not supported by this authentication provider.');
$provider = $this->getProvider();
$this->assertNull($provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()));
$provider->authenticate($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
*/
public function testAuthenticateWhenUsernameIsNotFound()
{
$this->expectException('Symfony\Component\Security\Core\Exception\UsernameNotFoundException');
$provider = $this->getProvider(false, false);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->throwException(new UsernameNotFoundException()))
->willThrowException(new UsernameNotFoundException())
;
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testAuthenticateWhenUsernameIsNotFoundAndHideIsTrue()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$provider = $this->getProvider(false, true);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->throwException(new UsernameNotFoundException()))
->willThrowException(new UsernameNotFoundException())
;
$provider->authenticate($this->getSupportedToken());
}
public function testAuthenticateWhenCredentialsAreInvalidAndHideIsTrue()
{
$provider = $this->getProvider();
$provider->expects($this->once())
->method('retrieveUser')
->willReturn($this->createMock(UserInterface::class))
;
$provider->expects($this->once())
->method('checkAuthentication')
->willThrowException(new BadCredentialsException())
;
$this->expectException(BadCredentialsException::class);
$this->expectExceptionMessage('Bad credentials.');
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationServiceException
* @group legacy
*/
public function testAuthenticateWhenProviderDoesNotReturnAnUserInterface()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationServiceException');
$provider = $this->getProvider(false, true);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue(null))
->willReturn(null)
;
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\CredentialsExpiredException
*/
public function testAuthenticateWhenPreChecksFails()
{
$this->expectException(BadCredentialsException::class);
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$userChecker->expects($this->once())
->method('checkPreAuth')
->will($this->throwException(new CredentialsExpiredException()))
->willThrowException(new CredentialsExpiredException())
;
$provider = $this->getProvider($userChecker);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock()))
->willReturn($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock())
;
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AccountExpiredException
*/
public function testAuthenticateWhenPostChecksFails()
{
$this->expectException(BadCredentialsException::class);
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$userChecker->expects($this->once())
->method('checkPostAuth')
->will($this->throwException(new AccountExpiredException()))
->willThrowException(new AccountExpiredException())
;
$provider = $this->getProvider($userChecker);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock()))
->willReturn($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock())
;
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
* @expectedExceptionMessage Bad credentials
*/
public function testAuthenticateWhenPostCheckAuthenticationFails()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$this->expectExceptionMessage('Bad credentials.');
$provider = $this->getProvider();
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock()))
->willReturn($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock())
;
$provider->expects($this->once())
->method('checkAuthentication')
->will($this->throwException(new BadCredentialsException()))
->willThrowException(new CredentialsExpiredException())
;
$provider->authenticate($this->getSupportedToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
* @expectedExceptionMessage Foo
*/
public function testAuthenticateWhenPostCheckAuthenticationFailsWithHideFalse()
{
$this->expectException('Symfony\Component\Security\Core\Exception\BadCredentialsException');
$this->expectExceptionMessage('Foo');
$provider = $this->getProvider(false, false);
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock()))
->willReturn($this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock())
;
$provider->expects($this->once())
->method('checkAuthentication')
->will($this->throwException(new BadCredentialsException('Foo')))
->willThrowException(new BadCredentialsException('Foo'))
;
$provider->authenticate($this->getSupportedToken());
@@ -161,33 +171,33 @@ class UserAuthenticationProviderTest extends TestCase
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->once())
->method('getRoles')
->will($this->returnValue(array('ROLE_FOO')))
->willReturn(['ROLE_FOO'])
;
$provider = $this->getProvider();
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($user))
->willReturn($user)
;
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getCredentials')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$token->expects($this->once())
->method('getRoles')
->will($this->returnValue(array()))
->willReturn([])
;
$authToken = $provider->authenticate($token);
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $authToken);
$this->assertSame($user, $authToken->getUser());
$this->assertEquals(array(new Role('ROLE_FOO')), $authToken->getRoles());
$this->assertEquals([new Role('ROLE_FOO')], $authToken->getRoles());
$this->assertEquals('foo', $authToken->getCredentials());
$this->assertEquals(array('foo' => 'bar'), $authToken->getAttributes(), '->authenticate() copies token attributes');
$this->assertEquals(['foo' => 'bar'], $authToken->getAttributes(), '->authenticate() copies token attributes');
}
public function testAuthenticateWithPreservingRoleSwitchUserRole()
@@ -195,47 +205,47 @@ class UserAuthenticationProviderTest extends TestCase
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->once())
->method('getRoles')
->will($this->returnValue(array('ROLE_FOO')))
->willReturn(['ROLE_FOO'])
;
$provider = $this->getProvider();
$provider->expects($this->once())
->method('retrieveUser')
->will($this->returnValue($user))
->willReturn($user)
;
$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getCredentials')
->will($this->returnValue('foo'))
->willReturn('foo')
;
$switchUserRole = new SwitchUserRole('foo', $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
$token->expects($this->once())
->method('getRoles')
->will($this->returnValue(array($switchUserRole)))
->willReturn([$switchUserRole])
;
$authToken = $provider->authenticate($token);
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $authToken);
$this->assertSame($user, $authToken->getUser());
$this->assertContains(new Role('ROLE_FOO'), $authToken->getRoles(), '', false, false);
$this->assertContains($switchUserRole, $authToken->getRoles(), '', false, false);
$this->assertContainsEquals(new Role('ROLE_FOO'), $authToken->getRoles());
$this->assertContainsEquals($switchUserRole, $authToken->getRoles());
$this->assertEquals('foo', $authToken->getCredentials());
$this->assertEquals(array('foo' => 'bar'), $authToken->getAttributes(), '->authenticate() copies token attributes');
$this->assertEquals(['foo' => 'bar'], $authToken->getAttributes(), '->authenticate() copies token attributes');
}
protected function getSupportedToken()
{
$mock = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken')->setMethods(array('getCredentials', 'getProviderKey', 'getRoles'))->disableOriginalConstructor()->getMock();
$mock = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken')->setMethods(['getCredentials', 'getProviderKey', 'getRoles'])->disableOriginalConstructor()->getMock();
$mock
->expects($this->any())
->method('getProviderKey')
->will($this->returnValue('key'))
->willReturn('key')
;
$mock->setAttributes(array('foo' => 'bar'));
$mock->setAttributes(['foo' => 'bar']);
return $mock;
}
@@ -246,6 +256,6 @@ class UserAuthenticationProviderTest extends TestCase
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
}
return $this->getMockForAbstractClass('Symfony\Component\Security\Core\Authentication\Provider\UserAuthenticationProvider', array($userChecker, 'key', $hide));
return $this->getMockForAbstractClass('Symfony\Component\Security\Core\Authentication\Provider\UserAuthenticationProvider', [$userChecker, 'key', $hide]);
}
}
@@ -12,8 +12,8 @@
namespace Symfony\Component\Security\Core\Tests\Authentication\RememberMe;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken;
use Symfony\Component\Security\Core\Authentication\RememberMe\InMemoryTokenProvider;
use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken;
class InMemoryTokenProviderTest extends TestCase
{
@@ -27,11 +27,9 @@ class InMemoryTokenProviderTest extends TestCase
$this->assertSame($provider->loadTokenBySeries('foo'), $token);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\TokenNotFoundException
*/
public function testLoadTokenBySeriesThrowsNotFoundException()
{
$this->expectException('Symfony\Component\Security\Core\Exception\TokenNotFoundException');
$provider = new InMemoryTokenProvider();
$provider->loadTokenBySeries('foo');
}
@@ -49,11 +47,9 @@ class InMemoryTokenProviderTest extends TestCase
$this->assertSame($token->getLastUsed(), $lastUsed);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\TokenNotFoundException
*/
public function testDeleteToken()
{
$this->expectException('Symfony\Component\Security\Core\Exception\TokenNotFoundException');
$provider = new InMemoryTokenProvider();
$token = new PersistentToken('foo', 'foo', 'foo', 'foo', new \DateTime());
@@ -36,16 +36,21 @@ class ConcreteToken extends AbstractToken
{
private $credentials = 'credentials_value';
public function __construct($user, array $roles = array())
public function __construct($user, array $roles = [])
{
parent::__construct($roles);
$this->setUser($user);
}
/**
* {@inheritdoc}
*/
public function serialize()
{
return serialize(array($this->credentials, parent::serialize()));
$serialized = [$this->credentials, parent::serialize(true)];
return $this->doSerialize($serialized, \func_num_args() ? func_get_arg(0) : null);
}
public function unserialize($serialized)
@@ -64,7 +69,7 @@ class AbstractTokenTest extends TestCase
{
public function testGetUsername()
{
$token = $this->getToken(array('ROLE_FOO'));
$token = $this->getToken(['ROLE_FOO']);
$token->setUser('fabien');
$this->assertEquals('fabien', $token->getUsername());
@@ -72,14 +77,14 @@ class AbstractTokenTest extends TestCase
$this->assertEquals('fabien', $token->getUsername());
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->once())->method('getUsername')->will($this->returnValue('fabien'));
$user->expects($this->once())->method('getUsername')->willReturn('fabien');
$token->setUser($user);
$this->assertEquals('fabien', $token->getUsername());
}
public function testEraseCredentials()
{
$token = $this->getToken(array('ROLE_FOO'));
$token = $this->getToken(['ROLE_FOO']);
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->expects($this->once())->method('eraseCredentials');
@@ -90,8 +95,8 @@ class AbstractTokenTest extends TestCase
public function testSerialize()
{
$token = $this->getToken(array('ROLE_FOO', new Role('ROLE_BAR')));
$token->setAttributes(array('foo' => 'bar'));
$token = $this->getToken(['ROLE_FOO', new Role('ROLE_BAR')]);
$token->setAttributes(['foo' => 'bar']);
$uToken = unserialize(serialize($token));
@@ -101,7 +106,7 @@ class AbstractTokenTest extends TestCase
public function testSerializeWithRoleObjects()
{
$user = new User('name', 'password', array(new Role('ROLE_FOO'), new Role('ROLE_BAR')));
$user = new User('name', 'password', [new Role('ROLE_FOO'), new Role('ROLE_BAR')]);
$token = new ConcreteToken($user, $user->getRoles());
$serialized = serialize($token);
@@ -115,9 +120,9 @@ class AbstractTokenTest extends TestCase
public function testSerializeParent()
{
$user = new TestUser('fabien');
$token = new ConcreteToken($user, array('ROLE_FOO'));
$token = new ConcreteToken($user, ['ROLE_FOO']);
$parentToken = new ConcreteToken($user, array(new SwitchUserRole('ROLE_PREVIOUS', $token)));
$parentToken = new ConcreteToken($user, [new SwitchUserRole('ROLE_PREVIOUS', $token)]);
$uToken = unserialize(serialize($parentToken));
$this->assertEquals(
@@ -128,14 +133,14 @@ class AbstractTokenTest extends TestCase
public function testConstructor()
{
$token = $this->getToken(array('ROLE_FOO'));
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
$token = $this->getToken(['ROLE_FOO']);
$this->assertEquals([new Role('ROLE_FOO')], $token->getRoles());
$token = $this->getToken(array(new Role('ROLE_FOO')));
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
$token = $this->getToken([new Role('ROLE_FOO')]);
$this->assertEquals([new Role('ROLE_FOO')], $token->getRoles());
$token = $this->getToken(array(new Role('ROLE_FOO'), 'ROLE_BAR'));
$this->assertEquals(array(new Role('ROLE_FOO'), new Role('ROLE_BAR')), $token->getRoles());
$token = $this->getToken([new Role('ROLE_FOO'), 'ROLE_BAR']);
$this->assertEquals([new Role('ROLE_FOO'), new Role('ROLE_BAR')], $token->getRoles());
}
public function testAuthenticatedFlag()
@@ -152,7 +157,7 @@ class AbstractTokenTest extends TestCase
public function testAttributes()
{
$attributes = array('foo' => 'bar');
$attributes = ['foo' => 'bar'];
$token = $this->getToken();
$token->setAttributes($attributes);
@@ -187,12 +192,12 @@ class AbstractTokenTest extends TestCase
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$advancedUser = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
return array(
array($advancedUser),
array($user),
array(new TestUser('foo')),
array('foo'),
);
return [
[$advancedUser],
[$user],
[new TestUser('foo')],
['foo'],
];
}
/**
@@ -216,50 +221,50 @@ class AbstractTokenTest extends TestCase
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$advancedUser = $this->getMockBuilder('Symfony\Component\Security\Core\User\AdvancedUserInterface')->getMock();
return array(
array(
return [
[
'foo', 'bar',
),
array(
],
[
'foo', new TestUser('bar'),
),
array(
],
[
'foo', $user,
),
array(
],
[
'foo', $advancedUser,
),
array(
],
[
$user, 'foo',
),
array(
],
[
$advancedUser, 'foo',
),
array(
],
[
$user, new TestUser('foo'),
),
array(
],
[
$advancedUser, new TestUser('foo'),
),
array(
],
[
new TestUser('foo'), new TestUser('bar'),
),
array(
],
[
new TestUser('foo'), 'bar',
),
array(
],
[
new TestUser('foo'), $user,
),
array(
],
[
new TestUser('foo'), $advancedUser,
),
array(
],
[
$user, $advancedUser,
),
array(
],
[
$advancedUser, $user,
),
);
],
];
}
/**
@@ -278,8 +283,8 @@ class AbstractTokenTest extends TestCase
$this->assertTrue($token->isAuthenticated());
}
protected function getToken(array $roles = array())
protected function getToken(array $roles = [])
{
return $this->getMockForAbstractClass('Symfony\Component\Security\Core\Authentication\Token\AbstractToken', array($roles));
return $this->getMockForAbstractClass('Symfony\Component\Security\Core\Authentication\Token\AbstractToken', [$roles]);
}
}
@@ -22,8 +22,8 @@ class AnonymousTokenTest extends TestCase
$token = new AnonymousToken('foo', 'bar');
$this->assertTrue($token->isAuthenticated());
$token = new AnonymousToken('foo', 'bar', array('ROLE_FOO'));
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
$token = new AnonymousToken('foo', 'bar', ['ROLE_FOO']);
$this->assertEquals([new Role('ROLE_FOO')], $token->getRoles());
}
public function testGetKey()
@@ -22,9 +22,9 @@ class PreAuthenticatedTokenTest extends TestCase
$token = new PreAuthenticatedToken('foo', 'bar', 'key');
$this->assertFalse($token->isAuthenticated());
$token = new PreAuthenticatedToken('foo', 'bar', 'key', array('ROLE_FOO'));
$token = new PreAuthenticatedToken('foo', 'bar', 'key', ['ROLE_FOO']);
$this->assertTrue($token->isAuthenticated());
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
$this->assertEquals([new Role('ROLE_FOO')], $token->getRoles());
$this->assertEquals('key', $token->getProviderKey());
}
@@ -24,16 +24,14 @@ class RememberMeTokenTest extends TestCase
$this->assertEquals('fookey', $token->getProviderKey());
$this->assertEquals('foo', $token->getSecret());
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
$this->assertEquals([new Role('ROLE_FOO')], $token->getRoles());
$this->assertSame($user, $token->getUser());
$this->assertTrue($token->isAuthenticated());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testConstructorSecretCannotBeNull()
{
$this->expectException('InvalidArgumentException');
new RememberMeToken(
$this->getUser(),
null,
@@ -41,11 +39,9 @@ class RememberMeTokenTest extends TestCase
);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testConstructorSecretCannotBeEmptyString()
{
$this->expectException('InvalidArgumentException');
new RememberMeToken(
$this->getUser(),
'',
@@ -53,13 +49,13 @@ class RememberMeTokenTest extends TestCase
);
}
protected function getUser($roles = array('ROLE_FOO'))
protected function getUser($roles = ['ROLE_FOO'])
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user
->expects($this->once())
->method('getRoles')
->will($this->returnValue($roles))
->willReturn($roles)
;
return $user;
@@ -22,17 +22,15 @@ class UsernamePasswordTokenTest extends TestCase
$token = new UsernamePasswordToken('foo', 'bar', 'key');
$this->assertFalse($token->isAuthenticated());
$token = new UsernamePasswordToken('foo', 'bar', 'key', array('ROLE_FOO'));
$this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
$token = new UsernamePasswordToken('foo', 'bar', 'key', ['ROLE_FOO']);
$this->assertEquals([new Role('ROLE_FOO')], $token->getRoles());
$this->assertTrue($token->isAuthenticated());
$this->assertEquals('key', $token->getProviderKey());
}
/**
* @expectedException \LogicException
*/
public function testSetAuthenticatedToTrue()
{
$this->expectException('LogicException');
$token = new UsernamePasswordToken('foo', 'bar', 'key');
$token->setAuthenticated(true);
}
@@ -53,7 +51,7 @@ class UsernamePasswordTokenTest extends TestCase
public function testToString()
{
$token = new UsernamePasswordToken('foo', '', 'foo', array('A', 'B'));
$token = new UsernamePasswordToken('foo', '', 'foo', ['A', 'B']);
$this->assertEquals('UsernamePasswordToken(user="foo", authenticated=true, roles="A, B")', (string) $token);
}
}
@@ -12,17 +12,18 @@
namespace Symfony\Component\Security\Core\Tests\Authorization;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManager;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Exception\LogicException;
use Symfony\Component\Security\Core\Tests\Authorization\Stub\VoterWithoutInterface;
class AccessDecisionManagerTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
public function testSetUnsupportedStrategy()
{
new AccessDecisionManager(array($this->getVoter(VoterInterface::ACCESS_GRANTED)), 'fooBar');
$this->expectException('InvalidArgumentException');
new AccessDecisionManager([$this->getVoter(VoterInterface::ACCESS_GRANTED)], 'fooBar');
}
/**
@@ -33,7 +34,7 @@ class AccessDecisionManagerTest extends TestCase
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$manager = new AccessDecisionManager($voters, $strategy, $allowIfAllAbstainDecisions, $allowIfEqualGrantedDeniedDecisions);
$this->assertSame($expected, $manager->decide($token, array('ROLE_FOO')));
$this->assertSame($expected, $manager->decide($token, ['ROLE_FOO']));
}
/**
@@ -41,27 +42,27 @@ class AccessDecisionManagerTest extends TestCase
*/
public function testStrategiesWith2Roles($token, $strategy, $voter, $expected)
{
$manager = new AccessDecisionManager(array($voter), $strategy);
$manager = new AccessDecisionManager([$voter], $strategy);
$this->assertSame($expected, $manager->decide($token, array('ROLE_FOO', 'ROLE_BAR')));
$this->assertSame($expected, $manager->decide($token, ['ROLE_FOO', 'ROLE_BAR']));
}
public function getStrategiesWith2RolesTests()
{
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
return array(
array($token, 'affirmative', $this->getVoter(VoterInterface::ACCESS_DENIED), false),
array($token, 'affirmative', $this->getVoter(VoterInterface::ACCESS_GRANTED), true),
return [
[$token, 'affirmative', $this->getVoter(VoterInterface::ACCESS_DENIED), false],
[$token, 'affirmative', $this->getVoter(VoterInterface::ACCESS_GRANTED), true],
array($token, 'consensus', $this->getVoter(VoterInterface::ACCESS_DENIED), false),
array($token, 'consensus', $this->getVoter(VoterInterface::ACCESS_GRANTED), true),
[$token, 'consensus', $this->getVoter(VoterInterface::ACCESS_DENIED), false],
[$token, 'consensus', $this->getVoter(VoterInterface::ACCESS_GRANTED), true],
array($token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_DENIED, VoterInterface::ACCESS_DENIED), false),
array($token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_DENIED, VoterInterface::ACCESS_GRANTED), false),
array($token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_GRANTED, VoterInterface::ACCESS_DENIED), false),
array($token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_GRANTED, VoterInterface::ACCESS_GRANTED), true),
);
[$token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_DENIED, VoterInterface::ACCESS_DENIED), false],
[$token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_DENIED, VoterInterface::ACCESS_GRANTED), false],
[$token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_GRANTED, VoterInterface::ACCESS_DENIED), false],
[$token, 'unanimous', $this->getVoterFor2Roles($token, VoterInterface::ACCESS_GRANTED, VoterInterface::ACCESS_GRANTED), true],
];
}
protected function getVoterFor2Roles($token, $vote1, $vote2)
@@ -69,10 +70,10 @@ class AccessDecisionManagerTest extends TestCase
$voter = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\Voter\VoterInterface')->getMock();
$voter->expects($this->any())
->method('vote')
->will($this->returnValueMap(array(
array($token, null, array('ROLE_FOO'), $vote1),
array($token, null, array('ROLE_BAR'), $vote2),
)))
->willReturnMap([
[$token, null, ['ROLE_FOO'], $vote1],
[$token, null, ['ROLE_BAR'], $vote2],
])
;
return $voter;
@@ -80,42 +81,42 @@ class AccessDecisionManagerTest extends TestCase
public function getStrategyTests()
{
return array(
return [
// affirmative
array(AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(1, 0, 0), false, true, true),
array(AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(1, 2, 0), false, true, true),
array(AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(0, 1, 0), false, true, false),
array(AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(0, 0, 1), false, true, false),
array(AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(0, 0, 1), true, true, true),
[AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(1, 0, 0), false, true, true],
[AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(1, 2, 0), false, true, true],
[AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(0, 1, 0), false, true, false],
[AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(0, 0, 1), false, true, false],
[AccessDecisionManager::STRATEGY_AFFIRMATIVE, $this->getVoters(0, 0, 1), true, true, true],
// consensus
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(1, 0, 0), false, true, true),
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(1, 2, 0), false, true, false),
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 1, 0), false, true, true),
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(1, 0, 0), false, true, true],
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(1, 2, 0), false, true, false],
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 1, 0), false, true, true],
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(0, 0, 1), false, true, false),
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(0, 0, 1), false, true, false],
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(0, 0, 1), true, true, true),
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(0, 0, 1), true, true, true],
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 0), false, true, true),
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 1), false, true, true),
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 0), false, true, true],
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 1), false, true, true],
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 0), false, false, false),
array(AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 1), false, false, false),
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 0), false, false, false],
[AccessDecisionManager::STRATEGY_CONSENSUS, $this->getVoters(2, 2, 1), false, false, false],
// unanimous
array(AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(1, 0, 0), false, true, true),
array(AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(1, 0, 1), false, true, true),
array(AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(1, 1, 0), false, true, false),
[AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(1, 0, 0), false, true, true],
[AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(1, 0, 1), false, true, true],
[AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(1, 1, 0), false, true, false],
array(AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(0, 0, 2), false, true, false),
array(AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(0, 0, 2), true, true, true),
);
[AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(0, 0, 2), false, true, false],
[AccessDecisionManager::STRATEGY_UNANIMOUS, $this->getVoters(0, 0, 2), true, true, true],
];
}
protected function getVoters($grants, $denies, $abstains)
{
$voters = array();
$voters = [];
for ($i = 0; $i < $grants; ++$i) {
$voters[] = $this->getVoter(VoterInterface::ACCESS_GRANTED);
}
@@ -134,8 +135,34 @@ class AccessDecisionManagerTest extends TestCase
$voter = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\Voter\VoterInterface')->getMock();
$voter->expects($this->any())
->method('vote')
->will($this->returnValue($vote));
->willReturn($vote);
return $voter;
}
public function testVotingWrongTypeNoVoteMethod()
{
$exception = LogicException::class;
$message = sprintf('"stdClass" should implement the "%s" interface when used as voter.', VoterInterface::class);
$this->expectException($exception);
$this->expectExceptionMessage($message);
$adm = new AccessDecisionManager([new \stdClass()]);
$token = $this->getMockBuilder(TokenInterface::class)->getMock();
$adm->decide($token, ['TEST']);
}
/**
* @group legacy
* @expectedDeprecation Calling vote() on an voter without Symfony\Component\Security\Core\Authorization\Voter\VoterInterface is deprecated as of 3.4 and will be removed in 4.0. Implement the Symfony\Component\Security\Core\Authorization\Voter\VoterInterface on your voter.
*/
public function testVotingWrongTypeWithVote()
{
$adm = new AccessDecisionManager([new VoterWithoutInterface()]);
$token = $this->getMockBuilder(TokenInterface::class)->getMock();
$adm->decide($token, ['TEST']);
}
}
@@ -46,7 +46,7 @@ class AuthorizationCheckerTest extends TestCase
->expects($this->once())
->method('authenticate')
->with($this->equalTo($token))
->will($this->returnValue($newToken));
->willReturn($newToken);
// default with() isn't a strict check
$tokenComparison = function ($value) use ($newToken) {
@@ -58,19 +58,17 @@ class AuthorizationCheckerTest extends TestCase
->expects($this->once())
->method('decide')
->with($this->callback($tokenComparison))
->will($this->returnValue(true));
->willReturn(true);
// first run the token has not been re-authenticated yet, after isGranted is called, it should be equal
$this->assertFalse($newToken === $this->tokenStorage->getToken());
$this->assertNotSame($newToken, $this->tokenStorage->getToken());
$this->assertTrue($this->authorizationChecker->isGranted('foo'));
$this->assertTrue($newToken === $this->tokenStorage->getToken());
$this->assertSame($newToken, $this->tokenStorage->getToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
*/
public function testVoteWithoutAuthenticationToken()
{
$this->expectException('Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException');
$this->authorizationChecker->isGranted('ROLE_FOO');
}
@@ -83,18 +81,18 @@ class AuthorizationCheckerTest extends TestCase
$token
->expects($this->once())
->method('isAuthenticated')
->will($this->returnValue(true));
->willReturn(true);
$this->accessDecisionManager
->expects($this->once())
->method('decide')
->will($this->returnValue($decide));
->willReturn($decide);
$this->tokenStorage->setToken($token);
$this->assertTrue($decide === $this->authorizationChecker->isGranted('ROLE_FOO'));
$this->assertSame($decide, $this->authorizationChecker->isGranted('ROLE_FOO'));
}
public function isGrantedProvider()
{
return array(array(true), array(false));
return [[true], [false]];
}
}
@@ -1,44 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Core\Tests\Authorization;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManager;
use Symfony\Component\Security\Core\Authorization\DebugAccessDecisionManager;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class DebugAccessDecisionManagerTest extends TestCase
{
/**
* @dataProvider provideObjectsAndLogs
*/
public function testDecideLog($expectedLog, $object)
{
$adm = new DebugAccessDecisionManager(new AccessDecisionManager());
$adm->decide($this->getMockBuilder(TokenInterface::class)->getMock(), array('ATTRIBUTE_1'), $object);
$this->assertSame($expectedLog, $adm->getDecisionLog());
}
public function provideObjectsAndLogs()
{
$object = new \stdClass();
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => null, 'result' => false)), null);
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => true, 'result' => false)), true);
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => 'jolie string', 'result' => false)), 'jolie string');
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => 12345, 'result' => false)), 12345);
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => $x = fopen(__FILE__, 'r'), 'result' => false)), $x);
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => $x = array(), 'result' => false)), $x);
yield array(array(array('attributes' => array('ATTRIBUTE_1'), 'object' => $object, 'result' => false)), $object);
}
}
@@ -12,11 +12,11 @@
namespace Symfony\Component\Security\Core\Tests\Authorization;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authorization\ExpressionLanguage;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authorization\ExpressionLanguage;
use Symfony\Component\Security\Core\User\User;
class ExpressionLanguageTest extends TestCase
@@ -24,14 +24,14 @@ class ExpressionLanguageTest extends TestCase
/**
* @dataProvider provider
*/
public function testIsAuthenticated($token, $expression, $result, array $roles = array())
public function testIsAuthenticated($token, $expression, $result, array $roles = [])
{
$anonymousTokenClass = 'Symfony\\Component\\Security\\Core\\Authentication\\Token\\AnonymousToken';
$rememberMeTokenClass = 'Symfony\\Component\\Security\\Core\\Authentication\\Token\\RememberMeToken';
$expressionLanguage = new ExpressionLanguage();
$trustResolver = new AuthenticationTrustResolver($anonymousTokenClass, $rememberMeTokenClass);
$context = array();
$context = [];
$context['trust_resolver'] = $trustResolver;
$context['token'] = $token;
$context['roles'] = $roles;
@@ -41,7 +41,7 @@ class ExpressionLanguageTest extends TestCase
public function provider()
{
$roles = array('ROLE_USER', 'ROLE_ADMIN');
$roles = ['ROLE_USER', 'ROLE_ADMIN'];
$user = new User('username', 'password', $roles);
$noToken = null;
@@ -49,32 +49,32 @@ class ExpressionLanguageTest extends TestCase
$rememberMeToken = new RememberMeToken($user, 'providerkey', 'firewall');
$usernamePasswordToken = new UsernamePasswordToken('username', 'password', 'providerkey', $roles);
return array(
array($noToken, 'is_anonymous()', false),
array($noToken, 'is_authenticated()', false),
array($noToken, 'is_fully_authenticated()', false),
array($noToken, 'is_remember_me()', false),
array($noToken, "has_role('ROLE_USER')", false),
return [
[$noToken, 'is_anonymous()', false],
[$noToken, 'is_authenticated()', false],
[$noToken, 'is_fully_authenticated()', false],
[$noToken, 'is_remember_me()', false],
[$noToken, "has_role('ROLE_USER')", false],
array($anonymousToken, 'is_anonymous()', true),
array($anonymousToken, 'is_authenticated()', false),
array($anonymousToken, 'is_fully_authenticated()', false),
array($anonymousToken, 'is_remember_me()', false),
array($anonymousToken, "has_role('ROLE_USER')", false),
[$anonymousToken, 'is_anonymous()', true],
[$anonymousToken, 'is_authenticated()', false],
[$anonymousToken, 'is_fully_authenticated()', false],
[$anonymousToken, 'is_remember_me()', false],
[$anonymousToken, "has_role('ROLE_USER')", false],
array($rememberMeToken, 'is_anonymous()', false),
array($rememberMeToken, 'is_authenticated()', true),
array($rememberMeToken, 'is_fully_authenticated()', false),
array($rememberMeToken, 'is_remember_me()', true),
array($rememberMeToken, "has_role('ROLE_FOO')", false, $roles),
array($rememberMeToken, "has_role('ROLE_USER')", true, $roles),
[$rememberMeToken, 'is_anonymous()', false],
[$rememberMeToken, 'is_authenticated()', true],
[$rememberMeToken, 'is_fully_authenticated()', false],
[$rememberMeToken, 'is_remember_me()', true],
[$rememberMeToken, "has_role('ROLE_FOO')", false, $roles],
[$rememberMeToken, "has_role('ROLE_USER')", true, $roles],
array($usernamePasswordToken, 'is_anonymous()', false),
array($usernamePasswordToken, 'is_authenticated()', true),
array($usernamePasswordToken, 'is_fully_authenticated()', true),
array($usernamePasswordToken, 'is_remember_me()', false),
array($usernamePasswordToken, "has_role('ROLE_FOO')", false, $roles),
array($usernamePasswordToken, "has_role('ROLE_USER')", true, $roles),
);
[$usernamePasswordToken, 'is_anonymous()', false],
[$usernamePasswordToken, 'is_authenticated()', true],
[$usernamePasswordToken, 'is_fully_authenticated()', true],
[$usernamePasswordToken, 'is_remember_me()', false],
[$usernamePasswordToken, "has_role('ROLE_FOO')", false, $roles],
[$usernamePasswordToken, "has_role('ROLE_USER')", true, $roles],
];
}
}

Some files were not shown because too many files have changed in this diff Show More