Moved whitelisted routes in CheckAuthenticationMiddleware to external configuration

This commit is contained in:
Alejandro Celaya 2018-05-01 18:35:12 +02:00
parent ef3c4aadf2
commit 2f5290b9d3
4 changed files with 32 additions and 6 deletions

View file

@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Shlinkio\Shlink\Rest;
return [
'auth' => [
'routes_whitelist' => [
Action\AuthenticateAction::class,
],
],
];

View file

@ -59,7 +59,12 @@ return [
Action\Tag\CreateTagsAction::class => [Service\Tag\TagService::class, LoggerInterface::class],
Action\Tag\UpdateTagAction::class => [Service\Tag\TagService::class, Translator::class, LoggerInterface::class],
Middleware\CheckAuthenticationMiddleware::class => [JWTService::class, 'translator', 'Logger_Shlink'],
Middleware\CheckAuthenticationMiddleware::class => [
JWTService::class,
'translator',
'config.auth.routes_whitelist',
'Logger_Shlink',
],
],
];

View file

@ -10,7 +10,6 @@ use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Shlinkio\Shlink\Rest\Action\AuthenticateAction;
use Shlinkio\Shlink\Rest\Authentication\JWTServiceInterface;
use Shlinkio\Shlink\Rest\Exception\AuthenticationException;
use Shlinkio\Shlink\Rest\Util\RestUtils;
@ -35,14 +34,20 @@ class CheckAuthenticationMiddleware implements MiddlewareInterface, StatusCodeIn
* @var LoggerInterface
*/
private $logger;
/**
* @var array
*/
private $routesWhitelist;
public function __construct(
JWTServiceInterface $jwtService,
TranslatorInterface $translator,
array $routesWhitelist,
LoggerInterface $logger = null
) {
$this->translator = $translator;
$this->jwtService = $jwtService;
$this->routesWhitelist = $routesWhitelist;
$this->logger = $logger ?: new NullLogger();
}
@ -64,8 +69,8 @@ class CheckAuthenticationMiddleware implements MiddlewareInterface, StatusCodeIn
$routeResult = $request->getAttribute(RouteResult::class);
if ($routeResult === null
|| $routeResult->isFailure()
|| $routeResult->getMatchedRouteName() === AuthenticateAction::class
|| $request->getMethod() === 'OPTIONS'
|| \in_array($routeResult->getMatchedRouteName(), $this->routesWhitelist, true)
) {
return $handler->handle($request);
}

View file

@ -37,9 +37,11 @@ class CheckAuthenticationMiddlewareTest extends TestCase
public function setUp()
{
$this->jwtService = $this->prophesize(JWTService::class);
$this->middleware = new CheckAuthenticationMiddleware($this->jwtService->reveal(), Translator::factory([]));
$this->dummyMiddleware = middleware(function ($request, $handler) {
return new Response\EmptyResponse;
$this->middleware = new CheckAuthenticationMiddleware($this->jwtService->reveal(), Translator::factory([]), [
AuthenticateAction::class,
]);
$this->dummyMiddleware = middleware(function () {
return new Response\EmptyResponse();
});
}