Commit f8892298 authored by Karamel's avatar Karamel
Browse files

Add more CORS stuff.

parent f5b7304c
<?php
use Pasteque\Server\System\API\APICaller;
/** Middleware to accept/reject CORS requests. */
$corsMiddleware = function($request, $response, $next) {
$ptApp = $this->get('settings')['ptApp'];
// Pass the call to the regular route
$response = $next($request, $response);
if (!APICaller::isAllowedOrigin($request->getHeader('Origin'),
$ptApp->getAllowedOrigin())) {
return $response->withResponse(403, 'Forbidden');
}
// Set CORS headers
$headers = APICaller::getCORSHeaders($request->getHeader('Origin'),
$ptApp->getAllowedOrigin());
foreach ($headers as $header => $value) {
$response = $response->withHeader($header, $value);
}
return $response;
};
......@@ -22,7 +22,8 @@ $loginMiddleware = function($request, $response, $next) {
}
$mustLogin = ('fiscal/' !== substr($request->getUri()->getPath(), 0, 7)
&& 'api/login' !== substr($request->getUri()->getPath(), 0, 9));
&& 'api/login' !== substr($request->getUri()->getPath(), 0, 9)
&& !$request->isOptions());
if ($userId === null && $mustLogin) {
// Reject the call because not authenticated.
......
......@@ -44,9 +44,11 @@ $app = new \Slim\App([
$app->add(new \Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware($app));
// Add login middleware
// Add middlewares
include('../middlewares/login_middleware.php');
$app->add($loginMiddleware);
include('../middlewares/cors_middleware.php');
$app->add($corsMiddleware);
// Default route
$app->get('/', function (Request $request, Response $response) {
......@@ -76,5 +78,6 @@ include('../routes/user.php');
include('../routes/version.php');
include('../routes/fiscal.php');
// Run
$app->run();
......@@ -20,6 +20,8 @@
namespace Pasteque\Server\System\API;
use \Pasteque\Server\System\Login;
/** Utility class to call API methods. */
class APICaller {
......@@ -103,8 +105,10 @@ class APICaller {
public static function getCORSHeaders($origin, $allowedOrigins, $maxAge = 86400) {
$headers = [];
$headers['Access-Control-Allow-Origin'] = $origin;
$headers['Access-Control-Allow-Credentials'] = false; // Turned off for now, api should embed token in requests.
$headers['Access-Control-Allow-Credentials'] = false;
$headers['Access-Control-Max-Age'] = $maxAge;
$headers['Access-Control-Expose-Headers'] = Login::TOKEN_HEADER;
$headers['Access-Control-Allow-Headers'] = Login::TOKEN_HEADER;
if (is_array($allowedOrigins)) { $headers['Vary'] = 'Origin'; }
return $headers;
}
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment