即使用户在laravel 5.7中被授权也禁止页面

时间:2018-11-30 09:12:19

标签: php mysql nginx laravel-5 laravel-authorization

我正在使用laravel 5.7 Gate和网站授权策略。我已按照以下步骤进行操作,但是即使用户在角色表中具有权限,也不允许使用Page。 在我的系统中,我有3个主要角色,分别是Super Admin,Admin,Guest。他们具有不同的权限作为附件图像。 Roles and Permissions。 请帮助我解决此问题。

web.php

Route::get('/users', 'UserController@index')->name('users')->middleware('can:view-user');

AuthServiceProvide.php

public function boot()
{
    $this->registerPolicies();
    $this->registerPostPolicies();   
}

public function registerPostPolicies()
{
    Gate::define('view-user', function($user){
        $user->hasAccess(['view-user']);
    });

    Gate::define('activate-user', function($user){
        $user->hasAccess(['activate-user']);
    });
}

角色模型

public function hasAccess(array $permissions)
{
    foreach($permissions as $permission){
        if($this->hasPermission($permission)){
            return true;
            echo("<script>console.log('PHP: ".$permissions."');</script>");
        }
    }
    return false;
}

protected function hasPermission(string $permission){
    $permissions = json_decode($this->permissions,true);
    return $permissions[$permission]??false;

}   

用户模型中的角色和hasAction功能

public function roles()
{
    return $this->belongsToMany(Role::class, 'roles_users');
}

public function hasAccess(array $permissions)
{
   foreach($this->roles as $role){
        if($role->hasAccess($permissions)){
            return true;
        }
   }
   return false;
}

角色播种机

use Illuminate\Database\Seeder;
Use App\Role;
class rolerSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $super_admin = Role::create([
            'name'        => 'Super Admin',
            'slug'        => 'super admin',
            'permissions' => json_encode([
                'create-user' => true,
                'update-user' => true,
                'update-user' => true,
                'activate-user' => true,
                'view-user'  => true,

            ]),
        ]);
        $admin = Role::create([
            'name'        => 'Admin',
            'slug'        => 'admin',
            'permissions' => json_encode([
                'view-user'  => true,
            ]),
        ]);

        $guest = Role::create([
            'name'        => 'Guest',
            'slug'        => 'guest',
            'permissions' => json_encode([
                'view-user'  => true,
            ]),
        ]);
    }
}

并且代码编写如下教程 link to tutorial

0 个答案:

没有答案