From cb5eb45fab44da6c68efff21572e18565874035e Mon Sep 17 00:00:00 2001 From: Adam Silverstein Date: Fri, 17 Feb 2023 08:08:19 +0000 Subject: [PATCH] Login and Registration: prevent registering with username that matches previous user email. When registering a new user, check that no existing user has an email matching the username. Prevents a login name collision when one user registers with the email address user@test.com and a second user tries to register with the username user@test.com. Props buutqn, dunhakdis, roytanck, ajayver. Fixes #57394. git-svn-id: https://develop.svn.wordpress.org/trunk@55358 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/user.php | 9 ++++++++- tests/phpunit/tests/user.php | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/user.php b/src/wp-includes/user.php index 867df81e16..e0cfae9188 100644 --- a/src/wp-includes/user.php +++ b/src/wp-includes/user.php @@ -2123,10 +2123,16 @@ function wp_insert_user( $userdata ) { return new WP_Error( 'user_login_too_long', __( 'Username may not be longer than 60 characters.' ) ); } + // Username must be unique. if ( ! $update && username_exists( $user_login ) ) { return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) ); } + // Username must not match an existing user email. + if ( email_exists( $user_login ) ) { + return new WP_Error( 'existing_user_login_as_email', __( 'Sorry, that username is not available.' ) ); + } + /** * Filters the list of disallowed usernames. * @@ -3340,7 +3346,8 @@ function register_new_user( $user_login, $user_email ) { $sanitized_user_login = ''; } elseif ( username_exists( $sanitized_user_login ) ) { $errors->add( 'username_exists', __( 'Error: This username is already registered. Please choose another one.' ) ); - + } elseif ( email_exists( $sanitized_user_login ) ) { + $errors->add( 'username_exists_as_email', __( 'Error: This username is not available. Please choose another one.' ) ); } else { /** This filter is documented in wp-includes/user.php */ $illegal_user_logins = (array) apply_filters( 'illegal_user_logins', array() ); diff --git a/tests/phpunit/tests/user.php b/tests/phpunit/tests/user.php index 7157a00cfa..03a5a11872 100644 --- a/tests/phpunit/tests/user.php +++ b/tests/phpunit/tests/user.php @@ -934,6 +934,24 @@ class Tests_User extends WP_UnitTestCase { $this->assertSame( $expected, $user->user_nicename ); } + /** + * @ticket 57394 + */ + public function test_wp_insert_user_should_reject_username_that_matches_existing_user_email() { + $existing_email = get_option( 'admin_email' ); + $username = wp_insert_user( + array( + 'user_login' => $existing_email, + 'user_email' => 'whatever@example.com', + 'user_pass' => 'whatever', + 'user_nicename' => 'whatever', + ) + ); + + $this->assertWPError( $username ); + $this->assertSame( 'existing_user_login_as_email', $username->get_error_code() ); + } + /** * @ticket 33793 */