首页 > 解决方案 > Laravel:如何确保用户在注册和登录后进入角色特定的主页视图?

问题描述

我在 laravel-5.8 中为一个大学网站创建了一个自定义的多身份验证系统,每个用户都注册一个特定的角色:管理员、教师或 HOD(部门主管)。

我正在使用我们在运行后获得的控制器和视图

php artisan make:auth

注册后,所有用户都将重定向到默认主页,无论其角色如何。这 3 个角色在用户表中存储为角色列下的 0、1 和 2。我修改了默认提供的用户表。

我的登录机制运行良好。用户被重定向到其角色的主页。这是我的做法:

登录控制器.php

public function login(Request $request){
if(Auth::attempt(['PID' => $request->PID, 'password' => $request->password])){

    $user = User::where('PID',$request->PID)->first();

    if($user->role == '0'){
        return redirect('home');
    }
    else{
        if($user->role == '1'){
            return redirect('hodhome');
        }
        else{
            return redirect('adminhome');
        }
    }
}
return redirect()->back();
}

这是来自login.blade.php的 POST 请求所使用的路由

Route::post('/login/custom', 'auth\LoginController@login')->name('login.custom');

但是每次我注册一个新用户时,它都会将用户带到教师主页路径,即使他们是管理员或 HOD。这是注册机制:

RegisterController.php (下面只展示相关函数)

use RegistersUsers;
protected $redirectTo = '/home';
public function __construct()
{
    $this->middleware('guest');
}
//validator function and create function after this line

我试图通过这样做使其正常工作:将变量更改redirectTo为函数。//一个想法:替换“protected $redirectTo = '/home';” 经过...

protected function redirectTo(array $data){
    if($data['role']=='0'){ return redirect('home'); }
    elseif($data['role']=='1'){ return redirect('hodhome'); }
    else return redirect('adminhome');
}

但它不起作用,因为我似乎错过了一些东西。

另一个令人沮丧的是,用户登录后可以访问其他角色的主页。在middleware('auth')我的路线中有助于防止在未登录时访问 URL,但它不会阻止已登录的用户访问其他主页。

以下是到主页的路线:

Auth::routes();

//-------------------MULTI AUTH SYSTEM------------------------------------------

Route::post('/login/custom', 'auth\LoginController@login')->name('login.custom');

Route::get('/home', 'HomeController@index')->name('home');

route::get('/adminhome', function () {
    return view('adminhome');
})->middleware('auth');

route::get('/hodhome', function () {
    return view('hodhome');
})->middleware('auth');
//----------------------------------------------------------------------------

默认welcome.blade.php也将登录的用户重定向到教师的主页:

@if (Route::has('login'))
        <div class="top-right links">
            @auth
                <a href="{{ url('/home') }}">Home</a>
            @else
                <a href="{{ route('login') }}">Login</a>

                @if (Route::has('register'))
                    <a href="{{ route('register') }}">Register</a>
                @endif
            @endauth
        </div>
    @endif

  1. 如何确保用户在新注册和登录时访问正确的主页?
  2. 如何确保一个角色的主页无法访问其他角色?

编辑1:

合并@N69S 建议的更改后,发生了以下情况:

该解决方案奏效了。但是当试图非法访问 URL 时,就会产生错误。但相反,用户被发送到欢迎页面。这个页面的右上角只有一个链接,叫做“HOME”。当管理员或 HOD 用户登录时,此链接不起作用,因为它路由到'/home'如下所示:

//welcome.blade.php
<body>
    <div class="flex-center position-ref full-height">
        @if (Route::has('login'))
            <div class="top-right links">
                @auth
                    <a href="{{ url('/home') }}">Home</a>
                @else
                    <a href="{{ route('login') }}">Login</a>

                    @if (Route::has('register'))
                        <a href="{{ route('register') }}">Register</a>
                    @endif
                @endauth
            </div>
        @endif

        <div class="content">
            <div class="title m-b-md text-center">
                COLLEGE ADMINISTRATION <br> SYSTEM
            </div>
        </div>
    </div>
</body>

如何更改此视图文件以将登录用户发送到其角色的 HOME?

标签: laravellaravel-authorizationlaravel-5.8laravel-authentication

解决方案


一种完整且正确的解决方案是分离实体(HOD、Admin、User)并为每个实体配置身份验证(auth:hod、auth:admin、auth)

另一种解决方案是制作 3 个单独的中间件,并相应地将您的路由与其中一个进行分组。

顺便说一句,redirectTo()方法不带参数。从Illuminate\Foundation\Auth\RedirectsUsers特质

/**
 * Get the post register / login redirect path.
 *
 * @return string
 */
public function redirectPath()
{
    if (method_exists($this, 'redirectTo')) {
        return $this->redirectTo();
    }

    return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
}

- - - - - - - -编辑

对于 3 中间件解决方案,可以使用命令php artisan make:middleware Admin,这将创建 Class 文件app/Http/ Middleware/Admin.php

在该handle方法中,您可以执行类似的操作

public function handle($request, Closure $next)
{
    if(auth()->user() && auth()->user()->role == 2){
        return $next($request);
    }
    return redirect(‘login’)->with(‘error’,’You have not admin access’);
}

对 HOD 做同样的事情

要像auth在路由中一样使用它,请在内核App\Http\Kernel.php中添加中间件$routeMiddleware

protected $routeMiddleware = [
    //....,
    //....,
    'admin' => \App\Http\Middleware\Admin::class,
];

推荐阅读