Skip to content

Commit 626c062

Browse files
committed
adding files from abdoned fork
1 parent e60c7cd commit 626c062

12 files changed

+613
-0
lines changed

.gitignore

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
/vendor/*
2+
composer.phar
3+
.vscode/launch.json
4+
5+
.phpunit.result.cache
6+
7+
.phpunit.cache/

LICENSE

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2016 Flavien Beninca
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

composer.json

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
{
2+
"name": "rrd108/cakephp-cors",
3+
"description": "A CakePHP plugin for activate cors domain in your application",
4+
"type": "cakephp-plugin",
5+
"require": {
6+
"cakephp/cakephp": "^5.0",
7+
"psr/http-server-handler": "^1.0",
8+
"psr/http-server-middleware": "^1.0"
9+
},
10+
"require-dev": {
11+
"phpunit/phpunit": "^10.1"
12+
},
13+
"autoload": {
14+
"psr-4": {
15+
"Cors\\": "src"
16+
}
17+
},
18+
"autoload-dev": {
19+
"psr-4": {
20+
"Cors\\Test\\": "tests",
21+
"Cake\\Test\\": "./vendor/cakephp/cakephp/tests"
22+
}
23+
}
24+
}

config/bootstrap.php

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?php
2+
use Cake\Event\EventManager;
3+
use Cake\Core\Configure;
4+
use Cake\Routing\Middleware\RoutingMiddleware;
5+
use Cors\Routing\Middleware\CorsMiddleware;
6+
7+
/**
8+
* Configuration
9+
*/
10+
Configure::load('Cors.default', 'default');
11+
12+
$defaultConfig = (array) Configure::consume('Cors-default');
13+
$personnalConfig = (array) Configure::consume('Cors');
14+
$config = array_merge($defaultConfig, $personnalConfig);
15+
16+
Configure::write('Cors', $config);
17+
18+
if ($config['exceptionRenderer'] && Configure::read('Error.exceptionRenderer') != $config['exceptionRenderer']) {
19+
Configure::write('Error.baseExceptionRenderer', Configure::read('Error.exceptionRenderer'));
20+
Configure::write('Error.exceptionRenderer', $config['exceptionRenderer']);
21+
}
22+
23+
/**
24+
* Middleware
25+
*/
26+
EventManager::instance()->on('Server.buildMiddleware',
27+
function ($event, $middleware) {
28+
try {
29+
$middleware->insertBefore(RoutingMiddleware::class, new CorsMiddleware());
30+
} catch (\LogicException $exception) {
31+
$middleware->add(new CorsMiddleware());
32+
}
33+
}
34+
);

config/default.php

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?php
2+
return [
3+
'Cors-default' => [
4+
'AllowOrigin' => true,
5+
'AllowCredentials' => true,
6+
'AllowMethods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
7+
'AllowHeaders' => true,
8+
'ExposeHeaders' => false,
9+
'MaxAge' => 86400, // 1 day
10+
'exceptionRenderer' => 'Cors\Error\AppExceptionRenderer',
11+
]
12+
];

phpunit.xml.dist

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
colors="true"
4+
processIsolation="false"
5+
stopOnFailure="false"
6+
bootstrap="tests/bootstrap.php"
7+
cacheDirectory=".phpunit.cache"
8+
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.1/phpunit.xsd">
9+
<php>
10+
<ini name="memory_limit" value="-1"/>
11+
<ini name="apc.enable_cli" value="1"/>
12+
</php>
13+
14+
<testsuites>
15+
<testsuite name="tokenAuthenticator">
16+
<directory>tests/TestCase/</directory>
17+
</testsuite>
18+
</testsuites>
19+
20+
<extensions>
21+
<bootstrap class="Cake\TestSuite\Fixture\Extension\PHPUnitExtension"/>
22+
</extensions>
23+
24+
<source>
25+
<include>
26+
<directory suffix=".php">src/</directory>
27+
<directory suffix=".php">plugins/*/src/</directory>
28+
</include>
29+
</source>
30+
</phpunit>

src/Error/AppExceptionRenderer.php

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
namespace Cors\Error;
3+
4+
use Cake\Core\Configure;
5+
use Cake\Controller\Controller;
6+
use Cors\Routing\Middleware\CorsMiddleware;
7+
8+
function get_dynamic_parent() {
9+
return Configure::read('Error.baseExceptionRenderer');// return what you need
10+
}
11+
class_alias(get_dynamic_parent(), 'Cors\Error\BaseExceptionRenderer');
12+
13+
class AppExceptionRenderer extends BaseExceptionRenderer
14+
{
15+
/**
16+
* Returns the current controller.
17+
*
18+
* @return \Cake\Controller\Controller
19+
*/
20+
protected function _getController(): Controller
21+
{
22+
$controller = parent::_getController();
23+
$cors = new CorsMiddleware();
24+
$controller->response = $cors->addHeaders(
25+
$controller->getRequest(),
26+
$controller->getResponse()
27+
);
28+
return $controller;
29+
}
30+
}

