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

ApiKeyHeaderPlugin::verify()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 12
ccs 7
cts 7
cp 1
crap 2
rs 9.8666
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Rest\Authentication\Plugin;
5
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Http\Message\ServerRequestInterface;
8
use Shlinkio\Shlink\Rest\Exception\VerifyAuthenticationException;
9
use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface;
10
use Shlinkio\Shlink\Rest\Util\RestUtils;
11
use Zend\I18n\Translator\TranslatorInterface;
12
13
class ApiKeyHeaderPlugin implements AuthenticationPluginInterface
14
{
15
    public const HEADER_NAME = 'X-Api-Key';
16
17
    /**
18
     * @var ApiKeyServiceInterface
19
     */
20
    private $apiKeyService;
21
    /**
22
     * @var TranslatorInterface
23
     */
24
    private $translator;
25
26 3
    public function __construct(ApiKeyServiceInterface $apiKeyService, TranslatorInterface $translator)
27
    {
28 3
        $this->apiKeyService = $apiKeyService;
29 3
        $this->translator = $translator;
30 3
    }
31
32
    /**
33
     * @throws VerifyAuthenticationException
34
     */
35 2
    public function verify(ServerRequestInterface $request): void
36
    {
37 2
        $apiKey = $request->getHeaderLine(self::HEADER_NAME);
38 2
        if ($this->apiKeyService->check($apiKey)) {
39 1
            return;
40
        }
41
42 1
        throw VerifyAuthenticationException::withError(
43 1
            RestUtils::INVALID_API_KEY_ERROR,
44 1
            $this->translator->translate('Provided API key does not exist or is invalid.')
45
        );
46
    }
47
48 1
    public function update(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
49
    {
50 1
        return $response;
51
    }
52
}
53