Skip to content

Commit

Permalink
Merge pull request #181 from akirk/fix-cors-header-sending
Browse files Browse the repository at this point in the history
Improve targeting of CORS headers
  • Loading branch information
akirk authored Oct 9, 2024
2 parents 195121c + 18bf187 commit 505f67b
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions includes/class-mastodon-api.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ public function register_hooks() {
add_action( 'wp_loaded', array( $this, 'rewrite_rules' ) );
add_action( 'query_vars', array( $this, 'query_vars' ) );
add_action( 'rest_api_init', array( $this, 'add_rest_routes' ) );
add_filter( 'rest_pre_serve_request', array( $this, 'allow_cors' ), 10, 0 );
add_filter( 'rest_post_dispatch', array( $this, 'send_http_links' ), 10, 3 );
add_filter( 'rest_pre_echo_response', array( $this, 'reformat_error_response' ), 10, 3 );
add_filter( 'template_include', array( $this, 'log_404s' ) );
Expand All @@ -85,14 +84,18 @@ public function register_hooks() {
add_filter( 'mastodon_api_in_reply_to_id', array( self::class, 'maybe_get_remapped_reblog_id' ), 15 );
}

public function allow_cors() {
/**
* Allow the Mastodon API to be accessed via CORS.
*
* @param WP_REST_Request $request Request used to generate the response.
*/
public function allow_cors( $request ) {
header( 'Access-Control-Allow-Origin: *' );
header( 'Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS' );
header( 'Access-Control-Allow-Headers: content-type, authorization' );
header( 'Access-Control-Allow-Credentials: true' );
if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) { // phpcs:ignore
if ( 'OPTIONS' === $request->get_method() ) {
header( 'Access-Control-Allow-Origin: *', true, 204 );
exit;
}
}

Expand Down Expand Up @@ -1661,7 +1664,7 @@ public function required_scope( $scopes, $also_public = false ) {
}

public function public_api_permission( $request ) {
$this->allow_cors();
$this->allow_cors( $request );
// Optionally log in.
$token = $this->oauth->get_token();
if ( ! $token ) {
Expand Down Expand Up @@ -1755,7 +1758,7 @@ public function api_apps( $request ) {
}

public function logged_in_permission( $request ) {
$this->allow_cors();
$this->allow_cors( $request );
$token = $this->oauth->get_token();
if ( ! $token ) {
return is_user_logged_in();
Expand All @@ -1768,7 +1771,7 @@ public function logged_in_permission( $request ) {
}

public function have_token_permission( $request ) {
$this->allow_cors();
$this->allow_cors( $request );
$token = $this->oauth->get_token();
if ( ! $token ) {
return is_user_logged_in();
Expand Down

0 comments on commit 505f67b

Please sign in to comment.