src/Plugin.php

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?php
2+
namespace Cors;
3+
4+
use Cake\Core\BasePlugin;
5+
6+
class Plugin extends BasePlugin
7+
{
8+
}
+143
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
<?php
2+
namespace Cors\Routing\Middleware;
3+
4+
use Cake\Core\Configure;
5+
use Psr\Http\Message\ResponseInterface;
6+
use Psr\Http\Message\ServerRequestInterface;
7+
use Psr\Http\Server\MiddlewareInterface;
8+
use Psr\Http\Server\RequestHandlerInterface;
9+
use Cake\Http\Response;
10+
11+
class CorsMiddleware implements MiddlewareInterface
12+
{
13+
/**
14+
* @param ServerRequestInterface $request
15+
* @param RequestHandlerInterface $handler
16+
* @return ResponseInterface
17+
*/
18+
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
19+
{
20+
if (strtoupper($request->getMethod()) === 'OPTIONS') {
21+
if (!array_intersect($request->getHeader("Access-Control-Request-Method"), Configure::read('Cors.AllowMethods'))) {
22+
$response = new Response([
23+
'status' => 403,
24+
'body' => 'Method Forbidden'
25+
]);
26+
} else {
27+
$response = new Response([
28+
'status' => 200
29+
]);
30+
}
31+
} else {
32+
$response = $handler->handle($request);
33+
}
34+
35+
$response = $this->addHeaders($request, $response);
36+
37+
return $response;
38+
}
39+
40+
public function addHeaders(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
41+
{
42+
if ($request->getHeader('Origin')) {
43+
$response = $response
44+
->withHeader('Access-Control-Allow-Origin', $this->_allowOrigin($request))
45+
->withHeader('Access-Control-Allow-Credentials', $this->_allowCredentials())
46+
->withHeader('Access-Control-Max-Age', $this->_maxAge());
47+
48+
if (strtoupper($request->getMethod()) === 'OPTIONS') {
49+
$response = $response
50+
->withHeader('Access-Control-Expose-Headers', $this->_exposeHeaders())
51+
->withHeader('Access-Control-Allow-Headers', $this->_allowHeaders($request))
52+
->withHeader('Access-Control-Allow-Methods', $this->_allowMethods());
53+
}
54+
55+
}
56+
57+
return $response;
58+
}
59+
60+
61+
/**
62+
* @param \Psr\Http\Message\ServerRequestInterface $request
63+
* @return array|string
64+
*/
65+
private function _allowOrigin(ServerRequestInterface $request)
66+
{
67+
$allowOrigin = Configure::read('Cors.AllowOrigin');
68+
$origin = $request->getHeader('Origin');
69+
70+
if ($allowOrigin === true || $allowOrigin === '*') {
71+
return $origin;
72+
}
73+
74+
if (is_array($allowOrigin)) {
75+
$origin = (array) $origin;
76+
77+
foreach ($origin as $o) {
78+
if (in_array($o, $allowOrigin)) {
79+
return $origin;
80+
}
81+
}
82+
83+
return '';
84+
}
85+
86+
return (string)$allowOrigin;
87+
}
88+
89+
/**
90+
* @return String
91+
*/
92+
private function _allowCredentials(): String
93+
{
94+
return (Configure::read('Cors.AllowCredentials')) ? 'true' : 'false';
95+
}
96+
97+
/**
98+
* @return String
99+
*/
100+
private function _allowMethods(): String
101+
{
102+
return implode(', ', (array) Configure::read('Cors.AllowMethods'));
103+
}
104+
105+
/**
106+
* @param \Psr\Http\Message\ServerRequestInterface $request
107+
* @return String
108+
*/
109+
private function _allowHeaders(ServerRequestInterface $request): String
110+
{
111+
$allowHeaders = Configure::read('Cors.AllowHeaders');
112+
113+
if ($allowHeaders === true) {
114+
return $request->getHeaderLine('Access-Control-Request-Headers');
115+
}
116+
117+
return implode(', ', (array) $allowHeaders);
118+
}
119+
120+
/**
121+
* @return String
122+
*/
123+
private function _exposeHeaders(): String
124+
{
125+
$exposeHeaders = Configure::read('Cors.ExposeHeaders');
126+
127+
if (is_string($exposeHeaders) || is_array($exposeHeaders)) {
128+
return implode(', ', (array) $exposeHeaders);
129+
}
130+
131+
return '';
132+
}
133+
134+
/**
135+
* @return String
136+
*/
137+
private function _maxAge(): String
138+
{
139+
$maxAge = (string) Configure::read('Cors.MaxAge');
140+
141+
return ($maxAge) ?: '0';
142+
}
143+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
namespace Cors\Tests\TestCase\Controller;
3+
4+
use PHPUnit\Framework\TestCase;
5+
6+
class ErrorControllerTest extends TestCase
7+
{
8+
private $controller;
9+
10+
public function testIncomplete() {
11+
$this->markTestIncomplete('Fail with travis because ErrorController extends App\Controller\ErrorController');
12+
}
13+
14+
// public function setUp()
15+
// {
16+
// parent::setUp();
17+
// $request = new Request();
18+
// $response = new Response();
19+
// $this->controller = $this->getMockBuilder('Cors\Controller\ErrorController')
20+
// ->setConstructorArgs([$request, $response])
21+
// ->setMethods(null)
22+
// ->getMock();
23+
// }
24+
//
25+
// public function testInitializeLoadRequestHandler() {
26+
// $this->assertInstanceOf('Cake\Controller\Component\RequestHandlerComponent', $this->controller->RequestHandler);
27+
// }
28+
//
29+
// public function testBeforeRenderAllowAllOrigin() {
30+
// $event = new Event('Controller.startup', $this->controller);
31+
// $this->controller->beforeRender($event);
32+
// $responsesHeader = $this->controller->response->header();
33+
// $this->assertEquals('*', $responsesHeader['Access-Control-Allow-Origin']);
34+
// }
35+
}

0 commit comments

Comments
 (0)