From 93e85e14f3b30d033324277751a9ba4c655b4399 Mon Sep 17 00:00:00 2001 From: Robert Sesek Date: Sun, 19 Nov 2017 00:00:08 -0500 Subject: [PATCH] Add an interceptor for CORS OPTIONS preflighting. --- http/cors_options_interceptor.php | 51 +++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 http/cors_options_interceptor.php diff --git a/http/cors_options_interceptor.php b/http/cors_options_interceptor.php new file mode 100644 index 0000000..6b3d899 --- /dev/null +++ b/http/cors_options_interceptor.php @@ -0,0 +1,51 @@ +. + +namespace hoplite\http; + +require_once HOPLITE_ROOT . '/http/interceptor.php'; +require_once HOPLITE_ROOT . '/http/response_code.php'; + +class CorsOptionsInterceptor implements Interceptor +{ + private $allowed_origins = []; + + public function __construct($allowed_origins = []) { + $this->allowed_origins = $allowed_origins; + } + + public function DoIntercept(FrontController $controller, + Action $action = NULL, + Request $request, + Response $response) + { + if ($action === NULL) { + return; + } + + // If a CORS pre-flight is in process, interrupt the action flow and + // permit the request. + if ($request->http_method == 'OPTIONS' && + isset($request->data['_SERVER']['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) { + if (in_array($request->data['_SERVER']['HTTP_ORIGIN'], $this->allowed_origins)) { + $controller->SendResponseCode(ResponseCode::OK); + } else { + $controller->SendResponseCode(ResponseCode::FORBIDDEN); + return; + } + } + } +} -- 2.22.5