Laravel 8:中间件角色

Laravel 8: Middleware Roles

当有人注册时,他们可以直接注册为个人资料或企业 select。从我下面的代码中,我如何创建中间件,以便个人资料用户无法访问业务仪表板并且业务用户无法访问个人资料仪表板?我如何保护这些页面?

2014_10_12_000000_create_users_table.php

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('account_type');
    $table->string('first_name');
    $table->string('last_name');
    $table->string('username')->unique();
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('phone');
    $table->string('address', 50);
    $table->string('city', 25);
    $table->char('state', 2);
    $table->char('zip', 10);
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

RegisterController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class RegisterController extends Controller
{
    public function index()
    {
        return view('auth.register');
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'account_type' => 'required|not_in:0',
            'first_name' => 'required|max:255',
            'last_name' => 'required|max:255',
            'username' => 'required|max:15|unique:users',
            'email' => 'required|email|unique:users',
            'phone' => 'required|max:255|digits:10',
            'address' => 'required|max:255',
            'city' => 'required|max:20',
            'state' => 'required|not_in:0',
            'zip' => 'required|regex:/\b\d{5}\b/',
            'password' => 'required|string|confirmed|min:8',
        ]);

        User::create([
            'account_type' => $request->account_type,
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'username' => $request->username,
            'email' => $request->email,
            'phone' => $request->phone,
            'address' => $request->address,
            'city' => $request->city,
            'state' => $request->state,
            'zip' => $request->zip,
            'password' => Hash::make($request->password),
        ]);

        Auth::attempt([
            'email' => $request->email,
            'password' => $request->password,
        ]);

        // Redirect to dashboards based on registers account type
        if(Auth::user()->account_type == 'profile'){
            return redirect()->route('dashboard_profile');
        } else {
            return redirect()->route('dashboard_business');
        }
    }
}

BusinessDashboardController.php

class BusinessDashboardController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    
    public function index()
    {        
        return view('auth.dashboard_business');
    }
}

ProfileDashboardController.php

class ProfileDashboardController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return view('auth.dashboard_profile');
    }
}

我想学习如何不使用软件包。

1- 运行 :

php artisan make:middleware AccountType

2- 通过打开 app/Http/Kernel.php:

将其添加到内核文件中的 routeMiddleware 数组
'accType' => \App\Http\Middleware\AccountType::class,

3- 编辑 AccountType 文件:

public function handle($request, Closure $next)
{
 // If user account type is profile allow to next or else block the request
     if (Auth::user() &&  Auth::user()->account_type == 'profile') {
            return $next($request);
     }else{
      abort(403, 'Unauthorized action.'); 
     }        
}

4- 将中间件应用于您的路由:

Route::get('/profile', ['middleware' => 'accType', function () {
    //
}]);

如果你想要一个多重认证系统,具有不同的逻辑,最好实现多重保护并在你想要的模型中定义它们:

[...]
'guards' => [
    [...]
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    'writer' => [
        'driver' => 'session',
        'provider' => 'writers',
    ],
],
[...]

  [...]
'providers' => [
    [...]
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\BusinessDashboard::class,
    ],
    'writers' => [
        'driver' => 'eloquent',
        'model' => App\ProfileDashboard::class,
    ],
],
[...]

您可以在下面的代码中找到完整的指南文章:
enter link description here

除了@nagidi 给出的解决方案外,您还可以更新middleware 处理条件以检查account_type 是个人资料还是业务。

public function handle($request, Closure $next, $type)
    {

     if (Auth::user() &&  Auth::user()->account_type == $type) {
            return $next($request);
     }
      abort(403, 'Unauthorized action.');
    }
Route::get('/business-profile', ['middleware' => 'accType:business', function () {
    //
}]);
Route::get('/profile', ['middleware' => 'accType:profile', function () {
    //
}]);

如何在 Laravel

中为多用户角色创建自己的中间件

假设您的角色数组可以是 ["admin","student","staff"];

创建一个中间件角色来检查角色“admin”。为每个角色重复步骤 1-4。

我发现这对我自己来说容易多了,其他人可能有自己的方法

步骤 1 运行 artisan 命令

php artisan make:middleware isAdmin

步骤 2

App/Http/Middlewere/isAdmin.php

    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Auth;
    class isAdmin
    {
         public function handle(Request $request, Closure $next,$is_admin)
        {
            
            $role=Auth::user()->role;
            //Get the role list
            $role_array=explode(",",$role); 
            if (in_array($is_admin, $role_array)) {
            return $next($request);
          }        
           //if not allowed redirect to home page with message
     $message="Unauthorized action.";
//return response($message, 401);//if you have friendly 401 page 


//otherwise I think is a best to return to home page                
                $request->session()->flash('error', $message);
                return redirect()->route('home');
            }
        }

步骤 3

App/Http/Kernel.php

protected $routeMiddleware = [
'isAdmin' => \App\Http\Middleware\isAdmin::class,
];

步骤 4

现在在您的路由控制器中添加此行以仅允许具有管理员角色的用户

public function __construct()
    {
         //ONLY ADMIN CAN ACCESS THIS ROUTE
        $this->middleware('isAdmin:admin'); 
        //$this->middleware('isStudent:student');        
        //$this->middleware('isStaff:staff'); 
}