我目前正在开发一个laravel应用程序,其中有3个user_roles
所以每个角色都可以访问他下面的角色。
e.g
Superadmins可以访问管理员和普通用户帐户。
如何通过单击按钮允许经过身份验证的超级管理员用户以管理员或普通用户身份登录?
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 *******
阅读评论我认为你想做以下事情:
以下解决方案是内置的,也许有一些laravel包可以解决这类问题。
Auth::loginById($otherUserId)可能是一个解决方案:
另一种方法是使用Policies
例如您是用户1,并希望在更新功能user/3/profile
中编辑用户3的配置文件。您可以调用策略函数来检查user_role_id是否小于其他用户。然后记录将被保存,记录器将使用您的用户ID将其记录下来。
两种方式都有利有弊。使用id登录将为您提供其他用户的确切视图。但是你必须修改你的记录器(而不是Auth :: id()使用会话的东西)。然后,您可以实现一个小按钮(跳回自己的个人资料)以登录您自己的帐户。使用策略对于记录器来说会更容易,但是在每个部分都必须使用策略实施检查。
不知道项目的大小和复杂性,我建议第一个解决方案。我自己在一个项目中实现了它,但没有记录器功能。
您可以使用以下方法登录任何用户
$userId = 1;
Auth::loginUsingId($userId, true);
要么
$user = User::where('id',1);
Auth::login($user);
如果您在用户模型中设置了角色,则可以使用类似的功能
//check if the current user is superadmin
$userRoles = Auth::user()->getRoleNames()->toArray();
if (in_array('superadmin', $userRoles)) {
//login the user
Auth::login($user);
}
首先,您需要向用户表添加2列:type(integer 1 = admin,2 = some other)和active(boolean 1 to true和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']);
});
}
}
在某些页面上链接
<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;
}
});