2019-01-26 12:19:20 +03:00
|
|
|
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace ShlinkioApiTest\Shlink\Rest\Middleware;
|
|
|
|
|
|
|
|
use GuzzleHttp\Exception\ClientException;
|
2019-01-27 12:54:04 +03:00
|
|
|
use Shlinkio\Shlink\Rest\Authentication\Plugin\ApiKeyHeaderPlugin;
|
|
|
|
use Shlinkio\Shlink\Rest\Authentication\RequestToHttpAuthPlugin;
|
|
|
|
use Shlinkio\Shlink\Rest\Util\RestUtils;
|
2019-01-26 12:19:20 +03:00
|
|
|
use ShlinkioTest\Shlink\Common\ApiTest\ApiTestCase;
|
2019-01-27 12:54:04 +03:00
|
|
|
use function implode;
|
|
|
|
use function Shlinkio\Shlink\Common\json_decode;
|
|
|
|
use function sprintf;
|
2019-01-26 12:19:20 +03:00
|
|
|
|
|
|
|
class AuthenticationTest extends ApiTestCase
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @test
|
|
|
|
*/
|
2019-01-27 12:54:04 +03:00
|
|
|
public function authorizationErrorIsReturnedIfNoApiKeyIsSent()
|
2019-01-26 12:19:20 +03:00
|
|
|
{
|
2019-01-27 12:54:04 +03:00
|
|
|
try {
|
|
|
|
$this->callApi(self::METHOD_GET, '/short-codes');
|
|
|
|
} catch (ClientException $e) {
|
2019-01-27 14:35:00 +03:00
|
|
|
['error' => $error, 'message' => $message] = $this->getJsonResponsePayload($e->getResponse());
|
2019-01-26 12:19:20 +03:00
|
|
|
|
2019-01-27 12:54:04 +03:00
|
|
|
$this->assertEquals(self::STATUS_UNAUTHORIZED, $e->getCode());
|
|
|
|
$this->assertEquals(RestUtils::INVALID_AUTHORIZATION_ERROR, $error);
|
|
|
|
$this->assertEquals(
|
|
|
|
sprintf(
|
|
|
|
'Expected one of the following authentication headers, but none were provided, ["%s"]',
|
|
|
|
implode('", "', RequestToHttpAuthPlugin::SUPPORTED_AUTH_HEADERS)
|
|
|
|
),
|
|
|
|
$message
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @test
|
2019-01-27 14:14:18 +03:00
|
|
|
* @dataProvider provideInvalidApiKeys
|
2019-01-27 12:54:04 +03:00
|
|
|
*/
|
2019-01-27 14:14:18 +03:00
|
|
|
public function apiKeyErrorIsReturnedWhenProvidedApiKeyIsInvalid(string $apiKey)
|
2019-01-27 12:54:04 +03:00
|
|
|
{
|
|
|
|
try {
|
|
|
|
$this->callApi(self::METHOD_GET, '/short-codes', [
|
|
|
|
'headers' => [
|
2019-01-27 14:14:18 +03:00
|
|
|
ApiKeyHeaderPlugin::HEADER_NAME => $apiKey,
|
2019-01-27 12:54:04 +03:00
|
|
|
],
|
|
|
|
]);
|
|
|
|
} catch (ClientException $e) {
|
|
|
|
['error' => $error, 'message' => $message] = json_decode((string) $e->getResponse()->getBody());
|
|
|
|
|
|
|
|
$this->assertEquals(self::STATUS_UNAUTHORIZED, $e->getCode());
|
|
|
|
$this->assertEquals(RestUtils::INVALID_API_KEY_ERROR, $error);
|
|
|
|
$this->assertEquals('Provided API key does not exist or is invalid.', $message);
|
|
|
|
}
|
2019-01-26 12:19:20 +03:00
|
|
|
}
|
2019-01-27 14:14:18 +03:00
|
|
|
|
|
|
|
public function provideInvalidApiKeys(): array
|
|
|
|
{
|
|
|
|
return [
|
|
|
|
'key which does not exist' => ['invalid'],
|
|
|
|
'key which is expired' => ['expired_api_key'],
|
|
|
|
'key which is disabled' => ['disabled_api_key'],
|
|
|
|
];
|
|
|
|
}
|
2019-01-26 12:19:20 +03:00
|
|
|
}
|