diff --git a/lib/endpoints/class-wp-rest-comments-controller.php b/lib/endpoints/class-wp-rest-comments-controller.php index 5d8606fb8d..fc7543dc21 100644 --- a/lib/endpoints/class-wp-rest-comments-controller.php +++ b/lib/endpoints/class-wp-rest-comments-controller.php @@ -411,6 +411,10 @@ public function get_item_permissions_check( $request ) { */ public function create_item_permissions_check( $request ) { + if ( ! is_user_logged_in() && get_option( 'comment_registration' ) ) { + return new WP_Error( 'rest_comment_login_required', __( 'Sorry, you must be logged in to comment.' ), array( 'status' => 401 ) ); + } + // Limit who can set comment `author`, `karma` or `status` to anything other than the default. if ( isset( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( 'moderate_comments' ) ) { return new WP_Error( 'rest_comment_invalid_author', __( 'Comment author invalid.' ), array( 'status' => rest_authorization_required_code() ) ); diff --git a/tests/test-rest-comments-controller.php b/tests/test-rest-comments-controller.php index 20c37beece..223bb152d8 100644 --- a/tests/test-rest-comments-controller.php +++ b/tests/test-rest-comments-controller.php @@ -587,6 +587,17 @@ public function test_create_comment_closed() { $this->assertEquals( 403, $response->get_status() ); } + public function test_create_comment_require_login() { + wp_set_current_user( 0 ); + update_option( 'comment_registration', 1 ); + $request = new WP_REST_Request( 'POST', '/wp/v2/comments' ); + $request->set_param( 'post', $this->post_id ); + $response = $this->server->dispatch( $request ); + $this->assertEquals( 401, $response->get_status() ); + $data = $response->get_data(); + $this->assertEquals( 'rest_comment_login_required', $data['code'] ); + } + public function test_create_comment_two_times() { $this->markTestSkipped( 'Needs to be revisited after wp_die handling is added' );