Allow admin users to see what other user type can

2019-04-14 06:11发布

问题:

I have a Laravel web application consist of 2 types of user:

  1. customer
  2. admin

Base on their user type , they can see, and perform different things.


Customer

When log-in as customer, my customer will see different dashboard.


Admin

When log-in as admin, I can see a list of users in a table

Example,

  1. userA
  2. userB
  3. userC
  4. more …

Goal: I want to see what customer see when click on one of the user on the list.

I couldn’t come up the solution for that.


IMO

Will Auth::user()->type work for this scenario ?

The goal is to render the page as Auth:user()->type == ‘customer’, when the actual Auth::user()->type == ‘admin’. I'm not entirely sure if what I am trying to do is possible.


How would I do something like that in Laravel ?

回答1:

You could try what I did in one of my projects - implementation is pretty simple, maybe you can make use of that as well.

There is additional action in our AuthController that allows a user to switch to other users and remembers current user ID in session:

public function switchUser($userId)
{
    // disallow switched users from switching again
    if (Session::get('previous_user')) App::abort(403);

    $user = User::findOrFail($userId);

    Session::set('previous_user', Auth::id());

    Auth::login($user);

    return redirect('some path');
}

Second part is customized logout function, that for switched users switches them back to their original user account instead of logging out:

public function getLogout()
{
    if ($previousUser = Session::get('previous_user')) {
        Session::remove('previous_user');
        Auth::loginUsingId($previousUser);

        return redirect('some path');
    }

    Auth::logout();

    return redirect('some path');
}

With that logic you'll be able to switch to other users and back. You might need to add permission checking, so that only admins can do that etc., link the customers in the list to the switch URL, anyway the core of the functionality is there in the code above.