[wp-trac] [WordPress Trac] #28020: get_userdata and wp_get_current_user do not share WP_User instance
WordPress Trac
noreply at wordpress.org
Sat Aug 3 14:13:12 UTC 2019
#28020: get_userdata and wp_get_current_user do not share WP_User instance
--------------------------------------+---------------------
Reporter: rmccue | Owner: (none)
Type: defect (bug) | Status: new
Priority: normal | Milestone:
Component: Users | Version:
Severity: normal | Resolution:
Keywords: has-patch has-unit-tests | Focuses:
--------------------------------------+---------------------
Changes (by donmhico):
* keywords: needs-patch => has-patch has-unit-tests
Comment:
So here's how I approached the problem - see my attached patch
[https://core.trac.wordpress.org/attachment/ticket/28020/28020.diff
28020.diff].
1. - Check if what is being fetched using the function `get_user_by()` is
the same as the current user. If it is, then return the current user
object using `wp_get_current_user()`.
{{{#!php
if ( get_current_user_id() == $userdata->ID ) {
return wp_get_current_user();
}
}}}
However, upon doing this and running the full test suite, bunch of failed
tests emerged.
2. After debugging, I found out that the failed tests' origin is from the
function `clean_user_cache()`. The code from no. 1 above returns the
current user object instead of a new user object with updated data. So
functions that transform the current state of a user object such as
`wp_set_password()` fails if the user in context is the current user.
To solve this, the current user object should be re-setup / initialized if
it is pass to `clean_user_cache()`. Hence the code.
{{{#!php
if ( get_current_user_id() == $user->ID ) {
wp_set_current_user( $user->ID, '', true );
}
}}}
3. Lastly, I added a new param - `$force` with default value of `false` -
in the function `wp_set_current_user()`. It is because
`wp_set_current_user()` returns the same current user object if the passed
`$id` is the same as the current user. At first I thought of using
{{{#!php
wp_set_current_user( 0 )
wp_set_current_user( $current_user_id )
}}}
The code above will first "remove" the current user effectively bypassing
the check. However, I believe it's not good to go around like this.
Another possible solution was to create another function which basically
do the same as `wp_set_current_user()` just without the check so it will
always re-setup the current user object. But then again, creating almost
duplicate functions are just ticking bombs.
So ultimately, I settled on creating a new param `$force` and added it to
the check.
I run the full test suite and it looks good.
{{{#!php
OK, but incomplete, skipped, or risky tests!
Tests: 9640, Assertions: 73874, Skipped: 39
}}}
Any thoughts and suggestions are greatly appreciated.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/28020#comment:3>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list