Skip to content

Commit

Permalink
Handle OPTIONS requests in one place.
Browse files Browse the repository at this point in the history
  • Loading branch information
kohler committed Feb 8, 2024
1 parent 7aca4d9 commit 61220b8
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
6 changes: 6 additions & 0 deletions index.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ function handle_request($nav) {

$nav = Navigation::get();

// handle OPTIONS requests, including CORS preflight
if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
include("src/pages/p_api.php");
API_Page::go_options($nav);
}

// handle `/u/USERINDEX/`
if ($nav->page === "u") {
$unum = $nav->path_component(0);
Expand Down
30 changes: 30 additions & 0 deletions src/pages/p_api.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,36 @@ static function export_messages(JsonResult $jr) {
return $ml;
}

static function go_options(NavigationState $nav) {
if ($nav->page === "u"
&& ($unum = $nav->path_component(0)) !== false
&& ctype_digit($unum)) {
$nav->shift_path_components(2);
}
$ok = true;
if (($m = $_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"] ?? null)) {
if ($nav->page === "api") {
$origin = $_SERVER["HTTP_ORIGIN"] ?? "*";
header("Access-Control-Allow-Origin: {$origin}");
if (($hdrs = $_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"] ?? null)) {
header("Access-Control-Allow-Headers: {$hdrs}");
}
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: OPTIONS, GET, HEAD, POST");
header("Access-Control-Max-Age: 86400");
} else if (in_array($nav->page, ["cacheable", "scorechart", "images", "scripts", "stylesheets"])) {
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: OPTIONS, GET, HEAD");
header("Access-Control-Max-Age: 86400");
} else {
$ok = false;
}
} else {
header("Allow: OPTIONS, GET, HEAD, POST"); // XXX other methods?
}
http_response_code($ok ? 200 : 403);
exit;
}

/** @param NavigationState $nav
* @param Conf $conf */
Expand Down

0 comments on commit 61220b8

Please sign in to comment.