Completed
Push — master ( 224127...d5dc6c )
by Alejandro
28s
created

AuthenticationMiddleware::process()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
nc 6
nop 2
dl 0
loc 30
ccs 19
cts 19
cp 1
crap 7
rs 8.5066
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Rest\Middleware;
5
6
use Fig\Http\Message\RequestMethodInterface;
7
use Fig\Http\Message\StatusCodeInterface;
8
use Psr\Container\ContainerExceptionInterface;
9
use Psr\Http\Message\ResponseInterface as Response;
10
use Psr\Http\Message\ServerRequestInterface as Request;
11
use Psr\Http\Server\MiddlewareInterface;
12
use Psr\Http\Server\RequestHandlerInterface;
13
use Psr\Log\LoggerInterface;
14
use Psr\Log\NullLogger;
15
use Shlinkio\Shlink\Rest\Authentication\RequestToHttpAuthPlugin;
16
use Shlinkio\Shlink\Rest\Authentication\RequestToHttpAuthPluginInterface;
17
use Shlinkio\Shlink\Rest\Exception\NoAuthenticationException;
18
use Shlinkio\Shlink\Rest\Exception\VerifyAuthenticationException;
19
use Shlinkio\Shlink\Rest\Util\RestUtils;
20
use Zend\Diactoros\Response\JsonResponse;
21
use Zend\Expressive\Router\RouteResult;
22
use Zend\I18n\Translator\TranslatorInterface;
23
use function implode;
24
use function in_array;
25
use function sprintf;
26
27
class AuthenticationMiddleware implements MiddlewareInterface, StatusCodeInterface, RequestMethodInterface
28
{
29
    /**
30
     * @var TranslatorInterface
31
     */
32
    private $translator;
33
    /**
34
     * @var LoggerInterface
35
     */
36
    private $logger;
37
    /**
38
     * @var array
39
     */
40
    private $routesWhitelist;
41
    /**
42
     * @var RequestToHttpAuthPluginInterface
43
     */
44
    private $requestToAuthPlugin;
45
46 8
    public function __construct(
47
        RequestToHttpAuthPluginInterface $requestToAuthPlugin,
48
        TranslatorInterface $translator,
49
        array $routesWhitelist,
50
        LoggerInterface $logger = null
51
    ) {
52 8
        $this->translator = $translator;
53 8
        $this->routesWhitelist = $routesWhitelist;
54 8
        $this->logger = $logger ?: new NullLogger();
0 ignored issues
show
Documentation Bug introduced by
It seems like $logger ?: new \Psr\Log\NullLogger() can also be of type object<Psr\Log\NullLogger>. However, the property $logger is declared as type object<Psr\Log\LoggerInterface>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
55 8
        $this->requestToAuthPlugin = $requestToAuthPlugin;
56 8
    }
57
58
    /**
59
     * Process an incoming server request and return a response, optionally delegating
60
     * to the next middleware component to create the response.
61
     *
62
     * @param Request $request
63
     * @param RequestHandlerInterface $handler
64
     *
65
     * @return Response
66
     * @throws \InvalidArgumentException
67
     */
68 8
    public function process(Request $request, RequestHandlerInterface $handler): Response
69
    {
70
        /** @var RouteResult|null $routeResult */
71 8
        $routeResult = $request->getAttribute(RouteResult::class);
72 8
        if ($routeResult === null
73 7
            || $routeResult->isFailure()
74 6
            || $request->getMethod() === self::METHOD_OPTIONS
75 8
            || in_array($routeResult->getMatchedRouteName(), $this->routesWhitelist, true)
76
        ) {
77 4
            return $handler->handle($request);
78
        }
79
80
        try {
81 4
            $plugin = $this->requestToAuthPlugin->fromRequest($request);
82 2
        } catch (ContainerExceptionInterface | NoAuthenticationException $e) {
83 2
            $this->logger->warning('Invalid or no authentication provided.' . PHP_EOL . $e);
84 2
            return $this->createErrorResponse(sprintf($this->translator->translate(
85 2
                'Expected one of the following authentication headers, but none were provided, ["%s"]'
86 2
            ), implode('", "', RequestToHttpAuthPlugin::SUPPORTED_AUTH_HEADERS)));
87
        }
88
89
        try {
90 2
            $plugin->verify($request);
91 1
            $response = $handler->handle($request);
92 1
            return $plugin->update($request, $response);
93 1
        } catch (VerifyAuthenticationException $e) {
94 1
            $this->logger->warning('Authentication verification failed.' . PHP_EOL . $e);
95 1
            return $this->createErrorResponse($e->getPublicMessage(), $e->getErrorCode());
96
        }
97
    }
98
99 3
    private function createErrorResponse(
100
        string $message,
101
        string $errorCode = RestUtils::INVALID_AUTHORIZATION_ERROR
102
    ): JsonResponse {
103 3
        return new JsonResponse([
104 3
            'error' => $errorCode,
105 3
            'message' => $message,
106 3
        ], self::STATUS_UNAUTHORIZED);
107
    }
108
}
109