diff options
35 files changed, 216 insertions, 111 deletions
diff --git a/Acl/Dbal/AclProvider.php b/Acl/Dbal/AclProvider.php index 7c512ad..1fade3b 100644 --- a/Acl/Dbal/AclProvider.php +++ b/Acl/Dbal/AclProvider.php @@ -177,13 +177,13 @@ class AclProvider implements AclProviderInterface if ($currentBatchesCount > 0 && (self::MAX_BATCH_SIZE === $currentBatchesCount || ($i + 1) === $c)) { try { $loadedBatch = $this->lookupObjectIdentities($currentBatch, $sids, $oidLookup); - } catch (AclNotFoundException $aclNotFoundexception) { + } catch (AclNotFoundException $e) { if ($result->count()) { $partialResultException = new NotAllAclsFoundException('The provider could not find ACLs for all object identities.'); $partialResultException->setPartialResult($result); throw $partialResultException; } else { - throw $aclNotFoundexception; + throw $e; } } foreach ($loadedBatch as $loadedOid) { diff --git a/Acl/Dbal/MutableAclProvider.php b/Acl/Dbal/MutableAclProvider.php index 30772b4..c62bdd4 100644 --- a/Acl/Dbal/MutableAclProvider.php +++ b/Acl/Dbal/MutableAclProvider.php @@ -62,10 +62,10 @@ class MutableAclProvider extends AclProvider implements MutableAclProviderInterf $this->connection->executeQuery($this->getInsertObjectIdentityRelationSql($pk, $pk)); $this->connection->commit(); - } catch (\Exception $failed) { + } catch (\Exception $e) { $this->connection->rollBack(); - throw $failed; + throw $e; } // re-read the ACL from the database to ensure proper caching, etc. @@ -90,10 +90,10 @@ class MutableAclProvider extends AclProvider implements MutableAclProviderInterf $this->deleteObjectIdentity($oidPK); $this->connection->commit(); - } catch (\Exception $failed) { + } catch (\Exception $e) { $this->connection->rollBack(); - throw $failed; + throw $e; } // evict the ACL from the in-memory identity map @@ -324,10 +324,10 @@ class MutableAclProvider extends AclProvider implements MutableAclProviderInterf } $this->connection->commit(); - } catch (\Exception $failed) { + } catch (\Exception $e) { $this->connection->rollBack(); - throw $failed; + throw $e; } $this->propertyChanges->offsetSet($acl, array()); diff --git a/Acl/Domain/ObjectIdentity.php b/Acl/Domain/ObjectIdentity.php index fc5b9c6..871bda7 100644 --- a/Acl/Domain/ObjectIdentity.php +++ b/Acl/Domain/ObjectIdentity.php @@ -68,8 +68,8 @@ final class ObjectIdentity implements ObjectIdentityInterface } elseif (method_exists($domainObject, 'getId')) { return new self((string) $domainObject->getId(), ClassUtils::getRealClass($domainObject)); } - } catch (\InvalidArgumentException $invalid) { - throw new InvalidDomainObjectException($invalid->getMessage(), 0, $invalid); + } catch (\InvalidArgumentException $e) { + throw new InvalidDomainObjectException($e->getMessage(), 0, $e); } throw new InvalidDomainObjectException('$domainObject must either implement the DomainObjectInterface, or have a method named "getId".'); diff --git a/Acl/Domain/ObjectIdentityRetrievalStrategy.php b/Acl/Domain/ObjectIdentityRetrievalStrategy.php index 21ac812..80de6e0 100644 --- a/Acl/Domain/ObjectIdentityRetrievalStrategy.php +++ b/Acl/Domain/ObjectIdentityRetrievalStrategy.php @@ -28,7 +28,7 @@ class ObjectIdentityRetrievalStrategy implements ObjectIdentityRetrievalStrategy { try { return ObjectIdentity::fromDomainObject($domainObject); - } catch (InvalidDomainObjectException $failed) { + } catch (InvalidDomainObjectException $e) { return; } } diff --git a/Acl/Domain/PermissionGrantingStrategy.php b/Acl/Domain/PermissionGrantingStrategy.php index ef80a20..742c4e5 100644 --- a/Acl/Domain/PermissionGrantingStrategy.php +++ b/Acl/Domain/PermissionGrantingStrategy.php @@ -55,21 +55,21 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface } return $this->hasSufficientPermissions($acl, $aces, $masks, $sids, $administrativeMode); - } catch (NoAceFoundException $noObjectAce) { + } catch (NoAceFoundException $e) { $aces = $acl->getClassAces(); if (!$aces) { - throw $noObjectAce; + throw $e; } return $this->hasSufficientPermissions($acl, $aces, $masks, $sids, $administrativeMode); } - } catch (NoAceFoundException $noClassAce) { + } catch (NoAceFoundException $e) { if ($acl->isEntriesInheriting() && null !== $parentAcl = $acl->getParentAcl()) { return $parentAcl->isGranted($masks, $sids, $administrativeMode); } - throw $noClassAce; + throw $e; } } @@ -86,20 +86,20 @@ class PermissionGrantingStrategy implements PermissionGrantingStrategyInterface } return $this->hasSufficientPermissions($acl, $aces, $masks, $sids, $administrativeMode); - } catch (NoAceFoundException $noObjectAces) { + } catch (NoAceFoundException $e) { $aces = $acl->getClassFieldAces($field); if (!$aces) { - throw $noObjectAces; + throw $e; } return $this->hasSufficientPermissions($acl, $aces, $masks, $sids, $administrativeMode); } - } catch (NoAceFoundException $noClassAces) { + } catch (NoAceFoundException $e) { if ($acl->isEntriesInheriting() && null !== $parentAcl = $acl->getParentAcl()) { return $parentAcl->isFieldGranted($field, $masks, $sids, $administrativeMode); } - throw $noClassAces; + throw $e; } } diff --git a/Acl/Domain/SecurityIdentityRetrievalStrategy.php b/Acl/Domain/SecurityIdentityRetrievalStrategy.php index 708c633..a08f67e 100644 --- a/Acl/Domain/SecurityIdentityRetrievalStrategy.php +++ b/Acl/Domain/SecurityIdentityRetrievalStrategy.php @@ -51,7 +51,7 @@ class SecurityIdentityRetrievalStrategy implements SecurityIdentityRetrievalStra if (!$token instanceof AnonymousToken) { try { $sids[] = UserSecurityIdentity::fromToken($token); - } catch (\InvalidArgumentException $invalid) { + } catch (\InvalidArgumentException $e) { // ignore, user has no user security identity } } diff --git a/Acl/Domain/UserSecurityIdentity.php b/Acl/Domain/UserSecurityIdentity.php index 3bf277f..ea17c63 100644 --- a/Acl/Domain/UserSecurityIdentity.php +++ b/Acl/Domain/UserSecurityIdentity.php @@ -36,7 +36,7 @@ final class UserSecurityIdentity implements SecurityIdentityInterface */ public function __construct($username, $class) { - if (empty($username)) { + if ('' === $username || null === $username) { throw new \InvalidArgumentException('$username must not be empty.'); } if (empty($class)) { diff --git a/Acl/Permission/MaskBuilder.php b/Acl/Permission/MaskBuilder.php index 45d89aa..ca25c70 100644 --- a/Acl/Permission/MaskBuilder.php +++ b/Acl/Permission/MaskBuilder.php @@ -132,7 +132,7 @@ class MaskBuilder if ('1' === $bitmask[$i]) { try { $pattern[$i] = self::getCode(1 << ($length - $i - 1)); - } catch (\Exception $notPredefined) { + } catch (\Exception $e) { $pattern[$i] = self::ON; } } diff --git a/Acl/Voter/AclVoter.php b/Acl/Voter/AclVoter.php index 9657eed..4a8533a 100644 --- a/Acl/Voter/AclVoter.php +++ b/Acl/Voter/AclVoter.php @@ -113,13 +113,13 @@ class AclVoter implements VoterInterface } return self::ACCESS_DENIED; - } catch (AclNotFoundException $noAcl) { + } catch (AclNotFoundException $e) { if (null !== $this->logger) { $this->logger->debug('No ACL found for the object identity. Voting to deny access.'); } return self::ACCESS_DENIED; - } catch (NoAceFoundException $noAce) { + } catch (NoAceFoundException $e) { if (null !== $this->logger) { $this->logger->debug('ACL found, no ACE applicable. Voting to deny access.'); } diff --git a/Core/Authentication/Provider/DaoAuthenticationProvider.php b/Core/Authentication/Provider/DaoAuthenticationProvider.php index b7b4917..90cba25 100644 --- a/Core/Authentication/Provider/DaoAuthenticationProvider.php +++ b/Core/Authentication/Provider/DaoAuthenticationProvider.php @@ -87,13 +87,13 @@ class DaoAuthenticationProvider extends UserAuthenticationProvider } return $user; - } catch (UsernameNotFoundException $notFound) { - $notFound->setUsername($username); - throw $notFound; - } catch (\Exception $repositoryProblem) { - $ex = new AuthenticationServiceException($repositoryProblem->getMessage(), 0, $repositoryProblem); - $ex->setToken($token); - throw $ex; + } catch (UsernameNotFoundException $e) { + $e->setUsername($username); + throw $e; + } catch (\Exception $e) { + $e = new AuthenticationServiceException($e->getMessage(), 0, $e); + $e->setToken($token); + throw $e; } } } diff --git a/Core/Authentication/Provider/UserAuthenticationProvider.php b/Core/Authentication/Provider/UserAuthenticationProvider.php index b948135..a624ccf 100644 --- a/Core/Authentication/Provider/UserAuthenticationProvider.php +++ b/Core/Authentication/Provider/UserAuthenticationProvider.php @@ -62,19 +62,19 @@ abstract class UserAuthenticationProvider implements AuthenticationProviderInter } $username = $token->getUsername(); - if (empty($username)) { + if ('' === $username || null === $username) { $username = 'NONE_PROVIDED'; } try { $user = $this->retrieveUser($username, $token); - } catch (UsernameNotFoundException $notFound) { + } catch (UsernameNotFoundException $e) { if ($this->hideUserNotFoundExceptions) { - throw new BadCredentialsException('Bad credentials', 0, $notFound); + throw new BadCredentialsException('Bad credentials', 0, $e); } - $notFound->setUsername($username); + $e->setUsername($username); - throw $notFound; + throw $e; } if (!$user instanceof UserInterface) { diff --git a/Core/Authentication/RememberMe/PersistentToken.php b/Core/Authentication/RememberMe/PersistentToken.php index 92fcb4f..d85572d 100644 --- a/Core/Authentication/RememberMe/PersistentToken.php +++ b/Core/Authentication/RememberMe/PersistentToken.php @@ -40,7 +40,7 @@ final class PersistentToken implements PersistentTokenInterface if (empty($class)) { throw new \InvalidArgumentException('$class must not be empty.'); } - if (empty($username)) { + if ('' === $username || null === $username) { throw new \InvalidArgumentException('$username must not be empty.'); } if (empty($series)) { diff --git a/Core/Authentication/Token/AbstractToken.php b/Core/Authentication/Token/AbstractToken.php index a2aefb1..b07312f 100644 --- a/Core/Authentication/Token/AbstractToken.php +++ b/Core/Authentication/Token/AbstractToken.php @@ -33,7 +33,7 @@ abstract class AbstractToken implements TokenInterface /** * Constructor. * - * @param RoleInterface[] $roles An array of roles + * @param RoleInterface[]|string[] $roles An array of roles * * @throws \InvalidArgumentException */ diff --git a/Core/Authentication/Token/PreAuthenticatedToken.php b/Core/Authentication/Token/PreAuthenticatedToken.php index abcd2bf..1798203 100644 --- a/Core/Authentication/Token/PreAuthenticatedToken.php +++ b/Core/Authentication/Token/PreAuthenticatedToken.php @@ -11,6 +11,8 @@ namespace Symfony\Component\Security\Core\Authentication\Token; +use Symfony\Component\Security\Core\Role\RoleInterface; + /** * PreAuthenticatedToken implements a pre-authenticated token. * @@ -23,6 +25,11 @@ class PreAuthenticatedToken extends AbstractToken /** * Constructor. + * + * @param string|object $user The user + * @param mixed $credentials The user credentials + * @param string $providerKey The provider key + * @param RoleInterface[]|string[] $roles An array of roles */ public function __construct($user, $credentials, $providerKey, array $roles = array()) { diff --git a/Core/User/ChainUserProvider.php b/Core/User/ChainUserProvider.php index 6e14a4f..8604ddc 100644 --- a/Core/User/ChainUserProvider.php +++ b/Core/User/ChainUserProvider.php @@ -47,7 +47,7 @@ class ChainUserProvider implements UserProviderInterface foreach ($this->providers as $provider) { try { return $provider->loadUserByUsername($username); - } catch (UsernameNotFoundException $notFound) { + } catch (UsernameNotFoundException $e) { // try next one } } @@ -67,18 +67,18 @@ class ChainUserProvider implements UserProviderInterface foreach ($this->providers as $provider) { try { return $provider->refreshUser($user); - } catch (UnsupportedUserException $unsupported) { + } catch (UnsupportedUserException $e) { // try next one - } catch (UsernameNotFoundException $notFound) { + } catch (UsernameNotFoundException $e) { $supportedUserFound = true; // try next one } } if ($supportedUserFound) { - $ex = new UsernameNotFoundException(sprintf('There is no user with name "%s".', $user->getUsername())); - $ex->setUsername($user->getUsername()); - throw $ex; + $e = new UsernameNotFoundException(sprintf('There is no user with name "%s".', $user->getUsername())); + $e->setUsername($user->getUsername()); + throw $e; } else { throw new UnsupportedUserException(sprintf('The account "%s" is not supported.', get_class($user))); } diff --git a/Core/User/InMemoryUserProvider.php b/Core/User/InMemoryUserProvider.php index 624eb3d..9aa39ca 100644 --- a/Core/User/InMemoryUserProvider.php +++ b/Core/User/InMemoryUserProvider.php @@ -67,17 +67,9 @@ class InMemoryUserProvider implements UserProviderInterface */ public function loadUserByUsername($username) { - if (!isset($this->users[strtolower($username)])) { - $ex = new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username)); - $ex->setUsername($username); - - throw $ex; - } + $user = $this->getUser($username); - $user = $this->users[strtolower($username)]; - - return new User($user->getUsername(), $user->getPassword(), $user->getRoles(), $user->isEnabled(), $user->isAccountNonExpired(), - $user->isCredentialsNonExpired(), $user->isAccountNonLocked()); + return new User($user->getUsername(), $user->getPassword(), $user->getRoles(), $user->isEnabled(), $user->isAccountNonExpired(), $user->isCredentialsNonExpired(), $user->isAccountNonLocked()); } /** @@ -89,7 +81,9 @@ class InMemoryUserProvider implements UserProviderInterface throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user))); } - return $this->loadUserByUsername($user->getUsername()); + $storedUser = $this->getUser($user->getUsername()); + + return new User($storedUser->getUsername(), $storedUser->getPassword(), $storedUser->getRoles(), $storedUser->isEnabled(), $storedUser->isAccountNonExpired(), $storedUser->isCredentialsNonExpired() && $storedUser->getPassword() === $user->getPassword(), $storedUser->isAccountNonLocked()); } /** @@ -99,4 +93,25 @@ class InMemoryUserProvider implements UserProviderInterface { return $class === 'Symfony\Component\Security\Core\User\User'; } + + /** + * Returns the user by given username. + * + * @param string $username The username. + * + * @return User + * + * @throws UsernameNotFoundException If user whose given username does not exist. + */ + private function getUser($username) + { + if (!isset($this->users[strtolower($username)])) { + $ex = new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username)); + $ex->setUsername($username); + + throw $ex; + } + + return $this->users[strtolower($username)]; + } } diff --git a/Core/User/User.php b/Core/User/User.php index ea2c6a4..86f1acd 100644 --- a/Core/User/User.php +++ b/Core/User/User.php @@ -30,7 +30,7 @@ final class User implements AdvancedUserInterface public function __construct($username, $password, array $roles = array(), $enabled = true, $userNonExpired = true, $credentialsNonExpired = true, $userNonLocked = true) { - if (empty($username)) { + if ('' === $username || null === $username) { throw new \InvalidArgumentException('The username cannot be empty.'); } diff --git a/Core/Util/SecureRandom.php b/Core/Util/SecureRandom.php index c0924df..3461b4e 100644 --- a/Core/Util/SecureRandom.php +++ b/Core/Util/SecureRandom.php @@ -42,12 +42,12 @@ final class SecureRandom implements SecureRandomInterface $this->seedFile = $seedFile; $this->logger = $logger; + $isUnsupportedPhp = '\\' === DIRECTORY_SEPARATOR && PHP_VERSION_ID < 50304; + // determine whether to use OpenSSL - if ('\\' === DIRECTORY_SEPARATOR && PHP_VERSION_ID < 50304) { - $this->useOpenSsl = false; - } elseif (!function_exists('openssl_random_pseudo_bytes')) { + if (!function_exists('random_bytes') && ($isUnsupportedPhp || !function_exists('openssl_random_pseudo_bytes'))) { if (null !== $this->logger) { - $this->logger->notice('It is recommended that you enable the "openssl" extension for random number generation.'); + $this->logger->notice('It is recommended that you install the "paragonie/random_compat" library or enable the "openssl" extension for random number generation.'); } $this->useOpenSsl = false; } else { @@ -60,6 +60,10 @@ final class SecureRandom implements SecureRandomInterface */ public function nextBytes($nbBytes) { + if (function_exists('random_bytes')) { + return random_bytes($nbBytes); + } + // try OpenSSL if ($this->useOpenSsl) { $bytes = openssl_random_pseudo_bytes($nbBytes, $strong); diff --git a/Http/Firewall/AbstractPreAuthenticatedListener.php b/Http/Firewall/AbstractPreAuthenticatedListener.php index f040107..9973683 100644 --- a/Http/Firewall/AbstractPreAuthenticatedListener.php +++ b/Http/Firewall/AbstractPreAuthenticatedListener.php @@ -62,8 +62,8 @@ abstract class AbstractPreAuthenticatedListener implements ListenerInterface try { list($user, $credentials) = $this->getPreAuthenticatedData($request); - } catch (BadCredentialsException $exception) { - $this->clearToken($exception); + } catch (BadCredentialsException $e) { + $this->clearToken($e); return; } @@ -90,8 +90,8 @@ abstract class AbstractPreAuthenticatedListener implements ListenerInterface $loginEvent = new InteractiveLoginEvent($request, $token); $this->dispatcher->dispatch(SecurityEvents::INTERACTIVE_LOGIN, $loginEvent); } - } catch (AuthenticationException $failed) { - $this->clearToken($failed); + } catch (AuthenticationException $e) { + $this->clearToken($e); } } diff --git a/Http/Firewall/BasicAuthenticationListener.php b/Http/Firewall/BasicAuthenticationListener.php index bfc4abc..eed9838 100644 --- a/Http/Firewall/BasicAuthenticationListener.php +++ b/Http/Firewall/BasicAuthenticationListener.php @@ -73,21 +73,21 @@ class BasicAuthenticationListener implements ListenerInterface try { $token = $this->authenticationManager->authenticate(new UsernamePasswordToken($username, $request->headers->get('PHP_AUTH_PW'), $this->providerKey)); $this->securityContext->setToken($token); - } catch (AuthenticationException $failed) { + } catch (AuthenticationException $e) { $token = $this->securityContext->getToken(); if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey()) { $this->securityContext->setToken(null); } if (null !== $this->logger) { - $this->logger->info(sprintf('Authentication request failed for user "%s": %s', $username, $failed->getMessage())); + $this->logger->info(sprintf('Authentication request failed for user "%s": %s', $username, $e->getMessage())); } if ($this->ignoreFailure) { return; } - $event->setResponse($this->authenticationEntryPoint->start($request, $failed)); + $event->setResponse($this->authenticationEntryPoint->start($request, $e)); } } } diff --git a/Http/Firewall/ContextListener.php b/Http/Firewall/ContextListener.php index c80fff3..43ad31d 100644 --- a/Http/Firewall/ContextListener.php +++ b/Http/Firewall/ContextListener.php @@ -167,11 +167,11 @@ class ContextListener implements ListenerInterface } return $token; - } catch (UnsupportedUserException $unsupported) { + } catch (UnsupportedUserException $e) { // let's try the next user provider - } catch (UsernameNotFoundException $notFound) { + } catch (UsernameNotFoundException $e) { if (null !== $this->logger) { - $this->logger->warning(sprintf('Username "%s" could not be found.', $notFound->getUsername())); + $this->logger->warning(sprintf('Username "%s" could not be found.', $e->getUsername())); } return; diff --git a/Http/Firewall/DigestAuthenticationListener.php b/Http/Firewall/DigestAuthenticationListener.php index 358c3c7..a88250b 100644 --- a/Http/Firewall/DigestAuthenticationListener.php +++ b/Http/Firewall/DigestAuthenticationListener.php @@ -93,7 +93,7 @@ class DigestAuthenticationListener implements ListenerInterface } $serverDigestMd5 = $digestAuth->calculateServerDigest($user->getPassword(), $request->getMethod()); - } catch (UsernameNotFoundException $notFound) { + } catch (UsernameNotFoundException $e) { $this->fail($event, $request, new BadCredentialsException(sprintf('Username %s not found.', $digestAuth->getUsername()))); return; @@ -101,7 +101,7 @@ class DigestAuthenticationListener implements ListenerInterface if ($serverDigestMd5 !== $digestAuth->getResponse()) { if (null !== $this->logger) { - $this->logger->debug(sprintf("Expected response: '%s' but received: '%s'; is AuthenticationDao returning clear text passwords?", $serverDigestMd5, $digestAuth->getResponse())); + $this->logger->debug(sprintf('Expected response: "%s" but received: "%s"; is AuthenticationDao returning clear text passwords?', $serverDigestMd5, $digestAuth->getResponse())); } $this->fail($event, $request, new BadCredentialsException('Incorrect response')); diff --git a/Http/Firewall/ExceptionListener.php b/Http/Firewall/ExceptionListener.php index 57321fb..8553c75 100644 --- a/Http/Firewall/ExceptionListener.php +++ b/Http/Firewall/ExceptionListener.php @@ -46,8 +46,9 @@ class ExceptionListener private $errorPage; private $logger; private $httpUtils; + private $stateless; - public function __construct(SecurityContextInterface $context, AuthenticationTrustResolverInterface $trustResolver, HttpUtils $httpUtils, $providerKey, AuthenticationEntryPointInterface $authenticationEntryPoint = null, $errorPage = null, AccessDeniedHandlerInterface $accessDeniedHandler = null, LoggerInterface $logger = null) + public function __construct(SecurityContextInterface $context, AuthenticationTrustResolverInterface $trustResolver, HttpUtils $httpUtils, $providerKey, AuthenticationEntryPointInterface $authenticationEntryPoint = null, $errorPage = null, AccessDeniedHandlerInterface $accessDeniedHandler = null, LoggerInterface $logger = null, $stateless = false) { $this->context = $context; $this->accessDeniedHandler = $accessDeniedHandler; @@ -57,6 +58,7 @@ class ExceptionListener $this->authenticationTrustResolver = $trustResolver; $this->errorPage = $errorPage; $this->logger = $logger; + $this->stateless = $stateless; } /** @@ -178,7 +180,9 @@ class ExceptionListener $this->logger->debug('Calling Authentication entry point'); } - $this->setTargetPath($request); + if (!$this->stateless) { + $this->setTargetPath($request); + } if ($authException instanceof AccountStatusException) { // remove the security token to prevent infinite redirect loops diff --git a/Http/Firewall/RememberMeListener.php b/Http/Firewall/RememberMeListener.php index beacff3..942e537 100644 --- a/Http/Firewall/RememberMeListener.php +++ b/Http/Firewall/RememberMeListener.php @@ -80,12 +80,12 @@ class RememberMeListener implements ListenerInterface if (null !== $this->logger) { $this->logger->debug('SecurityContext populated with remember-me token.'); } - } catch (AuthenticationException $failed) { + } catch (AuthenticationException $e) { if (null !== $this->logger) { $this->logger->warning( 'SecurityContext not populated with remember-me token as the' .' AuthenticationManager rejected the AuthenticationToken returned' - .' by the RememberMeServices: '.$failed->getMessage() + .' by the RememberMeServices: '.$e->getMessage() ); } diff --git a/Http/Firewall/SwitchUserListener.php b/Http/Firewall/SwitchUserListener.php index 7700096..79b715a 100644 --- a/Http/Firewall/SwitchUserListener.php +++ b/Http/Firewall/SwitchUserListener.php @@ -116,9 +116,9 @@ class SwitchUserListener implements ListenerInterface if (false !== $originalToken) { if ($token->getUsername() === $request->get($this->usernameParameter)) { return $token; - } else { - throw new \LogicException(sprintf('You are already switched to "%s" user.', $token->getUsername())); } + + throw new \LogicException(sprintf('You are already switched to "%s" user.', $token->getUsername())); } if (false === $this->accessDecisionManager->decide($token, array($this->role))) { @@ -163,7 +163,8 @@ class SwitchUserListener implements ListenerInterface } if (null !== $this->dispatcher) { - $switchEvent = new SwitchUserEvent($request, $original->getUser()); + $user = $this->provider->refreshUser($original->getUser()); + $switchEvent = new SwitchUserEvent($request, $user); $this->dispatcher->dispatch(SecurityEvents::SWITCH_USER, $switchEvent); } diff --git a/Http/RememberMe/AbstractRememberMeServices.php b/Http/RememberMe/AbstractRememberMeServices.php index ac5e10e..51eddb6 100644 --- a/Http/RememberMe/AbstractRememberMeServices.php +++ b/Http/RememberMe/AbstractRememberMeServices.php @@ -123,21 +123,21 @@ abstract class AbstractRememberMeServices implements RememberMeServicesInterface } return new RememberMeToken($user, $this->providerKey, $this->key); - } catch (CookieTheftException $theft) { + } catch (CookieTheftException $e) { $this->cancelCookie($request); - throw $theft; - } catch (UsernameNotFoundException $notFound) { + throw $e; + } catch (UsernameNotFoundException $e) { if (null !== $this->logger) { $this->logger->info('User for remember-me cookie not found.'); } - } catch (UnsupportedUserException $unSupported) { + } catch (UnsupportedUserException $e) { if (null !== $this->logger) { $this->logger->warning('User class for remember-me cookie not supported.'); } - } catch (AuthenticationException $invalid) { + } catch (AuthenticationException $e) { if (null !== $this->logger) { - $this->logger->debug('Remember-Me authentication failed: '.$invalid->getMessage()); + $this->logger->debug('Remember-Me authentication failed: '.$e->getMessage()); } } diff --git a/Http/RememberMe/TokenBasedRememberMeServices.php b/Http/RememberMe/TokenBasedRememberMeServices.php index 89bcb6f..de662fb 100644 --- a/Http/RememberMe/TokenBasedRememberMeServices.php +++ b/Http/RememberMe/TokenBasedRememberMeServices.php @@ -41,12 +41,12 @@ class TokenBasedRememberMeServices extends AbstractRememberMeServices } try { $user = $this->getUserProvider($class)->loadUserByUsername($username); - } catch (\Exception $ex) { - if (!$ex instanceof AuthenticationException) { - $ex = new AuthenticationException($ex->getMessage(), $ex->getCode(), $ex); + } catch (\Exception $e) { + if (!$e instanceof AuthenticationException) { + $e = new AuthenticationException($e->getMessage(), $e->getCode(), $e); } - throw $ex; + throw $e; } if (!$user instanceof UserInterface) { diff --git a/Resources/translations/security.tr.xlf b/Resources/translations/security.tr.xlf index fbf9b26..68c4421 100644 --- a/Resources/translations/security.tr.xlf +++ b/Resources/translations/security.tr.xlf @@ -8,7 +8,7 @@ </trans-unit> <trans-unit id="2"> <source>Authentication credentials could not be found.</source> - <target>Yetkilendirme girdileri bulunamadı.</target> + <target>Kimlik bilgileri bulunamadı.</target> </trans-unit> <trans-unit id="3"> <source>Authentication request could not be processed due to a system problem.</source> @@ -16,7 +16,7 @@ </trans-unit> <trans-unit id="4"> <source>Invalid credentials.</source> - <target>Geçersiz girdiler.</target> + <target>Geçersiz kimlik bilgileri.</target> </trans-unit> <trans-unit id="5"> <source>Cookie has already been used by someone else.</source> @@ -32,7 +32,7 @@ </trans-unit> <trans-unit id="8"> <source>Digest nonce has expired.</source> - <target>Derleme zaman aşımı gerçekleşti.</target> + <target>Derleme zaman aşımına uğradı.</target> </trans-unit> <trans-unit id="9"> <source>No authentication provider found to support the authentication token.</source> @@ -44,7 +44,7 @@ </trans-unit> <trans-unit id="11"> <source>No token could be found.</source> - <target>Bilet bulunamadı.</target> + <target>Fiş bulunamadı.</target> </trans-unit> <trans-unit id="12"> <source>Username could not be found.</source> @@ -56,11 +56,11 @@ </trans-unit> <trans-unit id="14"> <source>Credentials have expired.</source> - <target>Girdiler zaman aşımına uğradı.</target> + <target>Kimlik bilgileri zaman aşımına uğradı.</target> </trans-unit> <trans-unit id="15"> <source>Account is disabled.</source> - <target>Hesap devre dışı bırakılmış.</target> + <target>Hesap engellenmiş.</target> </trans-unit> <trans-unit id="16"> <source>Account is locked.</source> diff --git a/Tests/Acl/Dbal/AclProviderTest.php b/Tests/Acl/Dbal/AclProviderTest.php index ecd53db..7ca493f 100644 --- a/Tests/Acl/Dbal/AclProviderTest.php +++ b/Tests/Acl/Dbal/AclProviderTest.php @@ -45,11 +45,11 @@ class AclProviderTest extends \PHPUnit_Framework_TestCase $this->getProvider()->findAcls($oids); $this->fail('Provider did not throw an expected exception.'); - } catch (\Exception $ex) { - $this->assertInstanceOf('Symfony\Component\Security\Acl\Exception\AclNotFoundException', $ex); - $this->assertInstanceOf('Symfony\Component\Security\Acl\Exception\NotAllAclsFoundException', $ex); + } catch (\Exception $e) { + $this->assertInstanceOf('Symfony\Component\Security\Acl\Exception\AclNotFoundException', $e); + $this->assertInstanceOf('Symfony\Component\Security\Acl\Exception\NotAllAclsFoundException', $e); - $partialResult = $ex->getPartialResult(); + $partialResult = $e->getPartialResult(); $this->assertTrue($partialResult->contains($oids[0])); $this->assertFalse($partialResult->contains($oids[1])); } diff --git a/Tests/Acl/Dbal/MutableAclProviderTest.php b/Tests/Acl/Dbal/MutableAclProviderTest.php index f6d66ef..00500f8 100644 --- a/Tests/Acl/Dbal/MutableAclProviderTest.php +++ b/Tests/Acl/Dbal/MutableAclProviderTest.php @@ -88,7 +88,7 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase try { $provider->findAcl($oid); $this->fail('ACL has not been properly deleted.'); - } catch (AclNotFoundException $notFound) { + } catch (AclNotFoundException $e) { } } @@ -104,7 +104,7 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase try { $provider->findAcl(new ObjectIdentity(1, 'Foo')); $this->fail('Child-ACLs have not been deleted.'); - } catch (AclNotFoundException $notFound) { + } catch (AclNotFoundException $e) { } } @@ -290,7 +290,7 @@ class MutableAclProviderTest extends \PHPUnit_Framework_TestCase try { $provider->updateAcl($acl1); $this->fail('Provider failed to detect a concurrent modification.'); - } catch (ConcurrentModificationException $ex) { + } catch (ConcurrentModificationException $e) { } } diff --git a/Tests/Acl/Domain/PermissionGrantingStrategyTest.php b/Tests/Acl/Domain/PermissionGrantingStrategyTest.php index 4935bff..fd33f8d 100644 --- a/Tests/Acl/Domain/PermissionGrantingStrategyTest.php +++ b/Tests/Acl/Domain/PermissionGrantingStrategyTest.php @@ -154,7 +154,7 @@ class PermissionGrantingStrategyTest extends \PHPUnit_Framework_TestCase try { $strategy->isGranted($acl, array($requiredMask), array($sid)); $this->fail('The ACE is not supposed to match.'); - } catch (NoAceFoundException $noAce) { + } catch (NoAceFoundException $e) { } } else { $this->assertTrue($strategy->isGranted($acl, array($requiredMask), array($sid))); diff --git a/Tests/Core/User/InMemoryUserProviderTest.php b/Tests/Core/User/InMemoryUserProviderTest.php index 826e390..266d397 100644 --- a/Tests/Core/User/InMemoryUserProviderTest.php +++ b/Tests/Core/User/InMemoryUserProviderTest.php @@ -18,18 +18,39 @@ class InMemoryUserProviderTest extends \PHPUnit_Framework_TestCase { public function testConstructor() { - $provider = new InMemoryUserProvider(array( + $provider = $this->createProvider(); + + $user = $provider->loadUserByUsername('fabien'); + $this->assertEquals('foo', $user->getPassword()); + $this->assertEquals(array('ROLE_USER'), $user->getRoles()); + $this->assertFalse($user->isEnabled()); + } + + public function testRefresh() + { + $user = new User('fabien', 'bar'); + + $provider = $this->createProvider(); + + $refreshedUser = $provider->refreshUser($user); + $this->assertEquals('foo', $refreshedUser->getPassword()); + $this->assertEquals(array('ROLE_USER'), $refreshedUser->getRoles()); + $this->assertFalse($refreshedUser->isEnabled()); + $this->assertFalse($refreshedUser->isCredentialsNonExpired()); + } + + /** + * @return InMemoryUserProvider + */ + protected function createProvider() + { + return new InMemoryUserProvider(array( 'fabien' => array( 'password' => 'foo', 'enabled' => false, 'roles' => array('ROLE_USER'), ), )); - - $user = $provider->loadUserByUsername('fabien'); - $this->assertEquals('foo', $user->getPassword()); - $this->assertEquals(array('ROLE_USER'), $user->getRoles()); - $this->assertFalse($user->isEnabled()); } public function testCreateUser() diff --git a/Tests/Http/Firewall/SwitchUserListenerTest.php b/Tests/Http/Firewall/SwitchUserListenerTest.php index e86ee83..7ba71d4 100644 --- a/Tests/Http/Firewall/SwitchUserListenerTest.php +++ b/Tests/Http/Firewall/SwitchUserListenerTest.php @@ -11,7 +11,9 @@ namespace Symfony\Component\Security\Tests\Http\Firewall; +use Symfony\Component\Security\Http\Event\SwitchUserEvent; use Symfony\Component\Security\Http\Firewall\SwitchUserListener; +use Symfony\Component\Security\Http\SecurityEvents; class SwitchUserListenerTest extends \PHPUnit_Framework_TestCase { @@ -97,6 +99,56 @@ class SwitchUserListenerTest extends \PHPUnit_Framework_TestCase $listener->handle($this->event); } + public function testExitUserDispatchesEventWithRefreshedUser() + { + $originalUser = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); + $refreshedUser = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); + $this + ->userProvider + ->expects($this->any()) + ->method('refreshUser') + ->with($originalUser) + ->willReturn($refreshedUser); + $originalToken = $this->getToken(); + $originalToken + ->expects($this->any()) + ->method('getUser') + ->willReturn($originalUser); + $role = $this + ->getMockBuilder('Symfony\Component\Security\Core\Role\SwitchUserRole') + ->disableOriginalConstructor() + ->getMock(); + $role->expects($this->any())->method('getSource')->willReturn($originalToken); + $this + ->securityContext + ->expects($this->any()) + ->method('getToken') + ->willReturn($this->getToken(array($role))); + $this + ->request + ->expects($this->any()) + ->method('get') + ->with('_switch_user') + ->willReturn('_exit'); + $this + ->request + ->expects($this->any()) + ->method('getUri') + ->willReturn('/'); + + $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface'); + $dispatcher + ->expects($this->once()) + ->method('dispatch') + ->with(SecurityEvents::SWITCH_USER, $this->callback(function (SwitchUserEvent $event) use ($refreshedUser) { + return $event->getTargetUser() === $refreshedUser; + })) + ; + + $listener = new SwitchUserListener($this->securityContext, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager, null, '_switch_user', 'ROLE_ALLOWED_TO_SWITCH', $dispatcher); + $listener->handle($this->event); + } + /** * @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException */ diff --git a/Tests/Http/RememberMe/PersistentTokenBasedRememberMeServicesTest.php b/Tests/Http/RememberMe/PersistentTokenBasedRememberMeServicesTest.php index 89da09f..fe64abc 100644 --- a/Tests/Http/RememberMe/PersistentTokenBasedRememberMeServicesTest.php +++ b/Tests/Http/RememberMe/PersistentTokenBasedRememberMeServicesTest.php @@ -115,7 +115,7 @@ class PersistentTokenBasedRememberMeServicesTest extends \PHPUnit_Framework_Test try { $service->autoLogin($request); $this->fail('Expected CookieTheftException was not thrown.'); - } catch (CookieTheftException $theft) { + } catch (CookieTheftException $e) { } $this->assertTrue($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME)); diff --git a/composer.json b/composer.json index d18b644..2026fc4 100644 --- a/composer.json +++ b/composer.json @@ -39,7 +39,8 @@ "symfony/validator": "", "symfony/routing": "", "doctrine/dbal": "to use the built-in ACL implementation", - "ircmaxell/password-compat": "" + "ircmaxell/password-compat": "", + "paragonie/random_compat": "" }, "autoload": { "psr-0": { "Symfony\\Component\\Security\\": "" } |