'Laravel login as another user
I am currently developing a laravel app where there are 3 user_roles
- Superadmin
- Admin
- Normal
So each role can access the roles below him.
e.g
Superadmins can access admins and normal users account.
How do I allow a authenticated superadmin user to log in as an admin or normal user with a click of a button?
USER_ROLES TABLE
id name
1 superadmin
2 admin
3 normal
----------------------------
USERS TABLE
id first_name last_name user_role_id password
1 john doe 1 *******
2 jane doe 2 *******
3 cassie snow 3 *******
4 sansa stark 3 *******
Solution 1:[1]
You can use the following methods to log in any user
$userId = 1;
Auth::loginUsingId($userId, true);
or
$user = User::find(1);
Auth::login($user);
If you have set up roles in your user model you could use something like
//check if the current user is superadmin
$userRoles = Auth::user()->getRoleNames()->toArray();
if (in_array('superadmin', $userRoles)) {
//login the user
Auth::login($user);
}
Solution 2:[2]
First you need add 2 columns to user table: type(integer 1=admin, 2=some other) and active (boolean 1 to true and 0 false)
php artisan make:migration add_cols_to_users_table --table=users
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->integer('type')->default(0);
$table->boolean('active')->default(0);
});
}
public function down()
{
Schema::table('users', function ($table) {
$table->dropColumn(['type', 'active']);
});
}
}
link on some page
<a href="{{ url('impersonate') }}/{{ $user->id }}" class="btn btn-success">Enter as {{$user->name}}</a>
someUserController.php:
use Illuminate\Support\Facades\Auth;
class someUserController extends Controller
{
public function __construct()
{
$this->middleware('auth');
$id = Auth::id();
$user = User::find($id);
//echo '<pre>ID:'.$id.' - '.print_r($user,1); die();
if($user->type !== 1) //1 for type admin
{
echo ' error not admin (nice try!).';
die();
}
}
public function impersonate($id)
{
Auth::logout(); // for end current session
Auth::loginUsingId($id);
return redirect()->to('get-dashboard');
}
}
routes.php | web.php
Route::get('/impersonate/{id}', 'someUserController@impersonate');
Route::get('get-dashboard', function () {
$id = \Illuminate\Support\Facades\Auth::id();
$user = \App\User::find($id);
//echo '<pre>'.print_r($user,1); die();
if(!$user->active) return redirect('404-page');
switch($user->type)
{
case 1: return redirect('x-url-dashboard-1'); break;
case 2: return redirect('x-url-dashboard-2'); break;
case 3: return redirect('x-url-dashboard-3'); break;
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cmac |
| Solution 2 |
