Laravel 5.3 登录重定向到多个用户的不同页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40048732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5.3 Login redirect to different pages for multiple users
提问by avinash
I have Laravel 5.3 with three different types of users. I want them to be redirected to different dashboard pages after logging in. For example:
我的 Laravel 5.3 有三种不同类型的用户。我希望它们在登录后被重定向到不同的仪表板页面。例如:
user -> login -> user-dashboard
admin -> login -> admin-dashboard
用户 -> 登录 -> 用户仪表板
管理员 -> 登录 -> 管理员仪表板
I have created a middleware called CheckRole
:
我创建了一个名为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);
}
Routes
路线
Route::group(['middleware' => ['auth','roles'], 'roles' => 'Admin'], function () {
// Routes here
}
Roles are working perfectly.
角色工作得很好。
Now redirectTo= '';
in the LoginContoller
points to one view only. I have checked the documentation and I believe this has something to do with guards which have no explanation on how to set it up.
现在,redirectTo= '';
在LoginContoller
点一个只能查看。我检查了文档,我相信这与没有解释如何设置它的守卫有关。
I have also seen multiauth, but I do not think it is wise to create different tables for different users and hence looking for an alternate answer.
我也见过多重身份验证,但我认为为不同的用户创建不同的表并因此寻找替代答案是不明智的。
Any Suggestion would be appreciated.
任何建议将不胜感激。
My tables are like:
我的表是这样的:
Table users
id | name | email
---------
1 | John | [email protected]
2 | Michael | [email protected]
Table roles
id | name
---------
1 | Admin
2 | PrivilegedMember
3 | Subscriber
Table user_role
id | user_id | role_id
----------------------
1 | 1 | 1
2 | 2 | 2
This might be a duplicate of the below question but the answer provided leaves without explaining multiple redirections.
这可能是以下问题的重复,但提供的答案没有解释多次重定向。
采纳答案by sepehr
Implement an authenticated()
method in your LoginController
and add the redirection logic there:
authenticated()
在您的方法中实现一个方法LoginController
并在那里添加重定向逻辑:
<?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');
}
}
// ...
}
The method is called after the user is authenticated. See the last two lines of sendLoginResponse
:
该方法在用户通过身份验证后调用。见最后两行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());
}
So it's a perfect candidate for such logics.
所以它是这种逻辑的完美候选者。
One other note on your own answer, the AuthenticatesUser
is a trait that horizontally extends the LoginController
, you can safely override any of its methods in your controller without touching the core files.
关于您自己的答案的另一个注意事项,AuthenticatesUser
是水平扩展 的特征LoginController
,您可以安全地覆盖控制器中的任何方法,而无需触及核心文件。
回答by Yefferson Marín
The best way (that I've found) to do that is using Traits. What are we going to do is bassically the same but less complicated and more structured:
最好的方法(我发现)是使用Traits。我们要做的是基本相同但不那么复杂和更有条理:
1.Instead of creating two tables, our User Model will have a role field, in my case I'll have: 'admin', 'employee' and 'user'.
1.我们的用户模型将有一个角色字段,而不是创建两个表,在我的情况下,我将拥有:'admin'、'employee' 和 'user'。
2.We are going to create a Traits Folder, in this case it will be placed in App/Http
.
2.我们将创建一个 Traits 文件夹,在本例中它将被放置在App/Http
.
3.We are going to create a new file and call it RedirectTrait.php
inside that folder with this content:
3.我们将创建一个新文件并RedirectTrait.php
在该文件夹中使用以下内容调用它:
<?php
namespace App\Http\Traits; // Or the place where the trait is stored (step 2)
use Illuminate\Http\Request;
trait RedirectTrait
{
/**
* Where to redirect users after register/login/reset based in roles.
*
* @param \Iluminate\Http\Request $request
* @param mixed $user
* @return mixed
*/
public function RedirectBasedInRole(Request $request, $user) {
$route = '';
switch ($user->role) {
# Admin
case 'admin':
$route = '/admin/dashboard/route'; // the admin's route
break;
# Employee
case 'employee':
$route = '/employee/dashboard/route'; // the employee's route
break;
# User
case 'user':
$route = '/user/dashboard/route'; // the user's route
break;
default: break;
}
return redirect()->intended($route);
}
}
As you can see, we can 'play' with the redirections, but intended is necessary According laravel documentation:
如您所见,我们可以“玩”重定向,但意图是必要的根据 laravel 文档:
The intended method on the redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware. A fallback URI may be given to this method in case the intended destination is not available.
重定向器上的预期方法将用户重定向到他们在被身份验证中间件拦截之前尝试访问的 URL。如果预期目的地不可用,则可以为此方法提供后备 URI。
4.Finally, we'll place the trait and call it:
4.最后,我们将放置 trait 并调用它:
- In the
App/Http/Controllers/Auth/LoginController.php
file
- 在
App/Http/Controllers/Auth/LoginController.php
文件中
use Illuminate\Http\Request; // Add
use App\Http\Traits\RedirectTrait; // Call the trait
class LoginController extends Controller
{
...
use RedirectTrait; // Use the trait
/**
* The user has been authenticated.
*
* @param \Illuminate\Http\Request $request
* @param mixed $user
* @return mixed
*/
protected function authenticated(Request $request, $user)
{
return $this->RedirectBasedInRole($request, $user);
}
...
}
We're overwriting the 'authenticated' method placed in Illuminate\Foundation\Auth\AuthenticatesUsers
(which is empty by the way)
我们正在覆盖放置的“经过身份验证”的方法Illuminate\Foundation\Auth\AuthenticatesUsers
(顺便说一下,它是空的)
- We'll do the same in the
App/Http/Controllers/Auth/RegisterController.php
file, but the method will have a different name naturally:
- 我们将在
App/Http/Controllers/Auth/RegisterController.php
文件中做同样的事情,但该方法自然会有不同的名称:
/**
* The user has been registered.
*
* @param \Illuminate\Http\Request $request
* @param mixed $user
* @return mixed
*/
protected function registered(Request $request, $user)
{
return $this->RedirectBasedInRole($request, $user);
}
We're overwriting the 'redirected' method stored in Illuminate\Foundation\Auth\RegistersUsers
, and is empty as well.
我们正在覆盖存储在 中的“重定向”方法Illuminate\Foundation\Auth\RegistersUsers
,并且它也是空的。
5.Enjoy :D
5.享受 :D
PS.The reset password redirect is another history.
附注。重置密码重定向是另一个历史。
回答by avinash
It looks like the below solution over rides the process and does the job. But I do not think it is the right way as we are tinkering with Core files. Some body please throw a light on this.
看起来下面的解决方案超越了这个过程并完成了工作。但我不认为这是正确的方法,因为我们正在修补 Core 文件。请某些机构对此有所了解。
Go to AuthenticatesUser.php trait.
转到 AuthenticatesUser.php 特性。
locate SendLoginResponse(Request $request)
找到 SendLoginResponse(Request $request)
Before returning the default path add your conditions.I have changed it to below
在返回默认路径之前添加您的条件。我已将其更改为以下
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
if(Auth::User()->hasRole('Admin')) {
return redirect()->intended('admin');
} elseif (Auth::User()->hasRole('PrivilegedMember')) {
return redirect()->intended('PriviligedMember/index');
}
return $this->authenticated($request, $this->guard()->user())
?: redirect()->intended($this->redirectPath());
}