How can I allow access to two user accounts using one login?

I have spent the last two hours searching for this and I cannot find a solution to my problem.

I have a WP site with WooCommerce running which allows to users to create their own store.

My client has a scenario he needs two stores, but without having to login and logout every time to check this data.

I've already checked "User Switching" but its functionality is limited.

  1. It only allows you to switch to a user from the backend, which doesn't help because the access to WP Dashboard is locked.
  2. I found a repo which adds User Switch to the WP Admin bar. The WP Admin bar though is not visible to users. Even if I keep the bar open the problem is that it allows you to search through all users and get access to any account you want, but I need the user to be able to only switch between specific accounts.

I searched for other solutions but I cannot find anything out there.

Any suggestions would be greatly appreciated!

Topic woocommerce-offtopic switch user-access login Wordpress

Category Web


I would reverse engineer the User Switching plugin and then create a solution that works for you. Fortunately there is not a whole lot of work to do. Most of the crucial functionality is in this function:

function switch_to_user( $user_id, $remember = false, $set_old_user = true ) {
    if ( ! $user = get_userdata( $user_id ) ) {
        return false;
    }

    $old_user_id = get_current_user_id();

    if ( $set_old_user && $old_user_id ) {
        user_switching_set_olduser_cookie( $old_user_id );
    } else {
        user_switching_clear_olduser_cookie( false );
    }

    wp_clear_auth_cookie();
    wp_set_auth_cookie( $user_id, $remember );
    wp_set_current_user( $user_id );

    if ( $set_old_user ) {
        do_action( 'switch_to_user', $user_id, $old_user_id );
    } else {
        do_action( 'switch_back_user', $user_id, $old_user_id );
    }

    return $user;
}

You could just maintain a list of "linked accounts" for each user to determine if a user is allowed to switch to another account.

Pseudo code:

$switch_to = 0; // some user id
$linked_accounts = get_linked_accounts( get_current_user_id() );
if(in_array($switch_to, $linked_accounts)) {
    switch_to_user($switch_to)
}

You would need to define get_linked_accounts and setup a way to actually do the linking. You should also do a lot of testing to make sure users will not be able to switch to any arbitrary account.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.