API: Set access-control-allow-origin header on api responses, trim bearer api key

This commit is contained in:
Igor Scheller 2024-01-02 13:05:32 +01:00 committed by Michael Weimann
parent 8c64447273
commit 3f03d6b1d8
4 changed files with 27 additions and 2 deletions

View File

@ -165,7 +165,7 @@ class Authenticator
{
$header = $this->request->getHeader('authorization');
if (!empty($header) && Str::startsWith(Str::lower($header[0]), 'bearer ')) {
return $this->userByApiKey(Str::substr($header[0], 7));
return $this->userByApiKey(trim(Str::substr($header[0], 7)));
}
$header = $this->request->getHeader('x-api-key');

View File

@ -61,7 +61,7 @@ class ApiRouteHandler implements MiddlewareInterface
{
try {
$response = $handler->handle($request);
} catch (ModelNotFoundException $e) {
} catch (ModelNotFoundException) {
$response = new Response('', 404);
$response->setContent($response->getReasonPhrase());
} catch (HttpException $e) {
@ -85,6 +85,10 @@ class ApiRouteHandler implements MiddlewareInterface
->withBody($content);
}
if (!$response->hasHeader('access-control-allow-origin')) {
$response = $response->withHeader('access-control-allow-origin', '*');
}
$eTag = md5((string) $response->getBody());
$response->setEtag($eTag);

View File

@ -184,6 +184,26 @@ class AuthenticatorTest extends ServiceProviderTest
$this->assertEquals('F00Bar', $user->api_key);
}
/**
* @covers \Engelsystem\Helpers\Authenticator::userByHeaders
*/
public function testUserByHeadersBearerTrimApiKey(): void
{
$this->initDatabase();
$request = new Request();
$request = $request->withAttribute('route-api-accessible', true);
$session = new Session(new MockArraySessionStorage());
$this->app->instance('request', $request);
$request = $request->withHeader('authorization', 'bearer F00Bar ');
$auth = new Authenticator($request, $session, new User());
User::factory()->create(['api_key' => 'F00Bar']);
$user = $auth->user();
$this->assertInstanceOf(User::class, $user);
$this->assertEquals('F00Bar', $user->api_key);
}
/**
* @covers \Engelsystem\Helpers\Authenticator::resetApiKey
*/

View File

@ -67,6 +67,7 @@ class ApiRouteHandlerTest extends TestCase
if ($isApi) {
$this->assertEquals('application/json', $apiResponse->getHeaderLine('content-type'));
$this->assertEquals('*', $apiResponse->getHeaderLine('access-control-allow-origin'));
$this->assertEquals('{"message":"response content"}', (string) $apiResponse->getBody());
$this->assertNotEmpty($apiResponse->getHeaderLine('Etag'));
} else {