settings = Plugin::get_settings( 'users' );
add_filter( 'adminease_settings_fields', [ $this, 'adminease_settings_fields' ] );
if( empty( $this->settings['user_switch_enabled'] ) ) {
return;
}
add_filter( 'user_row_actions', [ $this, 'user_row_actions' ], 10, 2 );
add_action( 'admin_post_' . self::ACTION_SWITCH, [ $this, 'handle_switch' ] );
add_action( 'admin_post_' . self::ACTION_BACK, [ $this, 'handle_switch_back' ] );
add_action( 'admin_bar_menu', [ $this, 'admin_bar_menu' ], 8 );
add_action( 'wp_head', [ $this, 'print_mobile_style' ] );
add_action( 'admin_head', [ $this, 'print_mobile_style' ] );
add_action( 'wp_footer', [ $this, 'render_fallback_link' ] );
add_action( 'admin_footer', [ $this, 'render_fallback_link' ] );
add_action( 'wp_logout', [ $this, 'clear_cookie' ] );
}
/**
* Adds the switch to the Users tab.
*
* @param array $fields The settings fields keyed by tab.
*
* @return array The modified settings fields.
*/
public function adminease_settings_fields( array $fields ): array {
$fields['users']['fields'][] = [
'type' => 'switch',
'id' => 'user-switch-enabled',
'name' => 'adminease[users][user_switch_enabled]',
'value' => $this->settings['user_switch_enabled'] ?? '',
'label_class' => 'pwp-switch',
'input_class' => 'pwp-field-input',
'label' => __( 'User Switch', 'adminease' ),
'risk' => 'careful',
'breaks' => __( 'Administrators can see the site as any user they can edit. Switches are written to the Audit Log when it is on.', 'adminease' ),
'description' => __( 'Adds a "Switch to" link to each row of the Users list. Click it to see the site exactly as that user does, then use "Switch back" in the admin bar to return to your own account. Useful to check what a customer, author or editor can see and do.', 'adminease' ),
];
return $fields;
}
/**
* Tells whether the current user may switch to a user.
*
* @param int $target_id The user to switch to.
*
* @return bool
*/
public static function can_switch_to( int $target_id ): bool {
$current_id = get_current_user_id();
if( !$current_id || $target_id < 1 || $target_id === $current_id ) {
return false;
}
if( !get_userdata( $target_id ) || !current_user_can( 'edit_user', $target_id ) ) {
return false;
}
if( self::get_original_user_id() ) {
return false;
}
/**
* Filters whether the current user may switch to the target user.
*
* @param bool $allowed Whether the switch is allowed.
* @param int $from_id The user who wants to switch.
* @param int $target_id The user to switch to.
*/
return (bool) apply_filters( 'adminease_user_switch_can_switch', true, $current_id, $target_id );
}
/**
* Adds the "Switch to" link to a row of the Users list.
*
* @param array $actions The row actions.
* @param \WP_User $user The user of the row.
*
* @return array
*/
public function user_row_actions( array $actions, $user ): array {
if( !( $user instanceof \WP_User ) || !self::can_switch_to( (int) $user->ID ) ) {
return $actions;
}
$url = wp_nonce_url(
add_query_arg(
[
'action' => self::ACTION_SWITCH,
'user_id' => (int) $user->ID,
],
admin_url( 'admin-post.php' )
),
self::ACTION_SWITCH . '_' . (int) $user->ID
);
$actions['adminease_user_switch'] = '' . esc_html__( 'Switch to', 'adminease' ) . '';
return $actions;
}
/**
* Switches to the user in the request.
*
* @return void
*/
public function handle_switch(): void {
$target_id = isset( $_GET['user_id'] ) ? absint( wp_unslash( $_GET['user_id'] ) ) : 0;
check_admin_referer( self::ACTION_SWITCH . '_' . $target_id );
if( !self::can_switch_to( $target_id ) ) {
wp_die( esc_html__( 'You are not allowed to switch to this user.', 'adminease' ), '', [ 'response' => 403, 'back_link' => true ] );
}
$from = wp_get_current_user();
$to = get_userdata( $target_id );
$this->log( 'user_switched', $to, $from );
$expiration = time() + (int) apply_filters( 'auth_cookie_expiration', 2 * DAY_IN_SECONDS, $target_id, false );
$target_token = \WP_Session_Tokens::get_instance( $target_id )->create( $expiration );
$this->set_cookie( (int) $from->ID, $target_id, $expiration, (string) wp_get_session_token(), $target_token );
wp_set_auth_cookie( $target_id, false, '', $target_token );
wp_set_current_user( $target_id );
/**
* Fires after the current user switched to another user.
*
* @param int $from_id The user who switched.
* @param int $target_id The user switched to.
*/
do_action( 'adminease_user_switch_after', (int) $from->ID, $target_id );
$destination = user_can( $target_id, 'read' ) ? admin_url() : home_url( '/' );
wp_safe_redirect( $destination );
exit;
}
/**
* Switches back to the user who started the switch.
*
* @return void
*/
public function handle_switch_back(): void {
check_admin_referer( self::ACTION_BACK );
$switch = self::read_cookie();
$original_id = $switch ? $switch['original_id'] : 0;
if( !$original_id ) {
wp_safe_redirect( home_url( '/' ) );
exit;
}
$original = get_userdata( $original_id );
if( !$original ) {
$this->clear_cookie();
wp_die( esc_html__( 'The original user no longer exists.', 'adminease' ), '', [ 'response' => 403 ] );
}
$switched_from = wp_get_current_user();
$token = wp_get_session_token();
$this->log( 'user_switched_back', $original, $switched_from );
if( !\WP_Session_Tokens::get_instance( $original_id )->verify( $switch['original_token'] ) ) {
$this->clear_cookie();
wp_logout();
wp_safe_redirect( wp_login_url() );
exit;
}
wp_set_auth_cookie( $original_id, false, '', $switch['original_token'] );
wp_set_current_user( $original_id );
if( $token ) {
\WP_Session_Tokens::get_instance( (int) $switched_from->ID )->destroy( $token );
}
$this->clear_cookie();
wp_safe_redirect( admin_url( 'users.php' ) );
exit;
}
/**
* Adds the "Switch back" link to the admin bar while a switch is active.
*
* @param \WP_Admin_Bar $wp_admin_bar The admin bar.
*
* @return void
*/
public function admin_bar_menu( $wp_admin_bar ): void {
$original_id = self::get_original_user_id();
$original = $original_id ? get_userdata( $original_id ) : false;
if( !$original ) {
return;
}
$wp_admin_bar->add_node( [
'id' => 'adminease-user-switch-back',
'parent' => 'top-secondary',
'title' => esc_html( sprintf(
/* translators: %s: display name of the user to return to. */
__( 'Switch back to %s', 'adminease' ),
$original->display_name
) ),
'href' => wp_nonce_url( add_query_arg( 'action', self::ACTION_BACK, admin_url( 'admin-post.php' ) ), self::ACTION_BACK ),
'meta' => [ 'class' => 'adminease-user-switch-back' ],
] );
}
/**
* Keeps the "Switch back" link visible in the admin bar on narrow screens, where core hides
* every top-level item that is not on its short list.
*
* @return void
*/
public function print_mobile_style(): void {
if( !self::get_original_user_id() || !is_admin_bar_showing() ) {
return;
}
echo '' . "\n";
}
/**
* Prints a "Switch back" link when the admin bar is not showing for the switched user
* (WooCommerce customers, Hide Admin Bar, "Show Toolbar" off), so there is always a way back.
*
* @return void
*/
public function render_fallback_link(): void {
$original_id = self::get_original_user_id();
$original = $original_id ? get_userdata( $original_id ) : false;
if( !$original || is_admin_bar_showing() ) {
return;
}
$url = wp_nonce_url( add_query_arg( 'action', self::ACTION_BACK, admin_url( 'admin-post.php' ) ), self::ACTION_BACK );
printf(
'%2$s',
esc_url( $url ),
/* translators: %s: display name of the user to return to. */
esc_html( sprintf( __( 'Switch back to %s', 'adminease' ), $original->display_name ) ),
is_rtl() ? 'right' : 'left'
);
}
/**
* Gets the user who started the active switch, when the browser carries a valid cookie.
* The cookie only counts while the browser is logged in as the user and the session it was made for.
*
* @return int The original user ID, or 0 when no switch is active.
*/
public static function get_original_user_id(): int {
$switch = self::read_cookie();
return $switch ? $switch['original_id'] : 0;
}
/**
* Reads and checks the switch cookie.
*
* @return array{original_id:int,original_token:string}|null Null when there is no valid switch.
*/
private static function read_cookie(): ?array {
if( empty( $_COOKIE[ self::COOKIE ] ) || !is_user_logged_in() ) {
return null;
}
$parts = explode( '|', (string) wp_unslash( $_COOKIE[ self::COOKIE ] ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Compared against a signed value below.
if( 6 !== count( $parts ) ) {
return null;
}
$original_id = (int) $parts[0];
$target_id = (int) $parts[1];
$expires = (int) $parts[2];
$original_token = (string) $parts[3];
$target_hash = (string) $parts[4];
if( $expires < time() || $target_id !== get_current_user_id() || $original_id < 1 ) {
return null;
}
if( !hash_equals( $target_hash, wp_hash( (string) wp_get_session_token() ) ) ) {
return null;
}
if( !hash_equals( self::sign( $original_id, $target_id, $expires, $original_token, $target_hash ), (string) $parts[5] ) ) {
return null;
}
return [
'original_id' => $original_id,
'original_token' => $original_token,
];
}
/**
* Signs a switch so the cookie cannot be forged or reused for another user.
*
* @param int $original_id The user who started the switch.
* @param int $target_id The user switched to.
* @param int $expires Unix time the switch stops counting.
* @param string $original_token Session token of the original user.
* @param string $target_hash Hash of the switched user's session token.
*
* @return string
*/
private static function sign( int $original_id, int $target_id, int $expires, string $original_token, string $target_hash ): string {
return hash_hmac( 'sha256', 'adminease_user_switch|' . $original_id . '|' . $target_id . '|' . $expires . '|' . $original_token . '|' . $target_hash, wp_salt( 'auth' ) );
}
/**
* Sets the cookie that remembers who started the switch.
*
* @param int $original_id The user who started the switch.
* @param int $target_id The user switched to.
* @param int $expires Unix time the switch stops counting.
* @param string $original_token Session token of the original user.
* @param string $target_token Session token of the switched login.
*
* @return void
*/
private function set_cookie( int $original_id, int $target_id, int $expires, string $original_token, string $target_token ): void {
$target_hash = wp_hash( $target_token );
$value = $original_id . '|' . $target_id . '|' . $expires . '|' . $original_token . '|' . $target_hash . '|' . self::sign( $original_id, $target_id, $expires, $original_token, $target_hash );
setcookie( self::COOKIE, $value, [
'expires' => 0,
'path' => COOKIEPATH,
'domain' => COOKIE_DOMAIN,
'secure' => is_ssl(),
'httponly' => true,
'samesite' => 'Lax',
] );
$_COOKIE[ self::COOKIE ] = $value;
}
/**
* Removes the switch cookie.
*
* @return void
*/
public function clear_cookie(): void {
if( !headers_sent() ) {
setcookie( self::COOKIE, '', [
'expires' => time() - YEAR_IN_SECONDS,
'path' => COOKIEPATH,
'domain' => COOKIE_DOMAIN,
'secure' => is_ssl(),
'httponly' => true,
'samesite' => 'Lax',
] );
}
unset( $_COOKIE[ self::COOKIE ] );
}
/**
* Writes a switch to the Audit Log, when it is on.
*
* @param string $action Either user_switched or user_switched_back.
* @param \WP_User $to The user switched to.
* @param \WP_User $from The user who is logged in now.
*
* @return void
*/
private function log( string $action, \WP_User $to, \WP_User $from ): void {
do_action( 'adminease_audit_log', 'users', $action, (int) $to->ID, $to->user_login, [
'from' => $from->user_login,
'to' => $to->user_login,
] );
}
}