【问题标题】:Checking the user's role in Laravel在 Laravel 中检查用户的角色
【发布时间】:2019-06-07 03:15:53
【问题描述】:

我是 Laravel 的初学者。 我在 Laravel 5.8 中有项目。

我有这个代码:

中间件:

class CheckRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $role)
    {
        if (! $request->user()->hasRole([$role])) {
            if( $role == 'admin' || $role== 'receptionist' || $role == 'adminCompany' || $role == 'telemarketer')
            {
                return redirect('/cms');
            }
            else
            {
                return redirect()->route('index');
            }

        }

        return $next($request);
    }
}

播种机:

public function run()
    {
        DB::table('roles')->insert([
            'name' => 'admin'
        ]);
        DB::table('roles')->insert([
            'name' => 'adminCompany'
        ]);

        DB::table('roles')->insert([
            'name' => 'telemarketer'
        ]);

        DB::table('roles')->insert([
            'name' => 'receptionist'
        ]);

        DB::table('roles')->insert([
            'name' => 'user'
        ]);

        DB::table('roles')->insert([
            'name' => 'userPremium'
        ]);

        DB::table('roles')->insert([
            'name' => 'userCompany'
        ]);

        DB::table('roles')->insert([
            'name' => 'userSponsor'
        ]);

        DB::table('roles')->insert([
            'name' => 'userGuest'
        ]);

    }

架构:

Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->engine = "InnoDB";
        });

还有我的 web.php:

Route::group(['prefix' => 'admin'], function () {
    Route::get('/', 'BackendController@index')->name('adminHome')->middleware('CheckRole:user,CheckRole:userPremium,CheckRole:userCompany,CheckRole:userSponsor,CheckRole:userGuest');
});

用户.php

public function hasRole(array $roles)
    {

        foreach ($roles as $role) {

            if (isset(self::$roles[$role])) {
                if (self::$roles[$role]) return true;

            } else {
                self::$roles[$role] = $this->roles()->where('name', $role)->exists();
                if (self::$roles[$role]) return true;
            }

        }
        return false;
    }

我希望 CheckRole 中间件检查用户是否具有以下角色:用户、userPremium、userCompany、userSponsor、userGuest 用于路由 adminHome。目前,Laravel 只检查 1 个角色——不是全部。

如何修复?

【问题讨论】:

  • 您是否使用角色包?
  • 不,我使用我的代码
  • 可以显示用户类hasRole方法吗?
  • 是的,我将其添加到主帖

标签: php laravel laravel-5


【解决方案1】:

你应该用 分隔你的中间件参数,而不是重复请求到同一个中间件

同样的问题 看: How to pass multiple parameters to middleware with OR condition in Laravel 5.2

您可以将https://github.com/spatie/laravel-permission 视为权限包。

Route::group(['prefix' => 'admin'], function () {
    Route::get('/', 'BackendController@index')->name('adminHome')->middleware('CheckRole:user,userPremium,userCompany,userSponsor,UserGuest');
});

就像我在上面发布的文章中一样,您需要处理中间件参数,

作为另一个答案的例子,像这样

/**
 * Handle an incoming request.
 *
 * @param $request
 * @param Closure $next
 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
 */
public function handle($request, Closure $next) {

    $roles = array_slice(func_get_args(), 2); // [default, admin, manager]

    foreach ($roles as $role) {

        try {

            Role::whereName($role)->firstOrFail(); // make sure we got a "real" role

            if (Auth::user()->hasRole($role)) {
                return $next($request);
            }

        } catch (ModelNotFoundException $exception) {

            dd('Could not find role ' . $role);

        }
    }

    Flash::warning('Access Denied', 'You are not authorized to view that content.'); // custom flash class

    return redirect('/');
}

在 laravel 5.8 中,您可能可以像数组一样访问您的 $role 或者你应该检查它是一个数组还是字符串,然后循环遍历它们

使用 func_get_args() 看起来更干净

【讨论】:

  • “你应该用 分隔你的中间件参数,而不是重复请求到同一个中间件” - 怎么做?
  • @trafficker,我刚刚用示例编辑了我的答案,请参阅 ->middleware() 调用
  • 'CheckRole:user,userPremium,userCompany,userSponsor,UserGuest' 这不起作用:(
  • @trafficker ,阅读我发布的文章,您也没有在中间件中处理您的参数。
猜你喜欢
  • 2016-08-28
  • 1970-01-01
  • 2022-10-16
  • 2014-01-14
  • 1970-01-01
  • 2015-03-30
  • 2020-08-04
  • 2011-11-05
  • 1970-01-01
相关资源
最近更新 更多