Skip to content

Commit

Permalink
Check $user type to avoid fatal error.
Browse files Browse the repository at this point in the history
There are some rare cases where `rest_preload_api_request(Array, '/wp/v2/users/me...')` on a new user results in the `get_userdata()` calls in `\WordPressdotorg\Two_Factor\register_user_fields` returning `false`. It's not easy to reproduce, so handling it gracefully is good enough as a solution.

See https://wordpress.slack.com/archives/G02QB4059/p1675309698126049 and the 3 that followed it.
  • Loading branch information
iandunn committed Feb 3, 2023
1 parent 2640734 commit 2948682
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
7 changes: 7 additions & 0 deletions tests/test-wporg-two-factor.php
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,13 @@ public function data_user_requires_2fa() : array {
);
}

/**
* @covers WordPressdotorg\Two_Factor\user_requires_2fa
*/
public function test_invalid_user_doesnt_require_2fa() : void {
$this->assertFalse( user_requires_2fa( false ) );
}

/**
* @covers WordPressdotorg\Two_Factor\redirect_to_2fa_settings
*/
Expand Down
9 changes: 8 additions & 1 deletion wporg-two-factor.php
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,17 @@ function remove_capabilities_until_2fa_enabled( array $allcaps, array $caps, arr

/**
* Check if the user has enough elevated privileges to require 2FA.
*
* @param WP_User $user
*/
function user_requires_2fa( WP_User $user ) : bool {
function user_requires_2fa( $user ) : bool {
global $trusted_deputies, $wcorg_subroles;

// This shouldn't happen, but there've been a few times where it has inexplicably.
if ( ! $user instanceof WP_User ) {
return false;
}

// @codeCoverageIgnoreStart
if ( ! array_key_exists( 'phpunit_version', $GLOBALS ) ) {
// 2FA is opt-in during beta testing.
Expand Down

0 comments on commit 2948682

Please sign in to comment.