Add an interceptor for CORS OPTIONS preflighting.
[hoplite.git] / http / cors_options_interceptor.php
1 <?php
2 // Hoplite
3 // Copyright (c) 2017 Blue Static
4 //
5 // This program is free software: you can redistribute it and/or modify it
6 // under the terms of the GNU General Public License as published by the Free
7 // Software Foundation, either version 3 of the License, or any later version.
8 //
9 // This program is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 // more details.
13 //
14 // You should have received a copy of the GNU General Public License along with
15 // this program. If not, see <http://www.gnu.org/licenses/>.
16
17 namespace hoplite\http;
18
19 require_once HOPLITE_ROOT . '/http/interceptor.php';
20 require_once HOPLITE_ROOT . '/http/response_code.php';
21
22 class CorsOptionsInterceptor implements Interceptor
23 {
24 private $allowed_origins = [];
25
26 public function __construct($allowed_origins = []) {
27 $this->allowed_origins = $allowed_origins;
28 }
29
30 public function DoIntercept(FrontController $controller,
31 Action $action = NULL,
32 Request $request,
33 Response $response)
34 {
35 if ($action === NULL) {
36 return;
37 }
38
39 // If a CORS pre-flight is in process, interrupt the action flow and
40 // permit the request.
41 if ($request->http_method == 'OPTIONS' &&
42 isset($request->data['_SERVER']['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
43 if (in_array($request->data['_SERVER']['HTTP_ORIGIN'], $this->allowed_origins)) {
44 $controller->SendResponseCode(ResponseCode::OK);
45 } else {
46 $controller->SendResponseCode(ResponseCode::FORBIDDEN);
47 return;
48 }
49 }
50 }
51 }