View source
<?php
namespace Drupal\Tests\farm_api\Functional;
use Drupal\consumers\Entity\Consumer;
use Drupal\Core\Url;
use Drupal\Tests\farm_test\Functional\FarmBrowserTestBase;
use Drupal\Tests\jsonapi\Functional\JsonApiRequestTestTrait;
use GuzzleHttp\RequestOptions;
use Psr\Http\Message\ResponseInterface;
class CorsResponseEventSubscriberTest extends FarmBrowserTestBase {
use JsonApiRequestTestTrait;
protected $consumer;
protected static $modules = [
'farm_api',
];
protected function setUp() : void {
parent::setUp();
$this->consumer = Consumer::create([
'label' => $this
->getRandomGenerator()
->name(),
]);
$this->consumer
->save();
}
public function testCorsResponseHeaders() {
$request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
$uri = "base://api";
$response = $this
->request('OPTIONS', Url::fromUri($uri), $request_options);
$this
->assertSame(200, $response
->getStatusCode());
$this
->assertValidCorsHeaders($response);
$farmos_app_origin = 'https://farmOS.app';
$request_options[RequestOptions::HEADERS]['Origin'] = $farmos_app_origin;
$response = $this
->request('OPTIONS', Url::fromUri($uri), $request_options);
$this
->assertSame(200, $response
->getStatusCode());
$this
->assertValidCorsHeaders($response);
$this->consumer
->set('allowed_origins', [
$farmos_app_origin,
]);
$this->consumer
->save();
$response = $this
->request('OPTIONS', Url::fromUri($uri), $request_options);
$this
->assertSame(200, $response
->getStatusCode());
$this
->assertValidCorsHeaders($response, $farmos_app_origin);
$custom_app_origin = 'https://customApp.com';
$this->consumer
->set('allowed_origins', [
$farmos_app_origin,
$custom_app_origin,
]);
$this->consumer
->save();
$request_options[RequestOptions::HEADERS]['Origin'] = $farmos_app_origin;
$response = $this
->request('OPTIONS', Url::fromUri($uri), $request_options);
$this
->assertSame(200, $response
->getStatusCode());
$this
->assertValidCorsHeaders($response, $farmos_app_origin);
$request_options[RequestOptions::HEADERS]['Origin'] = $custom_app_origin;
$response = $this
->request('OPTIONS', Url::fromUri($uri), $request_options);
$this
->assertSame(200, $response
->getStatusCode());
$this
->assertValidCorsHeaders($response, $custom_app_origin);
}
protected function assertValidCorsHeaders(ResponseInterface $response, string $origin = NULL) {
$cors_headers = [
'Access-Control-Allow-Origin' => $origin,
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Allow-Headers' => 'Content-Type,Content-Disposition,Authorization,X-CSRF-Token',
'Access-Control-Allow-Methods' => 'GET,POST,PUT,DELETE,HEAD,OPTIONS',
'Vary' => 'Origin',
];
$needs_cors = !empty($origin);
foreach ($cors_headers as $header => $value) {
$this
->assertEquals($needs_cors, $response
->hasHeader($header), 'Response has correct CORS headers.');
if ($needs_cors) {
$this
->assertEquals($value, $response
->getHeader($header)[0], 'Response has correct header value.');
}
}
}
}