Multisite: Introduce a can_add_user_to_blog filter to prevent adding a user to a site.

Under certain circumstances, it can be necessary that a user should not be added to a site, beyond the restrictions that WordPress core applies. With the new `can_add_user_to_blog` filter, plugin developers can run custom checks and return an error in case of a failure, that will prevent the user from being added.

The user-facing parts and the REST API route that interact with `add_user_to_blog()` have been adjusted accordingly to provide appropriate error feedback when a user could not be added to a site. Furthermore, two existing error feedback messages in the site admin's "New User" screen have been adjusted to properly show inside an error notice instead of a success notice.

Props jmdodd.
Fixes #41101.


git-svn-id: https://develop.svn.wordpress.org/trunk@41225 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
flixos90
2017-08-03 21:40:02 +00:00
parent 814e1f5530
commit 0dc1e0633b
6 changed files with 146 additions and 33 deletions

View File

@@ -1020,6 +1020,30 @@ class WP_Test_REST_Users_Controller extends WP_Test_REST_Controller_Testcase {
$this->assertFalse( $user_is_member );
}
/**
* @ticket 41101
* @group ms-required
*/
public function test_create_new_network_user_with_add_user_to_blog_failure() {
$this->allow_user_to_manage_multisite();
$params = array(
'username' => 'testuser123',
'password' => 'testpassword',
'email' => 'test@example.com',
'name' => 'Test User 123',
'roles' => array( 'editor' ),
);
add_filter( 'can_add_user_to_blog', '__return_false' );
$request = new WP_REST_Request( 'POST', '/wp/v2/users' );
$request->add_header( 'content-type', 'application/x-www-form-urlencoded' );
$request->set_body_params( $params );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'user_cannot_be_added', $response );
}
/**
* @group ms-required
*/

View File

@@ -397,6 +397,32 @@ class Tests_Multisite_User extends WP_UnitTestCase {
$this->assertWPError( $result );
}
/**
* @ticket 41101
*/
public function test_should_fail_can_add_user_to_blog_filter() {
$site_id = self::factory()->blog->create();
$user_id = self::factory()->user->create();
add_filter( 'can_add_user_to_blog', '__return_false' );
$result = add_user_to_blog( $site_id, $user_id, 'subscriber' );
$this->assertWPError( $result );
}
/**
* @ticket 41101
*/
public function test_should_succeed_can_add_user_to_blog_filter() {
$site_id = self::factory()->blog->create();
$user_id = self::factory()->user->create();
add_filter( 'can_add_user_to_blog', '__return_true' );
$result = add_user_to_blog( $site_id, $user_id, 'subscriber' );
$this->assertTrue( $result );
}
/**
* @ticket 23016
*/