diff --git a/.gitignore b/.gitignore
index c3f54875..e1123f0c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,7 +1,10 @@
+phpstan.neon
phpunit.xml
Tests/autoload.php
+var/
vendor/
Propel/om/
Propel/map/
composer.lock
.php_cs.cache
+.phpunit.result.cache
diff --git a/.travis.yml b/.travis.yml
index bad59d75..88efa7de 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -2,7 +2,6 @@ language: php
sudo: true
php:
- - 7.1
- 7.2
service:
@@ -12,12 +11,18 @@ service:
matrix:
fast_finish: true
include:
- - php: 7.1
- env: SYMFONY_VERSION=3.4.*
- php: 7.2
- env: SYMFONY_VERSION=4.0.*
+ env: SYMFONY_VERSION=4.4.*
- php: 7.2
- env: SYMFONY_VERSION=4.0.* DEPENDENCIES=beta
+ env: SYMFONY_VERSION=5.0.*
+ - php: 7.3
+ env: SYMFONY_VERSION=4.4.*
+ - php: 7.3
+ env: SYMFONY_VERSION=5.0.*
+ - php: 7.4
+ env: SYMFONY_VERSION=4.4.*
+ - php: 7.4
+ env: SYMFONY_VERSION=5.0.*
cache:
directories:
diff --git a/Command/CleanCommand.php b/Command/CleanCommand.php
index e24590f4..bad03350 100644
--- a/Command/CleanCommand.php
+++ b/Command/CleanCommand.php
@@ -21,15 +21,20 @@
class CleanCommand extends Command
{
+ /** @var TokenManagerInterface */
private $accessTokenManager;
+
+ /** @var TokenManagerInterface */
private $refreshTokenManager;
+
+ /** @var AuthCodeManagerInterface */
private $authCodeManager;
public function __construct(
TokenManagerInterface $accessTokenManager,
TokenManagerInterface $refreshTokenManager,
- AuthCodeManagerInterface $authCodeManager)
- {
+ AuthCodeManagerInterface $authCodeManager
+ ) {
parent::__construct();
$this->accessTokenManager = $accessTokenManager;
@@ -40,7 +45,7 @@ public function __construct(
/**
* {@inheritdoc}
*/
- protected function configure()
+ protected function configure(): void
{
parent::configure();
@@ -63,7 +68,15 @@ protected function execute(InputInterface $input, OutputInterface $output)
{
foreach ([$this->accessTokenManager, $this->refreshTokenManager, $this->authCodeManager] as $service) {
$result = $service->deleteExpired();
- $output->writeln(sprintf('Removed %d items from %s storage.', $result, get_class($service)));
+ $output->writeln(
+ sprintf(
+ 'Removed %d items from %s storage.',
+ $result,
+ get_class($service)
+ )
+ );
}
+
+ return 0;
}
}
diff --git a/Command/CreateClientCommand.php b/Command/CreateClientCommand.php
index 6b881b2b..3790ef0f 100644
--- a/Command/CreateClientCommand.php
+++ b/Command/CreateClientCommand.php
@@ -22,6 +22,7 @@
class CreateClientCommand extends Command
{
+ /** @var ClientManagerInterface */
private $clientManager;
public function __construct(ClientManagerInterface $clientManager)
@@ -34,7 +35,7 @@ public function __construct(ClientManagerInterface $clientManager)
/**
* {@inheritdoc}
*/
- protected function configure()
+ protected function configure(): void
{
parent::configure();
diff --git a/Controller/AuthorizeController.php b/Controller/AuthorizeController.php
index 46c75fca..f973597e 100644
--- a/Controller/AuthorizeController.php
+++ b/Controller/AuthorizeController.php
@@ -19,7 +19,7 @@
use FOS\OAuthServerBundle\Model\ClientManagerInterface;
use OAuth2\OAuth2;
use OAuth2\OAuth2ServerException;
-use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
+use RuntimeException;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
@@ -31,6 +31,7 @@
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\User\UserInterface;
+use Twig\Environment;
/**
* Controller handling basic authorization.
@@ -65,9 +66,9 @@ class AuthorizeController
private $oAuth2Server;
/**
- * @var EngineInterface
+ * @var Environment
*/
- private $templating;
+ private $twig;
/**
* @var RequestStack
@@ -89,11 +90,6 @@ class AuthorizeController
*/
private $clientManager;
- /**
- * @var string
- */
- private $templateEngineType;
-
/**
* @var EventDispatcherInterface
*/
@@ -105,47 +101,32 @@ class AuthorizeController
*
* @todo This controller could be refactored to not rely on so many dependencies
*
- * @param RequestStack $requestStack
- * @param Form $authorizeForm
- * @param AuthorizeFormHandler $authorizeFormHandler
- * @param OAuth2 $oAuth2Server
- * @param EngineInterface $templating
- * @param TokenStorageInterface $tokenStorage
- * @param UrlGeneratorInterface $router
- * @param ClientManagerInterface $clientManager
- * @param EventDispatcherInterface $eventDispatcher
- * @param SessionInterface $session
- * @param string $templateEngineType
+ * @param SessionInterface $session
*/
public function __construct(
RequestStack $requestStack,
Form $authorizeForm,
AuthorizeFormHandler $authorizeFormHandler,
OAuth2 $oAuth2Server,
- EngineInterface $templating,
+ Environment $twig,
TokenStorageInterface $tokenStorage,
UrlGeneratorInterface $router,
ClientManagerInterface $clientManager,
EventDispatcherInterface $eventDispatcher,
- SessionInterface $session = null,
- $templateEngineType = 'twig'
+ SessionInterface $session = null
) {
$this->requestStack = $requestStack;
$this->session = $session;
$this->authorizeForm = $authorizeForm;
$this->authorizeFormHandler = $authorizeFormHandler;
$this->oAuth2Server = $oAuth2Server;
- $this->templating = $templating;
+ $this->twig = $twig;
$this->tokenStorage = $tokenStorage;
$this->router = $router;
$this->clientManager = $clientManager;
- $this->templateEngineType = $templateEngineType;
$this->eventDispatcher = $eventDispatcher;
}
- /**
- * Authorize.
- */
public function authorizeAction(Request $request)
{
$user = $this->tokenStorage->getToken()->getUser();
@@ -164,8 +145,11 @@ public function authorizeAction(Request $request)
/** @var OAuthEvent $event */
$event = $this->eventDispatcher->dispatch(
- OAuthEvent::PRE_AUTHORIZATION_PROCESS,
- new OAuthEvent($user, $this->getClient())
+ new OAuthEvent(
+ $user,
+ $this->getClient()
+ ),
+ OAuthEvent::PRE_AUTHORIZATION_PROCESS
);
if ($event->isAuthorizedClient()) {
@@ -183,26 +167,25 @@ public function authorizeAction(Request $request)
'client' => $this->getClient(),
];
- return $this->renderAuthorize($data, $this->templating, $this->templateEngineType);
+ return new Response(
+ $this->twig->render('@FOSOAuthServer/Authorize/authorize.html.twig', $data),
+ Response::HTTP_OK
+ );
}
- /**
- * @param UserInterface $user
- * @param AuthorizeFormHandler $formHandler
- * @param Request $request
- *
- * @return Response
- */
- protected function processSuccess(UserInterface $user, AuthorizeFormHandler $formHandler, Request $request)
- {
+ protected function processSuccess(
+ UserInterface $user,
+ AuthorizeFormHandler $formHandler,
+ Request $request
+ ): ?Response {
if ($this->session && true === $this->session->get('_fos_oauth_server.ensure_logout')) {
$this->tokenStorage->setToken(null);
$this->session->invalidate();
}
$this->eventDispatcher->dispatch(
- OAuthEvent::POST_AUTHORIZATION_PROCESS,
- new OAuthEvent($user, $this->getClient(), $formHandler->isAccepted())
+ new OAuthEvent($user, $this->getClient(), $formHandler->isAccepted()),
+ OAuthEvent::POST_AUTHORIZATION_PROCESS
);
$formName = $this->authorizeForm->getName();
@@ -221,20 +204,13 @@ protected function processSuccess(UserInterface $user, AuthorizeFormHandler $for
/**
* Generate the redirection url when the authorize is completed.
- *
- * @param UserInterface $user
- *
- * @return string
*/
- protected function getRedirectionUrl(UserInterface $user)
+ protected function getRedirectionUrl(UserInterface $user): string
{
return $this->router->generate('fos_oauth_server_profile_show');
}
- /**
- * @return ClientInterface
- */
- protected function getClient()
+ protected function getClient(): ClientInterface
{
if (null !== $this->client) {
return $this->client;
@@ -246,7 +222,7 @@ protected function getClient()
if (null === $clientId = $request->get('client_id')) {
$formData = $request->get($this->authorizeForm->getName(), []);
- $clientId = isset($formData['client_id']) ? $formData['client_id'] : null;
+ $clientId = $formData['client_id'] ?? null;
}
$this->client = $this->clientManager->findClientByPublicId($clientId);
@@ -258,25 +234,11 @@ protected function getClient()
return $this->client;
}
- /**
- * @throws \RuntimeException
- */
- protected function renderAuthorize(array $data, EngineInterface $engine, string $engineType): Response
- {
- return $engine->renderResponse(
- '@FOSOAuthServer/Authorize/authorize.html.'.$engineType,
- $data
- );
- }
-
- /**
- * @return null|Request
- */
- private function getCurrentRequest()
+ private function getCurrentRequest(): ?Request
{
$request = $this->requestStack->getCurrentRequest();
if (null === $request) {
- throw new \RuntimeException('No current request.');
+ throw new RuntimeException('No current request.');
}
return $request;
diff --git a/Controller/TokenController.php b/Controller/TokenController.php
index 09b0a07a..d5840276 100644
--- a/Controller/TokenController.php
+++ b/Controller/TokenController.php
@@ -25,17 +25,12 @@ class TokenController
*/
protected $server;
- /**
- * @param OAuth2 $server
- */
public function __construct(OAuth2 $server)
{
$this->server = $server;
}
/**
- * @param Request $request
- *
* @return Response
*/
public function tokenAction(Request $request)
diff --git a/DependencyInjection/Compiler/GrantExtensionsCompilerPass.php b/DependencyInjection/Compiler/GrantExtensionsCompilerPass.php
index 31cdaca7..a433b61c 100644
--- a/DependencyInjection/Compiler/GrantExtensionsCompilerPass.php
+++ b/DependencyInjection/Compiler/GrantExtensionsCompilerPass.php
@@ -13,6 +13,8 @@
namespace FOS\OAuthServerBundle\DependencyInjection\Compiler;
+use FOS\OAuthServerBundle\Storage\GrantExtensionDispatcherInterface;
+use ReflectionClass;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
@@ -23,12 +25,12 @@
*/
class GrantExtensionsCompilerPass implements CompilerPassInterface
{
- public function process(ContainerBuilder $container)
+ public function process(ContainerBuilder $container): void
{
$storageDefinition = $container->findDefinition('fos_oauth_server.storage');
$className = $container->getParameterBag()->resolveValue($storageDefinition->getClass());
- $storageClass = new \ReflectionClass($className);
- if (!$storageClass->implementsInterface('FOS\OAuthServerBundle\Storage\GrantExtensionDispatcherInterface')) {
+ $storageClass = new ReflectionClass($className);
+ if (!$storageClass->implementsInterface(GrantExtensionDispatcherInterface::class)) {
return;
}
diff --git a/DependencyInjection/Compiler/RequestStackCompilerPass.php b/DependencyInjection/Compiler/RequestStackCompilerPass.php
index a45f5ca3..1eeeb389 100644
--- a/DependencyInjection/Compiler/RequestStackCompilerPass.php
+++ b/DependencyInjection/Compiler/RequestStackCompilerPass.php
@@ -27,7 +27,7 @@ final class RequestStackCompilerPass implements CompilerPassInterface
/**
* {@inheritdoc}
*/
- public function process(ContainerBuilder $container)
+ public function process(ContainerBuilder $container): void
{
if ($container->has('request_stack')) {
return;
diff --git a/DependencyInjection/Compiler/TokenStorageCompilerPass.php b/DependencyInjection/Compiler/TokenStorageCompilerPass.php
deleted file mode 100644
index 2c55ebc0..00000000
--- a/DependencyInjection/Compiler/TokenStorageCompilerPass.php
+++ /dev/null
@@ -1,36 +0,0 @@
-
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace FOS\OAuthServerBundle\DependencyInjection\Compiler;
-
-use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
-use Symfony\Component\DependencyInjection\ContainerBuilder;
-use Symfony\Component\DependencyInjection\Reference;
-
-/**
- * @author Andras Ratz
- */
-class TokenStorageCompilerPass implements CompilerPassInterface
-{
- /**
- * {@inheritdoc}
- */
- public function process(ContainerBuilder $container)
- {
- $definition = $container->getDefinition('fos_oauth_server.security.authentication.listener');
-
- if ($container->hasDefinition('security.token_storage') === false) {
- $definition->replaceArgument(0, new Reference('security.context'));
- }
- }
-}
diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php
index 571fcafd..2bb09a69 100644
--- a/DependencyInjection/Configuration.php
+++ b/DependencyInjection/Configuration.php
@@ -13,6 +13,7 @@
namespace FOS\OAuthServerBundle\DependencyInjection;
+use InvalidArgumentException;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
@@ -20,19 +21,20 @@
/**
* This is the class that validates and merges configuration from your app/config files.
*
- * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
+ * To learn more see
+ * {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
- public function getConfigTreeBuilder()
+ public function getConfigTreeBuilder(): TreeBuilder
{
- $treeBuilder = new TreeBuilder();
+ $treeBuilder = new TreeBuilder('fos_oauth_server');
/** @var ArrayNodeDefinition $rootNode */
- $rootNode = $treeBuilder->root('fos_oauth_server');
+ $rootNode = $treeBuilder->getRootNode();
$supportedDrivers = ['orm', 'mongodb', 'propel', 'custom'];
@@ -43,20 +45,31 @@ public function getConfigTreeBuilder()
return $v;
}
- if (empty($v['service']['client_manager']) || $v['service']['client_manager'] === 'fos_oauth_server.client_manager.default') {
- throw new \InvalidArgumentException('The service client_manager must be set explicitly for custom db_driver.');
+ if (empty($v['service']['client_manager'])
+ ||
+ $v['service']['client_manager'] === 'fos_oauth_server.client_manager.default'
+ ) {
+ throw new InvalidArgumentException('The service client_manager must be set explicitly for custom db_driver.');
}
- if (empty($v['service']['access_token_manager']) || $v['service']['access_token_manager'] === 'fos_oauth_server.access_token_manager.default') {
- throw new \InvalidArgumentException('The service access_token_manager must be set explicitly for custom db_driver.');
+ if (empty($v['service']['access_token_manager'])
+ ||
+ $v['service']['access_token_manager'] === 'fos_oauth_server.access_token_manager.default') {
+ throw new InvalidArgumentException('The service access_token_manager must be set explicitly for custom db_driver.');
}
- if (empty($v['service']['refresh_token_manager']) || $v['service']['refresh_token_manager'] === 'fos_oauth_server.refresh_token_manager.default') {
- throw new \InvalidArgumentException('The service refresh_token_manager must be set explicitly for custom db_driver.');
+ if (empty($v['service']['refresh_token_manager'])
+ ||
+ $v['service']['refresh_token_manager'] === 'fos_oauth_server.refresh_token_manager.default'
+ ) {
+ throw new InvalidArgumentException('The service refresh_token_manager must be set explicitly for custom db_driver.');
}
- if (empty($v['service']['auth_code_manager']) || $v['service']['auth_code_manager'] === 'fos_oauth_server.auth_code_manager.default') {
- throw new \InvalidArgumentException('The service auth_code_manager must be set explicitly for custom db_driver.');
+ if (empty($v['service']['auth_code_manager'])
+ ||
+ $v['service']['auth_code_manager'] === 'fos_oauth_server.auth_code_manager.default'
+ ) {
+ throw new InvalidArgumentException('The service auth_code_manager must be set explicitly for custom db_driver.');
}
return $v;
@@ -66,7 +79,10 @@ public function getConfigTreeBuilder()
->scalarNode('db_driver')
->validate()
->ifNotInArray($supportedDrivers)
- ->thenInvalid('The driver %s is not supported. Please choose one of '.json_encode($supportedDrivers))
+ ->thenInvalid(
+ 'The driver %s is not supported. Please choose one of '
+ .json_encode($supportedDrivers)
+ )
->end()
->isRequired()
->cannotBeEmpty()
@@ -81,12 +97,11 @@ public function getConfigTreeBuilder()
$this->addAuthorizeSection($rootNode);
$this->addServiceSection($rootNode);
- $this->addTemplateSection($rootNode);
return $treeBuilder;
}
- private function addAuthorizeSection(ArrayNodeDefinition $node)
+ private function addAuthorizeSection(ArrayNodeDefinition $node): void
{
$node
->children()
@@ -97,9 +112,12 @@ private function addAuthorizeSection(ArrayNodeDefinition $node)
->arrayNode('form')
->addDefaultsIfNotSet()
->children()
- ->scalarNode('type')->defaultValue('fos_oauth_server_authorize')->end()
- ->scalarNode('handler')->defaultValue('fos_oauth_server.authorize.form.handler.default')->end()
- ->scalarNode('name')->defaultValue('fos_oauth_server_authorize_form')->cannotBeEmpty()->end()
+ ->scalarNode('type')
+ ->defaultValue('fos_oauth_server_authorize')->end()
+ ->scalarNode('handler')
+ ->defaultValue('fos_oauth_server.authorize.form.handler.default')->end()
+ ->scalarNode('name')
+ ->defaultValue('fos_oauth_server_authorize_form')->cannotBeEmpty()->end()
->arrayNode('validation_groups')
->prototype('scalar')->end()
->defaultValue(['Authorize', 'Default'])
@@ -112,7 +130,7 @@ private function addAuthorizeSection(ArrayNodeDefinition $node)
;
}
- private function addServiceSection(ArrayNodeDefinition $node)
+ private function addServiceSection(ArrayNodeDefinition $node): void
{
$node
->addDefaultsIfNotSet()
@@ -120,12 +138,18 @@ private function addServiceSection(ArrayNodeDefinition $node)
->arrayNode('service')
->addDefaultsIfNotSet()
->children()
- ->scalarNode('storage')->defaultValue('fos_oauth_server.storage.default')->cannotBeEmpty()->end()
- ->scalarNode('user_provider')->defaultNull()->end()
- ->scalarNode('client_manager')->defaultValue('fos_oauth_server.client_manager.default')->end()
- ->scalarNode('access_token_manager')->defaultValue('fos_oauth_server.access_token_manager.default')->end()
- ->scalarNode('refresh_token_manager')->defaultValue('fos_oauth_server.refresh_token_manager.default')->end()
- ->scalarNode('auth_code_manager')->defaultValue('fos_oauth_server.auth_code_manager.default')->end()
+ ->scalarNode('storage')
+ ->defaultValue('fos_oauth_server.storage.default')->cannotBeEmpty()->end()
+ ->scalarNode('user_provider')
+ ->defaultNull()->end()
+ ->scalarNode('client_manager')
+ ->defaultValue('fos_oauth_server.client_manager.default')->end()
+ ->scalarNode('access_token_manager')
+ ->defaultValue('fos_oauth_server.access_token_manager.default')->end()
+ ->scalarNode('refresh_token_manager')
+ ->defaultValue('fos_oauth_server.refresh_token_manager.default')->end()
+ ->scalarNode('auth_code_manager')
+ ->defaultValue('fos_oauth_server.auth_code_manager.default')->end()
->arrayNode('options')
->useAttributeAsKey('key')
->treatNullLike([])
@@ -137,18 +161,4 @@ private function addServiceSection(ArrayNodeDefinition $node)
->end()
;
}
-
- private function addTemplateSection(ArrayNodeDefinition $node)
- {
- $node
- ->children()
- ->arrayNode('template')
- ->addDefaultsIfNotSet()
- ->children()
- ->scalarNode('engine')->defaultValue('twig')->end()
- ->end()
- ->end()
- ->end()
- ;
- }
}
diff --git a/DependencyInjection/FOSOAuthServerExtension.php b/DependencyInjection/FOSOAuthServerExtension.php
index 256bff31..1a153df9 100644
--- a/DependencyInjection/FOSOAuthServerExtension.php
+++ b/DependencyInjection/FOSOAuthServerExtension.php
@@ -163,7 +163,7 @@ private function computeArraySupportedScopes(array $supportedScopes)
{
foreach ($supportedScopes as $scope) {
if (false !== mb_strpos($scope, ' ')) {
- throw new InvalidConfigurationException('The array notation for supported_scopes should not contain spaces in array items. Either use full array notation or use the string notation for supported_scopes. See https://git.io/vx1X0 for more informations.');
+ throw new InvalidConfigurationException('The array notation for supported_scopes should not contain spaces in array items. Either use full array notation or use the string notation for supported_scopes. See https://git.io/vx1X0 for more information.');
}
}
diff --git a/DependencyInjection/Security/Factory/OAuthFactory.php b/DependencyInjection/Security/Factory/OAuthFactory.php
index 62146aa8..4710832b 100644
--- a/DependencyInjection/Security/Factory/OAuthFactory.php
+++ b/DependencyInjection/Security/Factory/OAuthFactory.php
@@ -15,6 +15,7 @@
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
+use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
@@ -28,11 +29,11 @@ class OAuthFactory implements SecurityFactoryInterface
/**
* {@inheritdoc}
*/
- public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint)
+ public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint): array
{
// NOTE: done like this to avoid PHPStan complaining about a missing class for both Symfony v3 and Symfony v4
$definitionDecorator = 'Symfony\\Component\\DependencyInjection\\DefinitionDecorator';
- $childDefinition = 'Symfony\\Component\\DependencyInjection\\ChildDefinition';
+ $childDefinition = ChildDefinition::class;
$definitionClass = $childDefinition;
if (class_exists($definitionDecorator)) {
$definitionClass = $definitionDecorator;
@@ -45,7 +46,10 @@ public function create(ContainerBuilder $container, $id, $config, $userProvider,
;
$listenerId = 'security.authentication.listener.fos_oauth_server.'.$id;
- $container->setDefinition($listenerId, new $definitionClass('fos_oauth_server.security.authentication.listener'));
+ $container->setDefinition(
+ $listenerId,
+ new $definitionClass('fos_oauth_server.security.authentication.listener')
+ );
return [$providerId, $listenerId, 'fos_oauth_server.security.entry_point'];
}
@@ -53,7 +57,7 @@ public function create(ContainerBuilder $container, $id, $config, $userProvider,
/**
* {@inheritdoc}
*/
- public function getPosition()
+ public function getPosition(): string
{
return 'pre_auth';
}
@@ -61,7 +65,7 @@ public function getPosition()
/**
* {@inheritdoc}
*/
- public function getKey()
+ public function getKey(): string
{
return 'fos_oauth';
}
@@ -69,7 +73,7 @@ public function getKey()
/**
* {@inheritdoc}
*/
- public function addConfiguration(NodeDefinition $node)
+ public function addConfiguration(NodeDefinition $node): void
{
}
}
diff --git a/Document/AuthCodeManager.php b/Document/AuthCodeManager.php
index bdcc2ad1..fe45b735 100644
--- a/Document/AuthCodeManager.php
+++ b/Document/AuthCodeManager.php
@@ -14,7 +14,7 @@
namespace FOS\OAuthServerBundle\Document;
use Doctrine\ODM\MongoDB\DocumentManager;
-use Doctrine\ODM\MongoDB\DocumentRepository;
+use Doctrine\ODM\MongoDB\Repository\DocumentRepository;
use FOS\OAuthServerBundle\Model\AuthCodeInterface;
use FOS\OAuthServerBundle\Model\AuthCodeManager as BaseAuthCodeManager;
@@ -49,7 +49,7 @@ public function __construct(DocumentManager $dm, $class)
/**
* {@inheritdoc}
*/
- public function getClass()
+ public function getClass(): string
{
return $this->class;
}
@@ -65,7 +65,7 @@ public function findAuthCodeBy(array $criteria)
/**
* {@inheritdoc}
*/
- public function updateAuthCode(AuthCodeInterface $authCode)
+ public function updateAuthCode(AuthCodeInterface $authCode): void
{
$this->dm->persist($authCode);
$this->dm->flush();
@@ -74,7 +74,7 @@ public function updateAuthCode(AuthCodeInterface $authCode)
/**
* {@inheritdoc}
*/
- public function deleteAuthCode(AuthCodeInterface $authCode)
+ public function deleteAuthCode(AuthCodeInterface $authCode): void
{
$this->dm->remove($authCode);
$this->dm->flush();
@@ -83,8 +83,9 @@ public function deleteAuthCode(AuthCodeInterface $authCode)
/**
* {@inheritdoc}
*/
- public function deleteExpired()
+ public function deleteExpired(): int
{
+ /** @var \MongoDB\Driver\WriteResult */
$result = $this
->repository
->createQueryBuilder()
@@ -94,6 +95,6 @@ public function deleteExpired()
->execute()
;
- return $result['n'];
+ return $result->getDeletedCount();
}
}
diff --git a/Document/ClientManager.php b/Document/ClientManager.php
index 73a95d63..5fde9b3d 100644
--- a/Document/ClientManager.php
+++ b/Document/ClientManager.php
@@ -14,7 +14,7 @@
namespace FOS\OAuthServerBundle\Document;
use Doctrine\ODM\MongoDB\DocumentManager;
-use Doctrine\ODM\MongoDB\DocumentRepository;
+use Doctrine\ODM\MongoDB\Repository\DocumentRepository;
use FOS\OAuthServerBundle\Model\ClientInterface;
use FOS\OAuthServerBundle\Model\ClientManager as BaseClientManager;
@@ -49,7 +49,7 @@ public function __construct(DocumentManager $dm, $class)
/**
* {@inheritdoc}
*/
- public function getClass()
+ public function getClass(): string
{
return $this->class;
}
@@ -65,7 +65,7 @@ public function findClientBy(array $criteria)
/**
* {@inheritdoc}
*/
- public function updateClient(ClientInterface $client)
+ public function updateClient(ClientInterface $client): void
{
$this->dm->persist($client);
$this->dm->flush();
@@ -74,7 +74,7 @@ public function updateClient(ClientInterface $client)
/**
* {@inheritdoc}
*/
- public function deleteClient(ClientInterface $client)
+ public function deleteClient(ClientInterface $client): void
{
$this->dm->remove($client);
$this->dm->flush();
diff --git a/Document/TokenManager.php b/Document/TokenManager.php
index 9050924d..5f5fab7a 100644
--- a/Document/TokenManager.php
+++ b/Document/TokenManager.php
@@ -83,8 +83,9 @@ public function deleteToken(TokenInterface $token)
/**
* {@inheritdoc}
*/
- public function deleteExpired()
+ public function deleteExpired(): int
{
+ /** @var \MongoDB\Driver\WriteResult */
$result = $this
->repository
->createQueryBuilder()
@@ -94,6 +95,6 @@ public function deleteExpired()
->execute()
;
- return $result['n'];
+ return $result->getDeletedCount();
}
}
diff --git a/Entity/AuthCodeManager.php b/Entity/AuthCodeManager.php
index 048a9cee..355f2bd2 100644
--- a/Entity/AuthCodeManager.php
+++ b/Entity/AuthCodeManager.php
@@ -30,8 +30,7 @@ class AuthCodeManager extends BaseAuthCodeManager
protected $class;
/**
- * @param EntityManagerInterface $em
- * @param string $class
+ * @param string $class
*/
public function __construct(EntityManagerInterface $em, $class)
{
diff --git a/Event/OAuthEvent.php b/Event/OAuthEvent.php
index f686e4df..c0834d11 100644
--- a/Event/OAuthEvent.php
+++ b/Event/OAuthEvent.php
@@ -14,14 +14,13 @@
namespace FOS\OAuthServerBundle\Event;
use FOS\OAuthServerBundle\Model\ClientInterface;
-use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Security\Core\User\UserInterface;
+use Symfony\Contracts\EventDispatcher\Event;
class OAuthEvent extends Event
{
- const PRE_AUTHORIZATION_PROCESS = 'fos_oauth_server.pre_authorization_process';
-
- const POST_AUTHORIZATION_PROCESS = 'fos_oauth_server.post_authorization_process';
+ public const PRE_AUTHORIZATION_PROCESS = 'fos_oauth_server.pre_authorization_process';
+ public const POST_AUTHORIZATION_PROCESS = 'fos_oauth_server.post_authorization_process';
/**
* @var UserInterface
@@ -39,9 +38,7 @@ class OAuthEvent extends Event
private $isAuthorizedClient;
/**
- * @param UserInterface $user
- * @param ClientInterface $client
- * @param bool $isAuthorizedClient
+ * @param bool $isAuthorizedClient
*/
public function __construct(UserInterface $user, ClientInterface $client, $isAuthorizedClient = false)
{
@@ -50,10 +47,7 @@ public function __construct(UserInterface $user, ClientInterface $client, $isAut
$this->isAuthorizedClient = $isAuthorizedClient;
}
- /**
- * @return UserInterface
- */
- public function getUser()
+ public function getUser(): UserInterface
{
return $this->user;
}
@@ -61,23 +55,17 @@ public function getUser()
/**
* @param bool $isAuthorizedClient
*/
- public function setAuthorizedClient($isAuthorizedClient)
+ public function setAuthorizedClient($isAuthorizedClient): void
{
$this->isAuthorizedClient = $isAuthorizedClient;
}
- /**
- * @return bool
- */
- public function isAuthorizedClient()
+ public function isAuthorizedClient(): bool
{
return $this->isAuthorizedClient;
}
- /**
- * @return ClientInterface
- */
- public function getClient()
+ public function getClient(): ClientInterface
{
return $this->client;
}
diff --git a/FOSOAuthServerBundle.php b/FOSOAuthServerBundle.php
index c6ba0f9f..1505745d 100644
--- a/FOSOAuthServerBundle.php
+++ b/FOSOAuthServerBundle.php
@@ -15,7 +15,6 @@
use FOS\OAuthServerBundle\DependencyInjection\Compiler\GrantExtensionsCompilerPass;
use FOS\OAuthServerBundle\DependencyInjection\Compiler\RequestStackCompilerPass;
-use FOS\OAuthServerBundle\DependencyInjection\Compiler\TokenStorageCompilerPass;
use FOS\OAuthServerBundle\DependencyInjection\FOSOAuthServerExtension;
use FOS\OAuthServerBundle\DependencyInjection\Security\Factory\OAuthFactory;
use Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension;
@@ -38,7 +37,6 @@ public function build(ContainerBuilder $container)
$extension->addSecurityListenerFactory(new OAuthFactory());
$container->addCompilerPass(new GrantExtensionsCompilerPass());
- $container->addCompilerPass(new TokenStorageCompilerPass());
$container->addCompilerPass(new RequestStackCompilerPass());
}
}
diff --git a/Form/Handler/AuthorizeFormHandler.php b/Form/Handler/AuthorizeFormHandler.php
index df219c04..4f29097d 100644
--- a/Form/Handler/AuthorizeFormHandler.php
+++ b/Form/Handler/AuthorizeFormHandler.php
@@ -40,7 +40,6 @@ class AuthorizeFormHandler
private $requestStack;
/**
- * @param FormInterface $form
* @param Request|RequestStack $requestStack
*/
public function __construct(FormInterface $form, $requestStack = null)
@@ -94,7 +93,7 @@ public function process()
}
$this->form->handleRequest($request);
- if (!$this->form->isValid()) {
+ if ($this->form->isSubmitted() && $this->form->isValid() === false) {
return false;
}
diff --git a/Form/Model/Authorize.php b/Form/Model/Authorize.php
index fa639ea5..0811c81e 100644
--- a/Form/Model/Authorize.php
+++ b/Form/Model/Authorize.php
@@ -48,10 +48,6 @@ class Authorize
*/
public $scope;
- /**
- * @param bool $accepted
- * @param array $query
- */
public function __construct(bool $accepted, array $query = [])
{
foreach ($query as $key => $value) {
diff --git a/Form/Type/AuthorizeFormType.php b/Form/Type/AuthorizeFormType.php
index 08aec45f..cfecf2a1 100644
--- a/Form/Type/AuthorizeFormType.php
+++ b/Form/Type/AuthorizeFormType.php
@@ -41,6 +41,7 @@ public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'FOS\OAuthServerBundle\Form\Model\Authorize',
+ 'validation_groups' => [],
]);
}
diff --git a/Model/AuthCodeManagerInterface.php b/Model/AuthCodeManagerInterface.php
index 2239a849..23811b0d 100644
--- a/Model/AuthCodeManagerInterface.php
+++ b/Model/AuthCodeManagerInterface.php
@@ -35,8 +35,6 @@ public function getClass();
/**
* Retrieve an auth code using a set of criteria.
*
- * @param array $criteria
- *
* @return AuthCodeInterface|null
*/
public function findAuthCodeBy(array $criteria);
@@ -52,15 +50,11 @@ public function findAuthCodeByToken($token);
/**
* Update a given auth code.
- *
- * @param AuthCodeInterface $authCode
*/
public function updateAuthCode(AuthCodeInterface $authCode);
/**
* Delete a given auth code.
- *
- * @param AuthCodeInterface $authCode
*/
public function deleteAuthCode(AuthCodeInterface $authCode);
diff --git a/Model/ClientInterface.php b/Model/ClientInterface.php
index 1a179bee..c985d847 100644
--- a/Model/ClientInterface.php
+++ b/Model/ClientInterface.php
@@ -44,14 +44,8 @@ public function checkSecret($secret);
*/
public function getSecret();
- /**
- * @param array $redirectUris
- */
public function setRedirectUris(array $redirectUris);
- /**
- * @param array $grantTypes
- */
public function setAllowedGrantTypes(array $grantTypes);
/**
diff --git a/Model/ClientManagerInterface.php b/Model/ClientManagerInterface.php
index c62b542d..31b3ed38 100644
--- a/Model/ClientManagerInterface.php
+++ b/Model/ClientManagerInterface.php
@@ -26,24 +26,18 @@ public function createClient();
public function getClass();
/**
- * @return null|ClientInterface
+ * @return ClientInterface|null
*/
public function findClientBy(array $criteria);
/**
* @param mixed $publicId
*
- * @return null|ClientInterface
+ * @return ClientInterface|null
*/
public function findClientByPublicId($publicId);
- /**
- * @param ClientInterface $client
- */
public function updateClient(ClientInterface $client);
- /**
- * @param ClientInterface $client
- */
public function deleteClient(ClientInterface $client);
}
diff --git a/Model/TokenInterface.php b/Model/TokenInterface.php
index f6dcf3aa..3d32ef23 100644
--- a/Model/TokenInterface.php
+++ b/Model/TokenInterface.php
@@ -38,9 +38,6 @@ public function setToken($token);
*/
public function setScope($scope);
- /**
- * @param UserInterface $user
- */
public function setUser(UserInterface $user);
/**
@@ -48,8 +45,5 @@ public function setUser(UserInterface $user);
*/
public function getUser();
- /**
- * @param ClientInterface $client
- */
public function setClient(ClientInterface $client);
}
diff --git a/Model/TokenManagerInterface.php b/Model/TokenManagerInterface.php
index e6688dd8..efbd9377 100644
--- a/Model/TokenManagerInterface.php
+++ b/Model/TokenManagerInterface.php
@@ -32,8 +32,6 @@ public function getClass();
/**
* Retrieve a token using a set of criteria.
*
- * @param array $criteria
- *
* @return TokenInterface|null
*/
public function findTokenBy(array $criteria);
diff --git a/Resources/config/authorize.xml b/Resources/config/authorize.xml
index add0e780..540ac0e5 100644
--- a/Resources/config/authorize.xml
+++ b/Resources/config/authorize.xml
@@ -28,13 +28,12 @@
-
+
- %fos_oauth_server.template.engine%
diff --git a/Resources/doc/configuration_reference.md b/Resources/doc/configuration_reference.md
index 9529fa32..deade0e9 100644
--- a/Resources/doc/configuration_reference.md
+++ b/Resources/doc/configuration_reference.md
@@ -50,8 +50,6 @@ fos_oauth_server:
# Enforce state to be passed in authorization (see RFC 6749, section 10.12)
#enforce_state: true or false
- template:
- engine: twig
```
[Back to index](index.md)
diff --git a/Security/Authentication/Provider/OAuthProvider.php b/Security/Authentication/Provider/OAuthProvider.php
index bb11eae6..33089ecb 100644
--- a/Security/Authentication/Provider/OAuthProvider.php
+++ b/Security/Authentication/Provider/OAuthProvider.php
@@ -60,7 +60,7 @@ public function __construct(UserProviderInterface $userProvider, OAuth2 $serverS
/**
* @param OAuthToken&TokenInterface $token
*
- * @return null|OAuthToken
+ * @return OAuthToken|null
*/
public function authenticate(TokenInterface $token)
{
@@ -85,12 +85,7 @@ public function authenticate(TokenInterface $token)
try {
$this->userChecker->checkPreAuth($user);
} catch (AccountStatusException $e) {
- throw new OAuth2AuthenticateException(Response::HTTP_UNAUTHORIZED,
- OAuth2::TOKEN_TYPE_BEARER,
- $this->serverService->getVariable(OAuth2::CONFIG_WWW_REALM),
- 'access_denied',
- $e->getMessage()
- );
+ throw new OAuth2AuthenticateException(Response::HTTP_UNAUTHORIZED, OAuth2::TOKEN_TYPE_BEARER, $this->serverService->getVariable(OAuth2::CONFIG_WWW_REALM), 'access_denied', $e->getMessage());
}
$token->setUser($user);
@@ -114,12 +109,7 @@ public function authenticate(TokenInterface $token)
try {
$this->userChecker->checkPostAuth($user);
} catch (AccountStatusException $e) {
- throw new OAuth2AuthenticateException(Response::HTTP_UNAUTHORIZED,
- OAuth2::TOKEN_TYPE_BEARER,
- $this->serverService->getVariable(OAuth2::CONFIG_WWW_REALM),
- 'access_denied',
- $e->getMessage()
- );
+ throw new OAuth2AuthenticateException(Response::HTTP_UNAUTHORIZED, OAuth2::TOKEN_TYPE_BEARER, $this->serverService->getVariable(OAuth2::CONFIG_WWW_REALM), 'access_denied', $e->getMessage());
}
$token->setUser($user);
diff --git a/Security/Firewall/OAuthListener.php b/Security/Firewall/OAuthListener.php
index 914fcb9e..7546b2e4 100644
--- a/Security/Firewall/OAuthListener.php
+++ b/Security/Firewall/OAuthListener.php
@@ -16,19 +16,18 @@
use FOS\OAuthServerBundle\Security\Authentication\Token\OAuthToken;
use OAuth2\OAuth2;
use Symfony\Component\HttpFoundation\Response;
-use Symfony\Component\HttpKernel\Event\GetResponseEvent;
+use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
-use Symfony\Component\Security\Http\Firewall\ListenerInterface;
/**
* OAuthListener class.
*
* @author Arnaud Le Blanc
*/
-class OAuthListener implements ListenerInterface
+class OAuthListener
{
/**
* @var TokenStorageInterface
@@ -48,19 +47,23 @@ class OAuthListener implements ListenerInterface
/**
* @param TokenStorageInterface $tokenStorage the token storage
* @param AuthenticationManagerInterface $authenticationManager the authentication manager
- * @param OAuth2 $serverService
*/
- public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager, OAuth2 $serverService)
- {
+ public function __construct(
+ TokenStorageInterface $tokenStorage,
+ AuthenticationManagerInterface $authenticationManager,
+ OAuth2 $serverService
+ ) {
$this->tokenStorage = $tokenStorage;
$this->authenticationManager = $authenticationManager;
$this->serverService = $serverService;
}
- /**
- * @param GetResponseEvent $event the event
- */
- public function handle(GetResponseEvent $event)
+ public function __invoke(RequestEvent $event)
+ {
+ $this->handle($event);
+ }
+
+ public function handle(RequestEvent $event): void
{
if (null === $oauthToken = $this->serverService->getBearerToken($event->getRequest(), true)) {
return;
@@ -70,14 +73,12 @@ public function handle(GetResponseEvent $event)
$token->setToken($oauthToken);
try {
- $returnValue = $this->authenticationManager->authenticate($token);
-
- if ($returnValue instanceof TokenInterface) {
- return $this->tokenStorage->setToken($returnValue);
- }
+ $authenticateResult = $this->authenticationManager->authenticate($token);
- if ($returnValue instanceof Response) {
- return $event->setResponse($returnValue);
+ if ($authenticateResult instanceof TokenInterface) {
+ $this->tokenStorage->setToken($authenticateResult);
+ } elseif ($authenticateResult instanceof Response) {
+ $event->setResponse($authenticateResult);
}
} catch (AuthenticationException $e) {
if (null !== $p = $e->getPrevious()) {
diff --git a/Storage/OAuthStorage.php b/Storage/OAuthStorage.php
index a56dd25a..9b6d1f02 100644
--- a/Storage/OAuthStorage.php
+++ b/Storage/OAuthStorage.php
@@ -14,10 +14,13 @@
namespace FOS\OAuthServerBundle\Storage;
use FOS\OAuthServerBundle\Model\AccessTokenManagerInterface;
+use FOS\OAuthServerBundle\Model\AuthCodeInterface;
use FOS\OAuthServerBundle\Model\AuthCodeManagerInterface;
use FOS\OAuthServerBundle\Model\ClientInterface;
use FOS\OAuthServerBundle\Model\ClientManagerInterface;
use FOS\OAuthServerBundle\Model\RefreshTokenManagerInterface;
+use FOS\OAuthServerBundle\Model\TokenInterface;
+use InvalidArgumentException;
use OAuth2\IOAuth2GrantClient;
use OAuth2\IOAuth2GrantCode;
use OAuth2\IOAuth2GrantExtension;
@@ -69,18 +72,14 @@ class OAuthStorage implements IOAuth2RefreshTokens, IOAuth2GrantUser, IOAuth2Gra
*/
protected $grantExtensions;
- /**
- * @param ClientManagerInterface $clientManager
- * @param AccessTokenManagerInterface $accessTokenManager
- * @param RefreshTokenManagerInterface $refreshTokenManager
- * @param AuthCodeManagerInterface $authCodeManager
- * @param null|UserProviderInterface $userProvider
- * @param null|EncoderFactoryInterface $encoderFactory
- */
- public function __construct(ClientManagerInterface $clientManager, AccessTokenManagerInterface $accessTokenManager,
- RefreshTokenManagerInterface $refreshTokenManager, AuthCodeManagerInterface $authCodeManager,
- UserProviderInterface $userProvider = null, EncoderFactoryInterface $encoderFactory = null)
- {
+ public function __construct(
+ ClientManagerInterface $clientManager,
+ AccessTokenManagerInterface $accessTokenManager,
+ RefreshTokenManagerInterface $refreshTokenManager,
+ AuthCodeManagerInterface $authCodeManager,
+ UserProviderInterface $userProvider = null,
+ EncoderFactoryInterface $encoderFactory = null
+ ) {
$this->clientManager = $clientManager;
$this->accessTokenManager = $accessTokenManager;
$this->refreshTokenManager = $refreshTokenManager;
@@ -107,7 +106,7 @@ public function getClient($clientId)
public function checkClientCredentials(IOAuth2Client $client, $client_secret = null)
{
if (!$client instanceof ClientInterface) {
- throw new \InvalidArgumentException('Client has to implement the ClientInterface');
+ throw new InvalidArgumentException('Client has to implement the ClientInterface');
}
return $client->checkSecret($client_secret);
@@ -123,10 +122,15 @@ public function getAccessToken($token)
return $this->accessTokenManager->findTokenByToken($token);
}
- public function createAccessToken($tokenString, IOAuth2Client $client, $data, $expires, $scope = null)
- {
+ public function createAccessToken(
+ $tokenString,
+ IOAuth2Client $client,
+ $data,
+ $expires,
+ $scope = null
+ ): TokenInterface {
if (!$client instanceof ClientInterface) {
- throw new \InvalidArgumentException('Client has to implement the ClientInterface');
+ throw new InvalidArgumentException('Client has to implement the ClientInterface');
}
$token = $this->accessTokenManager->createToken();
@@ -147,7 +151,7 @@ public function createAccessToken($tokenString, IOAuth2Client $client, $data, $e
public function checkRestrictedGrantType(IOAuth2Client $client, $grant_type)
{
if (!$client instanceof ClientInterface) {
- throw new \InvalidArgumentException('Client has to implement the ClientInterface');
+ throw new InvalidArgumentException('Client has to implement the ClientInterface');
}
return in_array($grant_type, $client->getAllowedGrantTypes(), true);
@@ -156,7 +160,7 @@ public function checkRestrictedGrantType(IOAuth2Client $client, $grant_type)
public function checkUserCredentials(IOAuth2Client $client, $username, $password)
{
if (!$client instanceof ClientInterface) {
- throw new \InvalidArgumentException('Client has to implement the ClientInterface');
+ throw new InvalidArgumentException('Client has to implement the ClientInterface');
}
try {
@@ -186,10 +190,16 @@ public function getAuthCode($code)
/**
* {@inheritdoc}
*/
- public function createAuthCode($code, IOAuth2Client $client, $data, $redirect_uri, $expires, $scope = null)
- {
+ public function createAuthCode(
+ $code,
+ IOAuth2Client $client,
+ $data,
+ $redirect_uri,
+ $expires,
+ $scope = null
+ ): AuthCodeInterface {
if (!$client instanceof ClientInterface) {
- throw new \InvalidArgumentException('Client has to implement the ClientInterface');
+ throw new InvalidArgumentException('Client has to implement the ClientInterface');
}
$authCode = $this->authCodeManager->createAuthCode();
@@ -218,7 +228,7 @@ public function getRefreshToken($tokenString)
public function createRefreshToken($tokenString, IOAuth2Client $client, $data, $expires, $scope = null)
{
if (!$client instanceof ClientInterface) {
- throw new \InvalidArgumentException('Client has to implement the ClientInterface');
+ throw new InvalidArgumentException('Client has to implement the ClientInterface');
}
$token = $this->refreshTokenManager->createToken();
diff --git a/Tests/Command/CleanCommandTest.php b/Tests/Command/CleanCommandTest.php
index 92dbb9a9..99aa0d26 100644
--- a/Tests/Command/CleanCommandTest.php
+++ b/Tests/Command/CleanCommandTest.php
@@ -16,10 +16,12 @@
use FOS\OAuthServerBundle\Command\CleanCommand;
use FOS\OAuthServerBundle\Model\AuthCodeManagerInterface;
use FOS\OAuthServerBundle\Model\TokenManagerInterface;
+use PHPUnit\Framework\MockObject\MockObject;
+use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
-class CleanCommandTest extends \PHPUnit\Framework\TestCase
+class CleanCommandTest extends TestCase
{
/**
* @var CleanCommand
@@ -27,24 +29,24 @@ class CleanCommandTest extends \PHPUnit\Framework\TestCase
private $command;
/**
- * @var \PHPUnit_Framework_MockObject_MockObject|TokenManagerInterface
+ * @var MockObject|TokenManagerInterface
*/
private $accessTokenManager;
/**
- * @var \PHPUnit_Framework_MockObject_MockObject|TokenManagerInterface
+ * @var MockObject|TokenManagerInterface
*/
private $refreshTokenManager;
/**
- * @var \PHPUnit_Framework_MockObject_MockObject|AuthCodeManagerInterface
+ * @var MockObject|AuthCodeManagerInterface
*/
private $authCodeManager;
/**
* {@inheritdoc}
*/
- protected function setUp()
+ protected function setUp(): void
{
$this->accessTokenManager = $this->getMockBuilder(TokenManagerInterface::class)->disableOriginalConstructor()->getMock();
$this->refreshTokenManager = $this->getMockBuilder(TokenManagerInterface::class)->disableOriginalConstructor()->getMock();
@@ -64,27 +66,27 @@ protected function setUp()
/**
* Delete expired tokens for provided classes.
*/
- public function testItShouldRemoveExpiredToken()
+ public function testItShouldRemoveExpiredToken(): void
{
$expiredAccessTokens = 5;
$this->accessTokenManager
->expects($this->once())
->method('deleteExpired')
- ->will($this->returnValue($expiredAccessTokens))
+ ->willReturn($expiredAccessTokens)
;
$expiredRefreshTokens = 183;
$this->refreshTokenManager
->expects($this->once())
->method('deleteExpired')
- ->will($this->returnValue($expiredRefreshTokens))
+ ->willReturn($expiredRefreshTokens)
;
$expiredAuthCodes = 0;
$this->authCodeManager
->expects($this->once())
->method('deleteExpired')
- ->will($this->returnValue($expiredAuthCodes))
+ ->willReturn($expiredAuthCodes)
;
$tester = new CommandTester($this->command);
@@ -92,15 +94,15 @@ public function testItShouldRemoveExpiredToken()
$display = $tester->getDisplay();
- $this->assertContains(sprintf('Removed %d items from %s storage.', $expiredAccessTokens, get_class($this->accessTokenManager)), $display);
- $this->assertContains(sprintf('Removed %d items from %s storage.', $expiredRefreshTokens, get_class($this->refreshTokenManager)), $display);
- $this->assertContains(sprintf('Removed %d items from %s storage.', $expiredAuthCodes, get_class($this->authCodeManager)), $display);
+ self::assertStringContainsString(sprintf('Removed %d items from %s storage.', $expiredAccessTokens, get_class($this->accessTokenManager)), $display);
+ self::assertStringContainsString(sprintf('Removed %d items from %s storage.', $expiredRefreshTokens, get_class($this->refreshTokenManager)), $display);
+ self::assertStringContainsString(sprintf('Removed %d items from %s storage.', $expiredAuthCodes, get_class($this->authCodeManager)), $display);
}
/**
* Skip classes for deleting expired tokens that do not implement AuthCodeManagerInterface or TokenManagerInterface.
*/
- public function testItShouldNotRemoveExpiredTokensForOtherClasses()
+ public function testItShouldNotRemoveExpiredTokensForOtherClasses(): void
{
$this->markTestIncomplete('Needs a better way of testing this');
@@ -109,8 +111,8 @@ public function testItShouldNotRemoveExpiredTokensForOtherClasses()
$display = $tester->getDisplay();
- $this->assertNotRegExp(sprintf('\'Removed (\d)+ items from %s storage.\'', get_class($this->accessTokenManager)), $display);
- $this->assertNotRegExp(sprintf('\'Removed (\d)+ items from %s storage.\'', get_class($this->refreshTokenManager)), $display);
- $this->assertNotRegExp(sprintf('\'Removed (\d)+ items from %s storage.\'', get_class($this->authCodeManager)), $display);
+ self::assertNotRegExp(sprintf('\'Removed (\d)+ items from %s storage.\'', get_class($this->accessTokenManager)), $display);
+ self::assertNotRegExp(sprintf('\'Removed (\d)+ items from %s storage.\'', get_class($this->refreshTokenManager)), $display);
+ self::assertNotRegExp(sprintf('\'Removed (\d)+ items from %s storage.\'', get_class($this->authCodeManager)), $display);
}
}
diff --git a/Tests/Command/CreateClientCommandTest.php b/Tests/Command/CreateClientCommandTest.php
index 4a50b206..fd088bc8 100644
--- a/Tests/Command/CreateClientCommandTest.php
+++ b/Tests/Command/CreateClientCommandTest.php
@@ -14,8 +14,10 @@
namespace FOS\OAuthServerBundle\Tests\Command;
use FOS\OAuthServerBundle\Command\CreateClientCommand;
+use FOS\OAuthServerBundle\Document\Client;
use FOS\OAuthServerBundle\Model\ClientManagerInterface;
use FOS\OAuthServerBundle\Tests\TestCase;
+use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
@@ -27,16 +29,20 @@ class CreateClientCommandTest extends TestCase
private $command;
/**
- * @var \PHPUnit_Framework_MockObject_MockObject|ClientManagerInterface
+ * @var MockObject|ClientManagerInterface
*/
private $clientManager;
/**
* {@inheritdoc}
*/
- protected function setUp()
+ protected function setUp(): void
{
- $this->clientManager = $this->getMockBuilder(ClientManagerInterface::class)->disableOriginalConstructor()->getMock();
+ $this->clientManager =
+ $this->getMockBuilder(ClientManagerInterface::class)
+ ->disableOriginalConstructor()
+ ->getMock()
+ ;
$command = new CreateClientCommand($this->clientManager);
$application = new Application();
@@ -53,13 +59,12 @@ protected function setUp()
*
* @param string $client a fully qualified class name
*/
- public function testItShouldCreateClient($client)
+ public function testItShouldCreateClient($client): void
{
$this
->clientManager
- ->expects($this->any())
->method('createClient')
- ->will($this->returnValue(new $client()))
+ ->willReturn(new $client())
;
$commandTester = new CommandTester($this->command);
@@ -76,24 +81,21 @@ public function testItShouldCreateClient($client)
],
]);
- $this->assertSame(0, $commandTester->getStatusCode());
+ self::assertSame(0, $commandTester->getStatusCode());
$output = $commandTester->getDisplay();
- $this->assertContains('Client ID', $output);
- $this->assertContains('Client Secret', $output);
+ self::assertStringContainsString('Client ID', $output);
+ self::assertStringContainsString('Client Secret', $output);
}
- /**
- * @return array
- */
- public function clientProvider()
+ public function clientProvider(): array
{
return [
- ['FOS\OAuthServerBundle\Document\Client'],
- ['FOS\OAuthServerBundle\Entity\Client'],
- ['FOS\OAuthServerBundle\Model\Client'],
- ['FOS\OAuthServerBundle\Propel\Client'],
+ [Client::class],
+ [\FOS\OAuthServerBundle\Entity\Client::class],
+ [\FOS\OAuthServerBundle\Model\Client::class],
+ [\FOS\OAuthServerBundle\Propel\Client::class],
];
}
}
diff --git a/Tests/Controller/AuthorizeControllerFunctionalTest.php b/Tests/Controller/AuthorizeControllerFunctionalTest.php
new file mode 100644
index 00000000..40c76c31
--- /dev/null
+++ b/Tests/Controller/AuthorizeControllerFunctionalTest.php
@@ -0,0 +1,85 @@
+
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace FOS\OAuthServerBundle\Tests\Controller;
+
+use FOS\OAuthServerBundle\Tests\Functional\TestCase;
+use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
+use Symfony\Component\Security\Core\Exception\AccessDeniedException;
+use Symfony\Component\Security\Core\User\UserInterface;
+use Symfony\Component\Security\Guard\Token\PostAuthenticationGuardToken;
+
+class AuthorizeControllerFunctionalTest extends TestCase
+{
+ public function setUp(): void
+ {
+ parent::setUp();
+
+ $this->client = $this->createClient();
+ }
+
+ public function tearDown(): void
+ {
+ unset($this->client);
+
+ parent::tearDown();
+ }
+
+ public function testAuthorizeActionWillThrowAccessDeniedException(): void
+ {
+ self::$kernel->getContainer()->get('security.token_storage')->setToken(new AnonymousToken('test-secret', 'anon'));
+
+ $this->expectException(AccessDeniedException::class);
+ $this->expectExceptionMessage('This user does not have access to this section.');
+
+ $this->client->catchExceptions(false);
+ $this->client->request('GET', '/oauth/v2/auth');
+ }
+
+ public function testAuthorizeActionWillRenderTemplate(): void
+ {
+ $user = $this->getMockBuilder(UserInterface::class)
+ ->disableOriginalConstructor()
+ ->getMock()
+ ;
+
+ self::$kernel->getContainer()->get('security.token_storage')->setToken(
+ new PostAuthenticationGuardToken($user, 'member_area', ['ROLE_USER'])
+ );
+
+ $this->client->catchExceptions(false);
+ $this->client->request('GET', '/oauth/v2/auth', [
+ 'client_id' => '123_test-client-id',
+ ]);
+
+ $this->assertResponse(200, '