gpt4 book ai didi

php - Laravel 5.3 登录重定向到多个用户的不同页面

转载 作者:可可西里 更新时间:2023-11-01 13:17:19 25 4
gpt4 key购买 nike

我有 Laravel 5.3 和三种不同类型的用户。我希望他们在登录后被重定向到不同的仪表板页面。例如:

user -> login -> user-dashboard

admin -> login -> admin-dashboard

我创建了一个名为 CheckRole 的中间件:

public function handle($request, Closure $next)
{
if($request->user() === null) {
return response("Insufficient Permissions" , 401);
}
$actions = $request->route()->getAction();
$roles = isset($actions['roles']) ? $actions['roles'] : null;

if($request->user()->hasAnyRole($roles) || !$roles) {
return $next($request);
}
return response("Insufficient Permissions" , 401);

}

路线

Route::group(['middleware' => ['auth','roles'], 'roles' => 'Admin'],  function () { 
// Routes here
}

角色运作良好。

现在 loginContoller 中的 redirectTo= ''; 仅指向一个 View 。我检查了文档,我相信这与守卫有关,守卫没有说明如何设置。

我也见过多重身份验证,但我认为为不同的用户创建不同的表并因此寻找替代答案是不明智的。

如有任何建议,我们将不胜感激。

我的表是这样的:

Table users

id | name | email
---------
1 | John | john@blah.com
2 | Michael | michael@blah.com

Table roles

id | name
---------
1 | Admin
2 | PrivilegedMember
3 | Subscriber

Table user_role

id | user_id | role_id
----------------------
1 | 1 | 1
2 | 2 | 2

这可能与以下问题重复,但提供的答案没有解释多重重定向。

Multiple Authentication in Laravel 5.3

最佳答案

在你的 LoginController 中实现一个 authenticated() 方法并在那里添加重定向逻辑:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
use AuthenticatesUsers;

// ...

/**
* The user has been authenticated.
*
* @param \Illuminate\Http\Request $request
* @param mixed $user
*
* @return mixed
*/
protected function authenticated(Request $request, $user)
{
if($user->hasRole('Admin')) {
return redirect()->intended('admin');
}

if ($user->hasRole('PrivilegedMember')) {
return redirect()->intended('PriviligedMember/index');
}
}

// ...
}

该方法在用户通过身份验证后调用。查看 sendLoginResponse 的最后两行:

/**
* Send the response after the user was authenticated.
*
* @param \Illuminate\Http\Request $request
*
* @return \Illuminate\Http\Response
*/
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();

$this->clearLoginAttempts($request);

return $this->authenticated($request, $this->guard()->user())
?: redirect()->intended($this->redirectPath());
}

因此它非常适合此类逻辑。

关于您自己的答案的另一个注释,AuthenticatesUser 是水平扩展 LoginController 的特征,您可以安全地覆盖 Controller 中的任何方法,而无需触及核心文件。

关于php - Laravel 5.3 登录重定向到多个用户的不同页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40048732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com