我目前正在开发一个有3 user_roles的laravel应用程序。
所以每个角色都可以访问他下面的角色。
e.g
超级管理员可以访问管理员和普通用户帐户。
如何允许经过身份验证的超级管理员用户以管理员或普通用户的身份登录,只需单击按钮即可?
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 *******发布于 2017-08-16 07:31:43
阅读这些评论,我认为你想做以下几点:
下面的解决方案都是建立在一个,也许有一些软件包的拉里解决这类问题。
Auth::loginById($otherUserId)可以是一个解决方案:
另一种方法是使用政策
例如,您是用户1,希望在更新函数user/3/profile中编辑用户3的配置文件。您可以调用一个策略函数,检查您的user_role_id是否比其他函数小。然后,记录将被保存,记录器将用您的用户id将其记录下来。
这两种方式各有优缺点。使用id登录将为您提供其他用户的确切视图。但是您必须修改您的记录器(而不是Auth::id(),在会话中使用某些内容)。然后,您可以实现一个小按钮(跳转回自己的配置文件),以登录回您自己的帐户。对于记录器来说,使用策略会更容易,但是在每个部分,您都必须使用策略来实现检查。
不知道你的项目的规模和复杂性,我会建议第一个解决方案。我自己在一个项目中实现了它,但没有记录器功能。
发布于 2018-06-14 08:26:51
您可以使用下列方法登录任何用户
$userId = 1;
Auth::loginUsingId($userId, true);或
$user = User::find(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);
}发布于 2019-02-26 18:25:08
首先,您需要向用户表添加2列:类型(整数1=admin,2=some other)和活动(布尔值1改为true,0 false)
php make:迁移add_cols_to_users_table --table=user
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 x- 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;
}
});https://stackoverflow.com/questions/45705087
复制相似问题