检查用户在Laravel中的角色

时间:2019-06-06 18:12:02

标签: php laravel laravel-5

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

我有此代码:

Middleweare:

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');
});

User.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中间件检查用户是否具有以下角色:adminadmin的用户,userPremium,userCompany,userSponsor,userGuest。目前,Laravel仅检查1个角色-并非全部。

如何维修?

1 个答案:

答案 0 :(得分:2)

您应该使用分隔中间件的参数,而不是重复请求相同的中间件

同一问题在这里 看到: 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()